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/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Groovy | Groovy |
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
def number = rand.nextInt(range.size()) + range.from // get a random number in the range
println "The number is in ${range.toString()}" // print the range
def guess
while (guess != number) { // keep running until correct guess
... | Give a code snippet in #Groovy
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Ioke | Ioke | Camera = Origin mimic
MobilePhone = Origin mimic
CameraPhone = Camera mimic mimic!(MobilePhone) | Give a code snippet in #Ioke
Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePho... | 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 ... | #Nemerle | Nemerle | System.Console.Error.WriteLine("Goodbye, World!"); | Give a code snippet in #Nemerle
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 ou... | 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 |... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: showComparisons (in string: a, in string: b) is func
begin
writeln("compare " <& literal(a) <& " with " <& literal(b) <&":");
writeln("a = b returns: " <& a = b);
writeln("a <> b returns: " <& a <> b);
writeln("a < b returns: " <& a < b);
writeln("a > b r... | Give a code snippet in #Seed7
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Object_Pascal | Object Pascal |
type
Tanimal = class
public
procedure bark(); virtual; abstract;
end;
implementation
var
animal: Tanimal;
initialization
animal := Tanimal.Create;
animal.bark(); // abstract method call exception at runtime here
animal.Free;
end.
| Give a code snippet in #Object_Pascal
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Priority_queue
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
( )
( 3 "Clear drains" ) 0 put ( 4 "Feed cat" ) 0 put ( 5 "Make tea" ) 0 put ( 1 "Solve RC tasks" ) 0 put ( 2 "Tax return" ) 0 put
sort pop swap print pstack
| Give a code snippet in #Phixmonti
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #Maxima | Maxima | /* Maxima has inf (positive infinity) and minf (negative infinity) */
declare(x, real)$
is(x < inf);
/* true */
is(x > minf);
/* true */
/* However, it is an error to try to divide by zero, even with floating-point numbers */
1.0/0.0;
/* expt: undefined: 0 to a negative exponent.
-- an error. To debug this t... | Give a code snippet in #Maxima
Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #E | E | require(a == 42) # default message, "Required condition failed"
require(a == 42, "The Answer is Wrong.") # supplied message
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure | Give a code snippet in #E
Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Perl | Perl | sub damm {
my(@digits) = split '', @_[0];
my @tbl =([< 0 3 1 7 5 9 8 6 4 2 >],
[< 7 0 9 2 1 5 4 8 6 3 >],
[< 4 2 0 6 8 7 1 3 5 9 >],
[< 1 7 5 0 9 8 3 4 2 6 >],
[< 6 1 2 3 0 4 5 9 7 8 >],
[< 3 6 7 4 2 0 9 5 8 1 >],
[< 5 8 6 9 7 2... | Give a code snippet in #Perl
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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 ... | #Ruby | Ruby | class Foodbox
def initialize (*food)
raise ArgumentError, "food must be eadible" unless food.all?{|f| f.respond_to?(:eat)}
@box = food
end
end
class Fruit
def eat; end
end
class Apple < Fruit; end
p Foodbox.new(Fruit.new, Apple.new)
# => #<Foodbox:0x00000001420c88 @box=[#<Fruit:0x00000001420cd8>, #... | Give a code snippet in #Ruby
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 th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity | Abelian sandpile model/Identity | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by a... | #Nim | Nim |
import sequtils
import strutils
type SandPile = array[3, array[3, int]]
#---------------------------------------------------------------------------------------------------
iterator neighbors(i, j: int): tuple[a, b: int] =
## Yield the indexes of the neighbours of cell at indexes (i, j).
if i > 0:
yield... | Give a code snippet in #Nim
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never gener... | #zkl | zkl | while(1){n:=(0).random(20); n.print(" ");
if (n==10){ println(); break; } (0).random().println();
} | Give a code snippet in #zkl
Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #F.23 | F# | open System
[<EntryPoint>]
let main args =
let s = "hello"
Console.Write(s)
Console.WriteLine(" literal")
let s2 = s + " literal"
Console.WriteLine(s2)
0 | Give a code snippet in #F.23
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string lite... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #Befunge | Befunge | 00p10p20p30p&>40p&>50p60p>$#v~>:55+-vv+`1:%3:+*g04p03< >3/"P"%\56v>p\56*8*/8+:v
v5\`\"~"::-*3p06!:!-+67:_^#!<*<!g06!<>1+70g*\:3/"P"%v^ ^::+*g04%<*0v`1:%3\gp08<
>6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v
>%#74#<-!!70p 00g::1+00p:20g\-:0`*+20p10g::30g\-:0`*+^ ^2+2+g03*<*:v+g06p09:%2<
... | Give a code snippet in #Befunge
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #Oforth | Oforth | : luhnTest(n)
| s i |
n asString reverse ->s
0 s size loop: i [
i s at asDigit
i isEven ifTrue: [ 2 * dup 10 >= ifTrue: [ 9 - ] ] +
]
10 mod ==0 ; | Give a code snippet in #Oforth
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Genie | Genie | [indent=4]
/*
Logical operations in Genie
valac logicals.gs
./logicals true false
*/
def logicals(a:bool, b:bool)
print @"$a and $b is $(a and b)"
print @"$a or $b is $(a or b)"
print @"not $a is $(not a)"
init
a:bool = bool.parse(args[1])
b:bool = bool.parse(args[2])
logicals(a, b) | Give a code snippet in #Genie
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Bounded | Knapsack problem/Bounded | A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th... | #Crystal | Crystal | record Item, name : String, weight : Int32, value : Int32, count : Int32
record Selection, mask : Array(Int32), cur_index : Int32, total_value : Int32
class Knapsack
@threshold_value = 0
@threshold_choice : Selection?
getter checked_nodes = 0
def knapsack_step(taken, items, remaining_weight)
if taken.... | Give a code snippet in #Crystal
A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg w... | 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)
... | #Gambas | Gambas | Public Sub Main()
Dim siCount As Short
Dim sText As String
For siCount = 1 To 100
sText = ""
If siCount Mod 3 = 0 Then sText = "Fizz"
If siCount Mod 5 = 0 Then sText = "Buzz"
If siCount Mod 15 = 0 Then sText = "FizzBuzz"
If sText Then Print sText Else Print siCount
Next
End | Give a code snippet in #Gambas
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 FizzBuz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, sho... | #Raku | Raku | my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close-by-the-king's-castle-lay-a-great-dark
forest, and under an old lime-tree in th... | Give a code snippet in #Raku
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task als... | #Jsish | Jsish | /* Loops/Nested in Jsish */
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
var ncols = Math.floor(Math.random() * 6) + 6;
var matrix = new Array(nrows).fill(0).map(function(v, i, a):array { return new Array(ncols).fill(0); } );
var i,j;
for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) matrix[i... | Give a code snippet in #Jsish
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is me... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere wi... | #FreeBASIC | FreeBASIC | ' version 16-03-2017
' compile with: fbc -s gui
Const As ULong w = 400
Const As ULong w1 = w -1
Dim As Long x, y, lastx, lasty
Dim As Long count, max = w * w \ 4
ScreenRes w, w, 8 ' windowsize 400 * 400, 8bit
' hit any key to stop or mouseclick on close window [X]
WindowTitle "hit any key to stop and close the wi... | Give a code snippet in #FreeBASIC
Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The in... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Halt_and_catch_fire | Halt and catch fire | Task
Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok?
The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an... | #Arturo | Arturo | 0/0 | Give a code snippet in #Arturo
Task
Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok?
The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Dragon | Dragon | r = new run()
r.val() | Give a code snippet in #Dragon
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #R | R |
multiplication_table <- function(n=12)
{
one_to_n <- 1:n
x <- matrix(one_to_n) %*% t(one_to_n)
x[lower.tri(x)] <- 0
rownames(x) <- colnames(x) <- one_to_n
print(as.table(x), zero.print="")
invisible(x)
}
multiplication_table()
| Give a code snippet in #R
Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Phix | Phix | with javascript_semantics
constant tests = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"}
for test=1 to length(tests) do
string s = tests[test],
t = shuffle(s)
for i=1 to length(t) do
for j=1 to length(t) do
integer {ti,tj} = {t[i],t[j]}
if i!=j and ti!=s[j] an... | Give a code snippet in #Phix
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 i... | 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... | #Oforth | Oforth | : binomial(n, k) | i | 1 k loop: i [ n i - 1+ * i / ] ; | Give a code snippet in #Oforth
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/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #PowerShell | PowerShell | $string = Read-Host "Input a string"
[int]$number = Read-Host "Input a number" | Give a code snippet in #PowerShell
User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| christopher/rosetta-code | |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import kotlin.math.log10
import kotlin.math.floor
fun fileSizeDistribution(path: String) {
val sizes = IntArray(12)
val p = File(path)
val files = p.walk()
var accessible = 0
var notAccessible = 0
var totalSize = 0L
for (file in files) {
try ... | Give a code snippet in #Kotlin
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Host_introspection | Host introspection | Print the word size and endianness of the host machine.
See also: Variable size/Get
| #J | J | IF64 {32 64
64 | Give a code snippet in #J
Print the word size and endianness of the host machine.
See also: Variable size/Get
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations_and_permutations | Combinations and permutations |
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
This page uses content from Wikipedia. The original article was at P... | #Common_Lisp | Common Lisp | (defun combinations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m))
(b i (* b i)))
((= i k) (/ a b))))))
(defun permutations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m)... | Give a code snippet in #Common_Lisp
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
This page uses content from Wik... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #BBC_BASIC | BBC BASIC | OFF : REM Hide the cursor
WAIT 400
ON : REM Show the cursor again | Give a code snippet in #BBC_BASIC
The task is to hide the cursor and show it again.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ada | Ada | with Ada.Streams.Stream_IO, Ada.Directories;
use Ada.Streams.Stream_IO, Ada.Directories;
procedure File_Creation is
File_Handle : File_Type;
begin
Create (File_Handle, Out_File, "output.txt");
Close (File_Handle);
Create_Directory("docs");
Create (File_Handle, Out_File, "/output.txt");
Close ... | Give a code snippet in #Ada
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Logo | Logo | to multiple? :n :d
output equal? 0 modulo :n :d
end
to leapyear? :y
output ifelse multiple? :y 100 [multiple? :y 400] [multiple? :y 4]
end | Give a code snippet in #Logo
Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Dragon | Dragon | class run{
func val(){
showln 10+20
}
}
| Give a code snippet in #Dragon
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the cl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division | Sequence of primes by trial division | Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by... | #Ada | Ada | with Prime_Numbers, Ada.Text_IO, Ada.Command_Line;
procedure Sequence_Of_Primes is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Start: Natural := Natural'Value(Ada.Command_Line.Argument(1));
Stop: Natural := Natural'Value(Ada.Command_Line.Argument(2));
... | Give a code snippet in #Ada
Sequence of primes by trial division
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate a sequence of primes by means of trial division.
Trial division is an algorithm where a candidate number is tested for being a pr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #jq | jq | tostring | explode | map(tonumber - 48) | add | Give a code snippet in #jq
Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #C.2B.2B | C++ | #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
... | Give a code snippet in #C.2B.2B
Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a numb... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every write(getdirs(".","icn")) # writes out all directories from the current directory down
end
procedure getdirs(s,pat) #: return a list of directories beneath the directory 's'
local d,f
if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
while f := read(d) do
if find(pat,f) t... | Give a code snippet in #Icon_and_Unicon
Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #Vlang | Vlang | fn test(n i64) {
print('Testing integer $n')
if n&1 == 0 {
print(' even')
}else{
print(' odd')
}
if n%2 == 0 {
println(' even')
}else{
println(' odd')
}
}
fn main(){
test(-2)
test(-1)
test(0)
test(1)
test(2)
} | Give a code snippet in #Vlang
Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #Delphi | Delphi |
program AlmostPrime;
{$APPTYPE CONSOLE}
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Resu... | Give a code snippet in #Delphi
A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, w... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Honeycombs | Honeycombs | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position... | #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window, Process
import "math" for Math
import "font" for Font
import "input" for Mouse, Keyboard
import "random" for Random
import "./polygon" for Polygon
var Rand = Random.new()
class Hexagon is Polygon {
static baseColor { Color.yellow }
static selecte... | Give a code snippet in #Wren
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S... | #J | J | rcomb=: >@~.@:(/:~&.>)@,@{@# < | Give a code snippet in #J
The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of thos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program factorst.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessDeb: .ascii "Factors of :"
sMessValeur: .fill 12, 1, ' '
.asciz "ar... | Give a code snippet in #ARM_Assembly
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 Oper... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, base... | #ToffeeScript | ToffeeScript | #!/usr/local/bin/toffee
prog = require 'commander'
fs = require 'fs-extra'
if not fs.exists! 'data.json'
fs.outputJson! 'data.json', {}
prog
.command('add <name> <category> [date]')
.description('Add a new entry')
.option('-n <text>', 'notes')
.option('-t <tags>', 'tags')
.action addentry
prog
.co... | Give a code snippet in #ToffeeScript
Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
fun
letter_check
(
cs: string, c0: char
) : bool = cs.exists()(lam(c) => c0 = c)
//
(* ****** ****** *)
fun
Pangram_check
(text: string): bool = let
//
val
alphabet = "abcdefgh... | Give a code snippet in #ATS
Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Phix | Phix | function chowla(atom n)
return sum(factors(n))
end function
function sieve(integer limit)
-- True denotes composite, false denotes prime.
-- Only interested in odd numbers >= 3
sequence c = repeat(false,limit)
for i=3 to floor(limit/3) by 2 do
-- if not c[i] and chowla(i)==0 then
if n... | Give a code snippet in #Phix
Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #ERRE | ERRE |
PROGRAM MAX_SUM
DIM A%[11],B%[10],C%[4]
!$DYNAMIC
DIM P%[0]
PROCEDURE MAX_SUBSEQUENCE(P%[],N%->A$)
LOCAL A%,B%,I%,J%,M%,S%
A%=1
FOR I%=0 TO N% DO
S%=0
FOR J%=I% TO N% DO
S%+=P%[J%]
IF S%>M% THEN
M%=S%
A%=I%
B%=J%
... | Give a code snippet in #ERRE
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are n... | 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 ... | #WDTE | WDTE | io.writeln io.stderr 'Goodbye, World!'; | Give a code snippet in #WDTE
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/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Phix | Phix | --
-- demo\rosetta\peano_curve.exw
-- ============================
--
-- Draws a peano curve. Space key toggles between switchback and meander curves.
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
bool meander = false -- space toggles (false==draw switchback curve)
c... | Give a code snippet in #Phix
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newline_omission | Hello world/Newline omission | Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
| #Pascal | Pascal | program NewLineOmission(output);
begin
write('Goodbye, World!');
end. | Give a code snippet in #Pascal
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Stan... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #APL | APL | !6
720 | Give a code snippet in #APL
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #REXX | REXX | /*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b /*obtain two numbers from input stream.*/
say a+b /*display the sum to the terminal. */
... | Give a code snippet in #REXX
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Dart | Dart | import 'dart:convert';
void main() {
var encoded = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
var decoded = utf8.decode(base64.decode(encoded));
print(decoded);
} | Give a code snippet in #Dart
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/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as t... | #ALGOL_68 | ALGOL 68 | []STRING list1 = ("AA","BB","CC");
[]STRING list2 = ("AA","AA","AA");
[]STRING list3 = ("AA","CC","BB");
[]STRING list4 = ("AA","ACB","BB","CC");
[]STRING list5 = ("single_element");
[][]STRING all lists to test = (list1, list2, list3, list4, list5);
PROC equal = ([]STRING list) BOOL:
BEGIN
BOOL ok := TRUE... | Give a code snippet in #ALGOL_68
Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or fal... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurren... | #Scala | Scala | import scala.util.Random
object Magic8Ball extends App {
val shake: () => String = {
val answers = List(
"It is certain.", "It is decidedly so.", "Without a doubt.",
"Yes – definitely.", "You may rely on it.", "As I see it, yes.",
"Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",... | Give a code snippet in #Scala
Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinforma... | 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,... | #Forth | Forth | : prime? ( odd -- ? )
3
begin 2dup dup * >=
while 2dup mod 0=
if 2drop false exit
then 2 +
repeat 2drop true ;
: 2-exp-mod { e m -- 2^e mod m }
1
0 30 do
e 1 i lshift >= if
dup *
e 1 i lshift and if 2* then
m mod
then
-1 +loop ;
: factor-mersenne ( exponent ... | Give a code snippet in #Forth
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Ceylon | Ceylon | shared void run() {
function digitsSquaredSum(variable Integer n) {
variable value total = 0;
while(n > 0) {
total += (n % 10) ^ 2;
n /= 10;
}
return total;
}
function lastSum(variable Integer n) {
while(true) {
n = digitsSquaredSum(n);
if(n == 89 || n == 1) {
return n;
}
}
}
v... | Give a code snippet in #Ceylon
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = la... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const array string: lines is [] (
"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"... | Give a code snippet in #Seed7
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spac... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function... | #Maxima | Maxima | show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$
show(1, 2, 3, 4);
apply(show, [1, 2, 3, 4]);
/* Actually, the built-in function "disp" is already what we want */
disp(1, 2, 3, 4);
apply(disp, [1, 2, 3, 4]); | Give a code snippet in #Maxima
Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #OCaml | OCaml | let rec quicksort gt = function
| [] -> []
| x::xs ->
let ys, zs = List.partition (gt x) xs in
(quicksort gt ys) @ (x :: (quicksort gt zs))
let _ =
quicksort (>) [4; 65; 2; -31; 0; 99; 83; 782; 1] | Give a code snippet in #OCaml
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick so... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #LSE64 | LSE64 | " Hello world" @ 1 + 8 * , # 96 = (11+1)*(size of a cell) = 12*8 | Give a code snippet in #LSE64
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 cont... | 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... | #AutoIt | AutoIt | If problem Then
Exit
Endif | Give a code snippet in #AutoIt
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 finalizer... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, sho... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: wrap (in string: aText, in integer: lineWidth) is func
result
var string: wrapped is "";
local
var array string: words is 0 times "";
var string: word is "";
var integer: spaceLeft is 0;
begin
words := split(aText, " ");
if length(words) <> 0 ... | Give a code snippet in #Seed7
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or prov... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #Java | Java |
package org.rosettacode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
impor... | Give a code snippet in #Java
An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ter... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ring | Ring |
test = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
stoogeSort(test, 1, len(test))
for i = 1 to 10
see "" + test[i] + " "
next
see nl
func stoogeSort list, i, j
if list[j] < list[i]
temp = list[i]
list[i] = list[j]
list[j] = temp ok
if j - i > 1
t = (j - i + 1)/3
stoo... | Give a code snippet in #Ring
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of... | #REXX | REXX | /*REXX program uses a subtractive generator, and creates a sequence of random numbers. */
s.0= 292929; s.1= 1; billion= 1e9
numeric digits 20
cI= 55; do i=2 for cI-2; s.i= mod( s(i-2) - s(i-1), billion)
end /*i*/
Cp= 34
... | Give a code snippet in #REXX
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #PHP | PHP | class LZW
{
function compress($unc) {
$i;$c;$wc;
$w = "";
$dictionary = array();
$result = array();
$dictSize = 256;
for ($i = 0; $i < 256; $i += 1) {
$dictionary[chr($i)] = $i;
}
for ($i = 0; $i < strlen($unc); $i++) {
$c = $un... | Give a code snippet in #PHP
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
every write(F(!arglist)) # F of all arguments
end
procedure F(n)
if integer(n) >= 0 then
return (n = 0, 1) | n - M(F(n-1))
end
procedure M(n)
if integer(n) >= 0 then
return (0 = n) | n - F(M(n-1))
end | Give a code snippet in #Icon_and_Unicon
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or... | #Metafont | Metafont | num1 := oct"100";
num2 := hex"100"; | Give a code snippet in #Metafont
Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #zkl | zkl | class Church{ // kinda heavy, just an int + fcn churchAdd(ca,cb) would also work
fcn init(N){ var n=N; } // Church Zero is Church(0)
fcn toInt(f,x){ do(n){ x=f(x) } x } // c(3)(f,x) --> f(f(f(x)))
fcn succ{ self(n+1) }
fcn __opAdd(c){ self(n+c.n) }
fcn __opMul(c){ self(n*c.n) }
fcn pow(c) ... | Give a code snippet in #zkl
Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bit... | #Phix | Phix | with javascript_semantics
function entropy(sequence s)
sequence symbols = {},
counts = {}
integer N = length(s)
for i=1 to N do
object si = s[i]
integer k = find(si,symbols)
if k=0 then
symbols = append(symbols,si)
counts = append(counts,1)
... | Give a code snippet in #Phix
Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort | Sorting algorithms/Merge sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #FunL | FunL | def
sort( [] ) = []
sort( [x] ) = [x]
sort( xs ) =
val (l, r) = xs.splitAt( xs.length()\2 )
merge( sort(l), sort(r) )
merge( [], xs ) = xs
merge( xs, [] ) = xs
merge( x:xs, y:ys )
| x <= y = x : merge( xs, y:ys )
| otherwise = y : merg... | Give a code snippet in #FunL
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(... | #Clojure | Clojure | (defn !! [m n]
(->> (iterate #(- % m) n) (take-while pos?) (apply *)))
(doseq [m (range 1 6)]
(prn m (map #(!! m %) (range 1 11)))) | Give a code snippet in #Clojure
The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Liberty_BASIC | Liberty BASIC |
Call cuboid 1,3,4
End
Sub cuboid width, height, depth
wd=width*7+2: hi=height*3: dp=depth
For i=1 To wd-2
w$=w$+"-":h$=h$+" "
Next
w$="+"+w$+"+":d$="/"+h$+"/":h$="|"+h$+"|"
px=dp+2:py=1:Locate dp+2,py:Print w$;
For i=2 To hi+1
Locate wd+dp+1,i:Print"|";
Next
Locate ... | Give a code snippet in #Liberty_BASIC
Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational proje... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #BaCon | BaCon | REM empty window
INCLUDE "hug.bac"
mainwin = WINDOW("Rosetta Code empty", 400, 300)
REM start gtk event loop...
DISPLAY | Give a code snippet in #BaCon
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #Delphi | Delphi | type
TIntArray = array of Integer;
{ TSudokuSolver }
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s... | Give a code snippet in #Delphi
Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #IS-BASIC | IS-BASIC | PRINT INF | Give a code snippet in #IS-BASIC
Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Phix | Phix | function sumMul(atom n, f)
n = floor((n-1)/f)
return f*n*(n+1)/2
end function
function sum35(atom n)
return sumMul(n,3) +
sumMul(n,5) -
sumMul(n,15)
end function
for i=0 to 8 do
string sp = repeat(' ',9-i),
pt = "1"&repeat('0',i)
printf(1,"%s%s%s %d\n",{sp,pt,sp,... | Give a code snippet in #Phix
Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #ALGOL-M | ALGOL-M |
BEGIN
INTEGER ARRAY DOORS[1:100];
INTEGER I, J, OPEN, CLOSED;
OPEN := 1;
CLOSED := 0;
% ALL DOORS ARE INITIALLY CLOSED %
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
DOORS[I] := CLOSED;
END;
% PASS THROUGH AT INCREASING INTERVALS AND FLIP %
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
FOR J := I STEP I UNTIL 1... | Give a code snippet in #ALGOL-M
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ... | 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:... | #BaCon | BaCon |
PRAGMA INCLUDE <stdio.h>
PRAGMA INCLUDE <stdlib.h>
PRAGMA INCLUDE <string.h>
PRAGMA INCLUDE <openssl/md5.h>
PRAGMA LDFLAGS -lcrypto -lm -w
DECLARE result TYPE unsigned char *
DECLARE string TYPE const char *
string = "Rosetta code"
strlenght = LEN(string)
result = MD5( string, strlenght , 0)
FOR i = 0 TO MD... | Give a code snippet in #BaCon
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey se... | #Raku | Raku | sub farey ($order) {
my @l = 0/1, 1/1;
(2..$order).map: { push @l, |(1..$^d).map: { $_/$d } }
unique @l
}
say "Farey sequence order ";
.say for (1..11).hyper(:1batch).map: { "$_: ", .&farey.sort.map: *.nude.join('/') };
.say for (100, 200 ... 1000).race(:1batch).map: { "Farey sequence order $_ has " ~ [.&... | Give a code snippet in #Raku
The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Julia | Julia | dog, Dog, DOG = "Benjamin", "Samba", "Bernie"
if dog === Dog
println("There is only one dog, ", DOG)
else
println("The three dogs are: ", dog, ", ", Dog, " and ", DOG)
end | Give a code snippet in #Julia
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, Sa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Nim | Nim | proc beadSort[T](a: var openarray[T]) =
var max = low(T)
var sum = 0
for x in a:
if x > max: max = x
var beads = newSeq[int](max * a.len)
for i in 0 ..< a.len:
for j in 0 ..< a[i]:
beads[i * max + j] = 1
for j in 0 ..< max:
sum = 0
for i in 0 ..< a.len:
sum += beads[i * m... | Give a code snippet in #Nim
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares... | Give a code snippet in #Java
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Ring | Ring |
apple = 0
banana = 1
cherry = 2
see "apple : " + apple + nl
see "banana : " + banana + nl
see "cherry : " + cherry + nl
| Give a code snippet in #Ring
Task
Create an enumeration of constants with and without explicit values.
| 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... | #gnuplot | gnuplot |
## Ring of random points 2/18/17 aev
reset
fn="RingRandPntsGnu";
ttl="Ring of random points"
ofn=fn.".png"; lim=1000;
randgp(top) = floor(rand(0)*top)
set terminal png font arial 12 size 640,640
set output ofn
set title ttl font "Arial:Bold,12"
unset key;
set size square
set parametric
set xrange [-20:20]; set yrang... | Give a code snippet in #gnuplot
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" c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
window% = FN_newdialog("Rosetta Code", 100, 100, 120, 52, 8, 1000)
PROC_static(window%, "There have been no clicks yet", 100, 10, 10, 100, 14, 0)
PROC_pushbutton(window%, "Click me", FN_setproc(PROCclick), 40, 30, 40, 16, 0)
PROC_show... | Give a code snippet in #BBC_BASIC
Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #XPL0 | XPL0 | Text(0, "A and B = "); HexOut(0, A and B); CrLf(0); \alternate symbol: &
Text(0, "A or B = "); HexOut(0, A or B); CrLf(0); \alternate symbol: !
Text(0, "A xor B = "); HexOut(0, A xor B); CrLf(0); \alternate symbol: |
Text(0, "not A = "); HexOut(0, not A); CrLf(0); \alternate symbol: ~
Text(0, "A <... | Give a code snippet in #XPL0
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #BASIC256 | BASIC256 | dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
print "There is just one dog, named "; dog
end | Give a code snippet in #BASIC256
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,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyl... | #ERRE | ERRE |
PROGRAM ALMOST_PRIME
!
! for rosettacode.org
!
!$INTEGER
PROCEDURE KPRIME(N,K->KP)
LOCAL P,F
FOR P=2 TO 999 DO
EXIT IF NOT((F<K) AND (P*P<=N))
WHILE (N MOD P)=0 DO
N/=P
F+=1
END WHILE
END FOR
KP=(F-(N>1)=K)
END PROCEDURE
BEGIN
PRINT(CHR$(12);) !CLS
FOR K=1 TO 5... | Give a code snippet in #ERRE
A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, whe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #TXR | TXR | (crc32 "The quick brown fox jumps over the lazy dog") | Give a code snippet in #TXR
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Tcl | Tcl | set l {56 21 71 27 39 62 87 76 82 94 45 83 65 45 28 90 52 44 1 89}
puts [lmap x $l {if {$x % 2} continue; set x}] | Give a code snippet in #Tcl
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #11l | 11l | F modp(m, n)
V result = m % n
I result < 0
result += n
R result
F getA004290(n)
I n == 1
R BigInt(1)
V arr = [[0] * n] * n
arr[0][0] = 1
arr[0][1] = 1
V m = 0
V ten = BigInt(10)
V nBi = BigInt(n)
L
m++
I arr[m - 1][Int(modp(-pow(ten, m), nBi))] == 1
L.... | Give a code snippet in #11l
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrase... | 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.
| #Run_BASIC | Run BASIC | print fileSize(DefaultDir$,"input.txt") ' current default directory
print fileSize("","input.txt") ' root directory
function fileSize(dir$,file$)
open dir$;"\";file$ FOR input as #f
fileSize = lof(#f) ' Length Of File
close #f
end function | Give a code snippet in #Run_BASIC
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/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one dow... | #LDPL | LDPL |
DATA:
bottles-in-the-wall is number
plural is text
PROCEDURE:
store 99 in bottles-in-the-wall
sub-procedure check-plural
if bottles-in-the-wall is not equal to 1 then
store "s" in plural
else
store "" in plural
end if
end sub-procedure
while bottles-in-the-wall is greater than 0 do
... | Give a code snippet in #LDPL
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task als... | #Run_BASIC | Run BASIC | dim a(10,10)
cls
for row = 1 TO 10
for col = 1 TO 10
a(row,col) = INT(20 * RND(1) + 1)
next col
next row
for row = 1 to 10
for col = 1 to 10
print a(row, col)
if a(row, col) = 20 then goto [end]
next col
next row
[end]
print "At row:";row;... | Give a code snippet in #Run_BASIC
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #FutureBasic | FutureBasic | window 1
short i = 575
ptr j
j = @i
printf @"Address of i = %ld",j
print @"Value of i = ";peek word(j)
HandleEvents | Give a code snippet in #FutureBasic
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 Opera... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
StringForm["`` count: `` frequency: ``", Rule@@ #[[1]], StringPadLeft[ToString@ #[[2]], 8], PercentForm[N@ #[[2]]/(10^8 -1)]]& /@
Sort[Tally[Partition[Mod[Prime[Range[10^8]], 10], 2, 1]]] // Column
| Give a code snippet in #Mathematica.2FWolfram_Language
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it see... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #Dart | Dart | import 'dart:io';
// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));
void main() {
while(true) {
String input = stdin.readLineSync();
var chunks = input.split(new RegExp... | Give a code snippet in #Dart
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Topic_variable | Topic variable | Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h... | #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
3.let {
println(it)
println(it * it)
println(Math.sqrt(it.toDouble()))
}
} | Give a code snippet in #Kotlin
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.
A topic variable is a special variable with a very short name which can also often be omitted.
Demonstrate the utilization and behaviour of the topic variable within the langu... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.