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/Send_email | Send email | Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are given.
Solutions using libraries or f... | #PicoLisp | PicoLisp | (mail "localhost" 25 "me@from.org" "you@to.org" "Subject" NIL "Hello") | Give a code snippet in #PicoLisp
Task
Write a function to send an email.
The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
If appropriate, explain what notifications of problems/success are give... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var sleepingBeauty = Fn.new { |reps|
var wakings = 0
var heads = 0
for (i in 0...reps) {
var coin = rand.int(2) // heads = 0, tails = 1 say
wakings = wakings + 1
if (coin == 0) {
heads = heads + ... | Give a code snippet in #Wren
Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sun... | 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.
| #NewLISP | NewLISP | (let (pid (fork (println "Hello from child")))
(cond
((nil? pid) (throw-error "Unable to fork"))
('t (wait-pid pid)))) | Give a code snippet in #NewLISP
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
| 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... | #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int PRIMES[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157... | Give a code snippet in #C
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 firs... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Raku | Raku | sub gray_encode ( Int $n --> Int ) {
return $n +^ ( $n +> 1 );
}
sub gray_decode ( Int $n is copy --> Int ) {
my $mask = 1 +< (32-2);
$n +^= $mask +> 1 if $n +& $mask while $mask +>= 1;
return $n;
}
for ^32 -> $n {
my $g = gray_encode($n);
my $d = gray_decode($g);
printf "%2d: %5b => %5b... | Give a code snippet in #Raku
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Oz | Oz | declare
[Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}
DB = {Sqlite.open 'test.db'}
in
try
{Sqlite.exec DB
"CREATE TABLE address ("
#"addrID INTEGER PRIMARY KEY,"
#"addrStreet TEXT NOT NULL,"
#"addrCity TEXT NOT NULL,"
#"addrState TEXT NOT NULL,"
#"addrZIP T... | Give a code snippet in #Oz
Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
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
... | #Maple | Maple | Compare_fn:= proc(s1, s2)
local len1, len2;
len1 := StringTools:-Length(s1);
len2 := StringTools:-Length(s2);
if (len1 > len2) then
return true;
elif (len1 < len2) then
return false;
else # ascending lexicographic order for strings of equal length / case insensitive
StringTools:-CompareCI(s1, s2);
end if;
... | Give a code snippet in #Maple
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/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar tricker... | #Nim | Nim | proc main() =
echo "Hello World!"
main()
| Give a code snippet in #Nim
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #DBL | DBL | ;
; Check file and directory exists for DBL version 4 by Dario B.
;
PROC
;------------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message
CLOSE 1
OPEN (1,O,'TT:')
;The file path can be written as:
... | Give a code snippet in #DBL
Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Lambdatalk | Lambdatalk |
{S.reverse hello brave new world}
-> world new brave hello
| Give a code snippet in #Lambdatalk
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #BQN | BQN | Factor ← { 𝕊n:
# Prime sieve
primes ← ↕0
Sieve ← { p 𝕊 a‿b:
p(⍋↑⊣)↩√b ⋄ l←b-a
E ← {↕∘⌈⌾(((𝕩|-a)+𝕩×⊢)⁼)l} # Indices of multiples of 𝕩
a + / (1⥊˜l) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Primes in segment [a,b)
}
# Factor by trial division
r ← ↕0 # Result list
Try ← {
... | Give a code snippet in #BQN
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the pr... | 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.
| #Peloton | Peloton | <@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
<@ TSTEVEELTLST>...</@>
<@ IFF>
<@ LETLSTELTLST>evens|...</@>
</@>
</@> | Give a code snippet in #Peloton
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/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
... | #Wortel | Wortel | @let {
; using a composition and a fork (like you would do in J)
rms1 ^(@sqrt @(@sum / #) *^@sq)
; using a function with a named argument
rms2 &a @sqrt ~/ #a @sum !*^@sq a
[[
!rms1 @to 10
!rms2 @to 10
]]
} | Give a code snippet in #Wortel
Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort | Sorting algorithms/Comb sort | Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algor... | #Kotlin | Kotlin | // version 1.1.2
fun <T : Comparable<T>> combSort(input: Array<T>) {
var gap = input.size
if (gap <= 1) return // already sorted
var swaps = false
while (gap > 1 || swaps) {
gap = (gap / 1.247331).toInt()
if (gap < 1) gap = 1
var i = 0
swaps = false
while (i + ... | Give a code snippet in #Kotlin
Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #D | D | import std.stdio;
void main() {
int delegate()[] funcs;
foreach (i; 0 .. 10)
funcs ~= (i => () => i ^^ 2)(i);
writeln(funcs[3]());
} | Give a code snippet in #D
Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
D... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Ring | Ring |
see "Active Source File Name : " + filename() + nl
| Give a code snippet in #Ring
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Factor | Factor | USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
:: balanced ( str -- )
0 :> counter!
1 :> ok!
str
[ dup length 0 > ]
[ 1 cut swap
"[" = [ counter 1 + counter! ] [ counter 1 - counter! ] if
counter 0 < [ 0 ok! ] when
]
while
drop
ok 0 =
[ ... | Give a code snippet in #Factor
Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Bracmat | Bracmat | ( ( mod-power
= base exponent modulus result
. !arg:(?base,?exponent,?modulus)
& !exponent:~<0
& 1:?result
& whl
' ( !exponent:>0
& ( ( mod$(!exponent.2):1
& mod$(!result*!base.!modulus):?result
& -1
... | Give a code snippet in #Bracmat
Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337... | 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... | #Python | Python | typedef unsigned long long u8;
typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;
#define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
u8 ranval( ranctx *x ) {
u8 e = x->a - rot(x->b, 7);
x->a = x->b ^ rot(x->c, 13);
x->b = x->c + rot(x->d, 37);
x->c = x->d + e;
x->d = e + x->a;
return x->d;
}... | Give a code snippet in #Python
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 algorit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Here_document | Here document | A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The text ... | #Ursala | Ursala | hd =
-[
The text enclosed within the so called dash-brackets shown above
and below will be interpreted as a list of character strings. It
can contain anything except uninterpreted dash-brackets, and can
be used in any declaration or expression. The dash-brackets don't
have to be on a line by themselves.
]-
examp... | Give a code snippet in #Ursala
A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) follow... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #AutoHotkey | AutoHotkey | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... | Give a code snippet in #AutoHotkey
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabli... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Me... | #Oforth | Oforth | "Hello,How,Are,You,Today" wordsWith(',') println | Give a code snippet in #Oforth
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #ATS | ATS |
(* ****** ****** *)
//
// How to compile:
//
// patscc -DATS_MEMALLOC_LIBC -o idmatrix idmatrix.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
extern
fun
idmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n)
implement
idmatrix(n) =
matrixref_tabulate_cloref<int> (n, n, lam(... | Give a code snippet in #ATS
Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #CoffeeScript | CoffeeScript | mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
counts = {}
for elem in arr
counts[elem] ||= 0
counts[elem] += 1
max = 0
for key, cnt of counts
max = cnt if cnt > max
(key for key, cnt of counts when cnt == max)
console.log mode [1,... | Give a code snippet in #CoffeeScript
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array)... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The... | #Scheme | Scheme | (define table #(
#("" "X" "Y" "Z")
#(1 1 2 3)
#(2 4 5 6)
#(3 7 8 9)))
(display "<table>")
(do ((r 0 (+ r 1))) ((eq? r (vector-length table)))
(display "<tr>")
(do ((c 0 (+ c 1))) ((eq? c (vector-length (vector-ref table r))))
... | Give a code snippet in #Scheme
Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled wi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo... | #BaCon | BaCon | DECLARE month$[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }
DECLARE month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
year$ = "1969"
' Leap year
INCR month[1], IIF(MOD(VAL(year$), 4) = 0 OR MOD(VAL(year$), 100) = 0 AND MOD(VA... | Give a code snippet in #BaCon
Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Raku | Raku | multi triples (60, $n) {
my %sq = (1..$n).map: { .² => $_ };
my atomicint $i = 0;
my @triples[2*$n];
(1..^$n).race(:8degree).map: -> $a {
for $a^..$n -> $b {
my $cos = $a * $a + $b * $b - $a * $b;
@triples[$i⚛++] = $a, %sq{$cos}, $b if %sq{$cos}:exists;
}
}
... | Give a code snippet in #Raku
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagorean_quadruples | Pythagorean quadruples |
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclusive), for all values of ... | #AWK | AWK |
# syntax: GAWK -f PYTHAGOREAN_QUADRUPLES.AWK
# converted from Go
BEGIN {
n = 2200
s = 3
for (a=1; a<=n; a++) {
a2 = a * a
for (b=a; b<=n; b++) {
ab[a2 + b * b] = 1
}
}
for (c=1; c<=n; c++) {
s1 = s
s += 2
s2 = s
for (d=c+1; d<=n; d++) {
if ... | Give a code snippet in #AWK
One form of Pythagorean quadruples is (for positive integers a, b, c, and d):
a2 + b2 + c2 = d2
An example:
22 + 32 + 62 = 72
which is:
4 + 9 + 36 = 49
Task
For positive integers up 2,200 (inclu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, ... | #OCaml | OCaml |
let get, sum_unto =
let cache = ref [||]
let rec get i j =
if Array.length !cache < i then
cache :=
Array.init i begin fun i ->
try !cache.(i) with Invalid_argument _ ->
Array.make (i+1) (Num.num_of_int 0)
end;
if Num.(!cache.(i-1).(j-1) =/ num_of_int 0)
then ... | Give a code snippet in #OCaml
This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #FreeBASIC | FreeBASIC |
type MOUSE
'mouse position, button state, wheel state
x as integer
y as integer
buttons as integer
wheel as integer
end type
screen 12
dim as MOUSE mouse
while inkey=""
locate 1,1
getmouse(mouse.x, mouse.y, mouse.wheel, mouse.buttons)
if mouse.x < 0 then
print "Mouse out of wi... | Give a code snippet in #FreeBASIC
Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| 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... | #8086_Assembly | 8086 Assembly | test ax,1
jne isOdd
;else, is even | Give a code snippet in #8086_Assembly
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 od... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds | Sorting algorithms/Cocktail sort with shifting bounds |
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
... | #C.2B.2B | C++ | #include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
// This only works for random access iterators
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
if (begin == end)
return;
for (--end; begin < end; ) {
iterato... | Give a code snippet in #C.2B.2B
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are... | #J | J |
nsmooth=: dyad define NB. TALLY nsmooth N
factors=. x: i.@:>:&.:(p:inv) y
smoothies=. , 1x
result=. , i. 0x
while. x > # result do.
mn =. {. smoothies
smoothies =. ({.~ (x <. #)) ~. /:~ (}. smoothies) , mn * factors
result=. result , mn
end.
)
| Give a code snippet in #J
n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_increasing_subsequence | Longest increasing subsequence | Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
Note that a list may have m... | #jq | jq | def until(cond; update):
def _until:
if cond then . else (update | _until) end;
try _until catch if .== "break" then empty else . end;
# binary search for insertion point
def bsearch(target):
. as $in
| [0, length-1] # [low, high]
| until(.[0] > .[1];
.[0] as $low | .[1] as $high
| ... | Give a code snippet in #jq
Calculate and show here a longest increasing subsequence of the list:
{
3
,
2
,
6
,
4
,
5
,
1
}
{\displaystyle \{3,2,6,4,5,1\}}
And of the list:
{
0
,
8
,
4
,
12
,
2
,
10
,
6
,
14
,
1
,
9
,
5
,
13
,
3
,
11
,
7
,
15
}
{\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}
... | 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 ... | #Pascal | Pascal | program Palindro;
{ RECURSIVE }
function is_palindro_r(s : String) : Boolean;
begin
if length(s) <= 1 then
is_palindro_r := true
else begin
if s[1] = s[length(s)] then
is_palindro_r := is_palindro_r(copy(s, 2, length(s)-2))
else
is_palindro_r := false
end
end; { is_palindro_r }
{ NON ... | Give a code snippet in #Pascal
A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Arturo | Arturo | binarySearch: function [arr,val,low,high][
if high < low -> return ø
mid: shr low+high 1
case [val]
when? [< arr\[mid]] -> return binarySearch arr val low mid-1
when? [> arr\[mid]] -> return binarySearch arr val mid+1 high
else -> return mid
]
ary: [
0 1 4 5 6 7 ... | Give a code snippet in #Arturo
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/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... | #VBScript | VBScript | Dim MyWord
MyWord = UCase("alphaBETA") ' Returns "ALPHABETA"
MyWord = LCase("alphaBETA") ' Returns "alphabeta" | Give a code snippet in #VBScript
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 no... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #Perl | Perl | my $tenfactorial;
print "$tenfactorial\n";
BEGIN
{$tenfactorial = 1;
$tenfactorial *= $_ foreach 1 .. 10;} | Give a code snippet in #Perl
Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #HicEst | HicEst | CHARACTER haystack='Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo.'
CHARACTER needle*10
DLG(TItle="Enter search string", Edit=needle)
n = EDIT(Text=haystack, Option=2, End, Count=needle) ! Option = word
IF( n == 0 ) THEN
WRITE(Messagebox="!") needle, "not found" ! bus not found
ELSE
first = EDIT(Text=... | Give a code snippet in #HicEst
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Standard_ML | Standard ML | (* this function only recognizes integers in decimal format *)
fun isInteger s = case Int.scan StringCvt.DEC Substring.getc (Substring.full s) of
SOME (_,subs) => Substring.isEmpty subs
| NONE => false
fun isReal s = case Real.scan Substring.getc (Substring.full s) of
SOME (_,subs) => Substring.isEmpt... | Give a code snippet in #Standard_ML
Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(let (NoData 0 NoDataMax -1 NoDataMaxline "!" TotFile 0 NumFile 0)
(let InFiles
(glue ","
(mapcar
'((File)
(in File
(while (split (line) "^I")
(let (Len (length @) Date (car @) TotLine... | Give a code snippet in #PicoLisp
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or pers... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #C.2B.2B | C++ |
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
#if 1 // optimized for 64-bit architecture
typedef unsigned long usingle;
typedef unsigned long long udouble;
const int word_len = 32;
#else // optimized for 32-bit architecture
typedef unsigned shor... | Give a code snippet in #C.2B.2B
Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is invol... | #XPL0 | XPL0 | include c:\cxpl\codes;
def Size = 10_000_000;
int Tbl(12+1);
int I, J, N;
real X, S0, S1;
[for J:= 5 to 12 do Tbl(J):= 0;
for I:= 0 to 1_000_000-1 do \generate one million items
[N:= Ran(Size);
for J:= 5 to 11 do
[N:= N - Size/J;
if N < 0 then [Tbl(J):... | Give a code snippet in #XPL0
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #Pare | Pare | (print "hello world") | Give a code snippet in #Pare
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome 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
... | #Quackery | Quackery | [ dup size times
[ i^ 0 > if
[ dup i^ 1 - peek
over i^ peek
2dup > iff
[ dip [ swap i^ poke ]
swap i^ 1 - poke
-1 step ]
else 2drop ] ] ] is gnomesort ( [ --> [ ) | Give a code snippet in #Quackery
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #EasyLang | EasyLang | items$[] = [ "iced" "jam" "plain" ]
n = len items$[]
k = 2
len result[] k
n_results = 0
#
func output . .
n_results += 1
if len items$[] > 0
for r in result[]
write items$[r] & " "
.
print ""
.
.
func combine pos val . .
if pos = k
call output
else
for i = val to n - 1
result[... | Give a code snippet in #EasyLang
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #MiniScript | MiniScript | middle3 = function(num)
if num < 0 then num = -num
s = str(num)
if s.len < 3 then return "Input too short"
if s.len % 2 == 0 then return "Input length not odd"
mid = (s.len + 1) / 2 - 1
return s[mid-1:mid+2]
end function
for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
... | Give a code snippet in #MiniScript
Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should ... | 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... | #zkl | zkl | [-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") }) | Give a code snippet in #zkl
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... | 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.
| #SQL_PL | SQL PL |
BEGIN
DECLARE UTL_FILE_HANDLER UTL_FILE.FILE_TYPE;
DECLARE DIR_ALIAS_CURRENT VARCHAR(128);
DECLARE DIR_ALIAS_ROOT VARCHAR(128);
DECLARE DIRECTORY VARCHAR(1024);
DECLARE FILENAME VARCHAR(255);
SET DIR_ALIAS_CURRENT = 'outputFileCurrent';
SET DIRECTORY = '/home/db2inst1/doc';
SET FILENAME = 'output.tx... | Give a code snippet in #SQL_PL
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/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Vala | Vala | bool is_prime(int n) {
var d = 5;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
int count_prime_factors(int n) {
var count = 0;
... | Give a code snippet in #Vala
A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Sh... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Window_creation/X11 | Window creation/X11 | Task
Create a simple X11 application, using an X11 protocol library such as Xlib or XCB, that draws a box and "Hello World" in a window.
Implementations of this task should avoid using a toolkit as much as possible.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program creatFenX1164.s */
/* link with gcc options -lX11 -L/usr/lpp/X11/lib */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in lang... | Give a code snippet in #AArch64_Assembly
Task
Create a simple X11 application, using an X11 protocol library such as Xlib or XCB, that draws a box and "Hello World" in a window.
Implementations of this task should avoid using a toolkit as much as possible.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #AutoHotkey | AutoHotkey | IncompleteList := "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
CompleteList := Perm( "ABCD" )
Missing := ""
Loop, Parse, CompleteList, `n, `r
If !InStr( IncompleteList , A_LoopField )
Missing .= "`n" A_LoopField
MsgBox Missing Permutati... | Give a code snippet in #AutoHotkey
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, o... | #C.2B.2B | C++ |
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
(def data "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$s... | Give a code snippet in #C.2B.2B
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either l... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #J | J | hash=: vals {~ keys&i. | Give a code snippet in #J
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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
)
)
,
... | #BQN | BQN | F ← {0:1; 𝕩-M F𝕩-1}
M ← {0:0; 𝕩-F M𝕩-1}
⍉"FM"∾>(F∾M)¨↕15 | Give a code snippet in #BQN
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #AWK | AWK |
# syntax: GAWK -f MINIMUM_MULTIPLE_OF_M_WHERE_DIGITAL_SUM_EQUALS_M.AWK
BEGIN {
start = 1
stop = 70
printf("A131382 %d-%d:\n",start,stop)
for (n=start; n<=stop; n++) {
for (m=1; ; m++) {
if (digit_sum(m*n,10) == n) {
printf("%9d%1s",m,++count%10?"":"\n")
break
... | Give a code snippet in #AWK
Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that... | christopher/rosetta-code | |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
t... | #11l | 11l | F foursquares(lo, hi, unique, show)
V solutions = 0
L(c) lo .. hi
L(d) lo .. hi
I !unique | (c != d)
V a = c + d
I a >= lo & a <= hi
I !unique | (c != 0 & d != 0)
L(e) lo .. hi
I !unique | (e !C (a, c, d))
... | Give a code snippet in #11l
4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Order | Order | #include <order/interpreter.h>
ORDER_PP(8to_lit(
8seq_fold(8plus, 0,
8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9)))
)) | Give a code snippet in #Order
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Raku | Raku | class Farragut {
method FALLBACK ($name, *@rest) {
say "{self.WHAT.raku}: $name.tc() the @rest[], full speed ahead!";
}
}
class Sparrow is Farragut { }
Farragut.damn: 'torpedoes';
Sparrow.hoist: <Jolly Roger mateys>; | Give a code snippet in #Raku
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 o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sequence_of_non-squares | Sequence of non-squares | Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
| #Scheme | Scheme | (define non-squares
(lambda (index)
(+ index (inexact->exact (floor (+ (/ 1 2) (sqrt index)))))))
(define sequence
(lambda (function)
(lambda (start)
(lambda (stop)
(if (> start stop)
(list)
(cons (function start)
(((sequence function) (+ start 1)) s... | Give a code snippet in #Scheme
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A0000... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Stata | Stata | . matrix a=2,9,4\7,5,3\6,1,8
. matrix list a
a[3,3]
c1 c2 c3
r1 2 9 4
r2 7 5 3
r3 6 1 8
. matrix b=I(3)
. matrix list b
symmetric b[3,3]
c1 c2 c3
r1 1
r2 0 1
r3 0 0 1
. matrix c=a,b
. matrix list c
c[3,6]
c1 c2 c3 c1 c2 c3
r1 2 9 4 1 0 0
r2 7 ... | Give a code snippet in #Stata
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names give... | #Dyalect | Dyalect | func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
}
fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(y: 42, x: 12) | Give a code snippet in #Dyalect
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Self_numbers | Self numbers | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or d... | #AppleScript | AppleScript | (*
Base-10 self numbers by index (single or range).
Follows an observed sequence pattern whereby, after the initial single-digit odd numbers, self numbers are
grouped in runs whose members occur at numeric intervals of 11. Runs after the first one come in blocks of
ten: eight runs of ten numbers followe... | Give a code snippet in #AppleScript
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 10227... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Aime | Aime | integer p, s, f;
p = 0;
while ((p += 2) <= 7) {
s = 0;
while ((s += 1) <= 7) {
f = 0;
while ((f += 1) <= 7) {
if (p + s + f == 12 && p != s && p != f && s != f) {
o_form(" ~ ~ ~\n", p, s, f);
}
}
}
} | Give a code snippet in #Aime
There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (dif... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #NGS | NGS | {
F Acc(start:Int) {
sum = start
F acc(i:Int) {
sum = sum + i
sum
}
}
acc = Acc(10)
echo(acc(5))
echo(acc(2))
} | Give a code snippet in #NGS
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 passe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Scheme | Scheme | (define (lex<? a b)
(cond ((null? b) #f)
((null? a) #t)
((= (car a) (car b)) (lex<? (cdr a) (cdr b)))
(else (< (car a) (car b))))) | Give a code snippet in #Scheme
sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #E | E | def sumOfSquares(numbers) {
var sum := 0
for x in numbers {
sum += x**2
}
return sum
} | Give a code snippet in #E
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Line_printer | Hello world/Line printer | Task
Cause a line printer attached to the computer to print a line containing the message: Hello World!
Note
A line printer is not the same as standard output.
A line printer was an older-style printer which prints one line at a time to a continuous ream of paper.
With some systems, a line printer can be... | #Delphi | Delphi | program Project1;
{$APPTYPE CONSOLE}
uses Printers;
var
lPrinterAsTextFile: TextFile;
begin
AssignPrn(lPrinterAsTextFile);
Rewrite(lPrinterAsTextFile);
Writeln(lPrinterAsTextFile, 'Hello World!');
CloseFile(lPrinterAsTextFile);
end. | Give a code snippet in #Delphi
Task
Cause a line printer attached to the computer to print a line containing the message: Hello World!
Note
A line printer is not the same as standard output.
A line printer was an older-style printer which prints one line at a time to a continuous ream of paper.
With som... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #Befunge | Befunge | <v_>#!,#:< "<table>" \0 +55
v >0>::65*1+`\"~"`!*#v_4-5v >
v>#^~^<v"<tr><td>" < \v-1/<>">elb"
<^ >:#,_$10 |!:<>\#v_ vv"ta"
v-",":\-"&":\-"<":\<>5#05#<v+ >"/"v
>#v_$$$0">dt<>dt/<"vv"tr>"+<5 v"<"<
>^>\#v_$$0";pma&" v>"/<>d"v5 v , <
$ > \#v_$0";tl&"v v"</t"<0 > : |
^_>#!,#:<>#<0#<\#<<< >:#,_$#^_v@ $< | Give a code snippet in #Befunge
Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Racket | Racket | #lang racket
(for ([i (in-naturals)]) (displayln i))
| Give a code snippet in #Racket
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations l... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #OxygenBasic | OxygenBasic |
'FUNCTION TO BE PASSED
'=====================
function f(double d,e) as double
return (d+e)*2
end function
'FUNCTION TAKING A FUNCTION AS AN ARGUMENT
'=========================================
function g(sys p) as string
declare function x(double d,e) as double at p
return x(10,11)
end function
... | Give a code snippet in #OxygenBasic
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Racket | Racket |
#lang racket
(provide instance)
(define singleton%
(class object%
(super-new)))
(define instance (new singleton%))
| Give a code snippet in #Racket
A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #Lua | Lua | function sort(word)
local bytes = {word:byte(1, -1)}
table.sort(bytes)
return string.char(table.unpack(bytes))
end
-- Read in and organize the words.
-- word_sets[<alphabetized_letter_list>] = {<words_with_those_letters>}
local word_sets = {}
local max_size = 0
for word in io.lines('unixdict.txt') do
local ke... | Give a code snippet in #Lua
When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the ... | #Ada | Ada | -- licenselist.adb --
-- run under GPS 4.3-5 (Sidux/Debian)
-- process rosetta.org text_processing/3 example
-- uses linked-list to hold times
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO,
Ada.Containers.Doubly_Linked_Lists;
use Ada.Text_IO, Ada.Integer_Text_IO,
... | Give a code snippet in #Ada
A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a check... | 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 ... | #Prolog | Prolog | % binary 4 bit adder chip simulation
b_not(in(hi), out(lo)) :- !. % not(1) = 0
b_not(in(lo), out(hi)). % not(0) = 1
b_and(in(hi,hi), out(hi)) :- !. % and(1,1) = 1
b_and(in(_,_), out(lo)). % and(anything else) = 0
b_or(in(hi,_), out(hi)) :- !. % or(1,any) = 1
b_or(in(_,hi), out(hi)) :... | Give a code snippet in #Prolog
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #PureBasic | PureBasic | Enumeration
#Apple
#Banana
#Cherry
EndEnumeration | Give a code snippet in #PureBasic
Task
Create an enumeration of constants with and without explicit values.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #LaTeX | LaTeX | \documentclass{minimal}
\begin{document}
5\% of \$10
\end{document} | Give a code snippet in #LaTeX
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_number_generator_(device) | Random number generator (device) | Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| #Factor | Factor | USE: random
[ random-32 ] with-system-random . | Give a code snippet in #Factor
Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #MBS | MBS | USER>Set S1="Hello, World!" Write S1
Hello, World!
USER>Set S2=""Hello, World!"" Write S2
SET S2=""Hello, World!"" Write S2
^
<SYNTAX>
USER>Set S3="""Hello, World!"" she typed." Write S3
"Hello, World!" she typed.
USER>Set S4="""""""Wow""""""" Write S4
"""Wow"""
| Give a code snippet in #MBS
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #Component_Pascal | Component Pascal |
MODULE RosettaGreys;
IMPORT Views, Ports, Properties, Controllers, StdLog;
CONST
(* orient values *)
left = 1;
right = 0;
TYPE
View = POINTER TO RECORD
(Views.View)
END;
PROCEDURE LoadGreyPalette(VAR colors: ARRAY OF Ports.Color);
VAR
i, step, hue: INTEGER;
BEGIN
step := 255 DIV LEN(colors);
FOR... | Give a code snippet in #Component_Pascal
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #BASIC | BASIC | FUNCTION gcd(a%, b%)
IF a > b THEN
factor = a
ELSE
factor = b
END IF
FOR l = factor TO 1 STEP -1
IF a MOD l = 0 AND b MOD l = 0 THEN
gcd = l
END IF
NEXT l
gcd = 1
END FUNCTION | Give a code snippet in #BASIC
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest... | 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... | #D | D | void main() {
import std.stdio, std.utf;
string test = "a";
size_t index = 0;
// Get four-byte utf32 value for index 0.
writefln("%d", test.decode(index));
// 'index' has moved to next character input position.
assert(index == 1);
} | Give a code snippet in #D
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).
Converse... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Smalltalk | Smalltalk | Array extend [
dictionaryWithValues: array [ |d|
d := Dictionary new.
1 to: ((self size) min: (array size)) do: [:i|
d at: (self at: i) put: (array at: i).
].
^ d
]
].
({ 'red' . 'one' . 'two' }
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl. | Give a code snippet in #Smalltalk
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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
... | #Modula-2 | Modula-2 | MODULE RankingMethods;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToFixed;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteCard(c : CARDINAL);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%c", buf, c);
WriteString(buf)
END WriteCard;
TYPE Entry = RECORD
name ... | Give a code snippet in #Modula-2
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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 |... | #Perl | Perl | sub show_bool
{
return shift() ? 'true' : 'false', "\n";
}
sub test_logic
{
my ($a, $b) = @_;
print "a and b is ", show_bool $a && $b;
print "a or b is ", show_bool $a || $b;
print "not a is ", show_bool !$a;
print "a xor b is ", show_bool($a xor $b);
} | Give a code snippet in #Perl
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/Undefined_values | Undefined values | #Python | Python | # Check to see whether a name is defined
try: name
except NameError: print "name is undefined at first check"
# Create a name, giving it a string value
name = "Chocolate"
# Check to see whether the name is defined now.
try: name
except NameError: print "name is undefined at second check"
# Remove the definition o... | Give a code snippet in #Python
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
T... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
M=1000
Function Global xz {
=9999
}
Module TopModule {
\\ clear vars and static vars
Clear
M=500
Function Global xz {
=10000
}
Module Kappa {
Static N=1
... | Give a code snippet in #M2000_Interpreter
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations... | 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... | #Haskell | Haskell | data Door
= Open
| Closed
deriving (Eq, Show)
toggle :: Door -> Door
toggle Open = Closed
toggle Closed = Open
toggleEvery :: Int -> [Door] -> [Door]
toggleEvery k = zipWith toggleK [1 ..]
where
toggleK n door
| n `mod` k == 0 = toggle door
| otherwise = door
run :: Int -> [Door]
run n = f... | Give a code snippet in #Haskell
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/Tonelli-Shanks_algorithm | Tonelli-Shanks algorithm |
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number theory, the Tonelli–Shanks algor... | #Python | Python | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, ... | Give a code snippet in #Python
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In computational number ... | 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... | #Haskell | Haskell | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ sh... | Give a code snippet in #Haskell
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 ... | 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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Horner(coefficients As Double(), variable As Double) As Double
Return coefficients.Reverse().Aggregate(Function(acc, coeff) acc * variable + coeff)
End Function
Sub Main()
Console.WriteLine(Horner({-19.0, 7.0, -4.0, 6.0}, 3.0))
End Sub
End Module | Give a code snippet in #Visual_Basic_.NET
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
+
(
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Delphi | Delphi |
program Department_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
i, j, k, count: Integer;
begin
writeln('Police Sanitation Fire');
writeln('------ ---------- ----');
count := 0;
i := 2;
while i < 7 do
begin
for j := 1 to 7 do
begin
if j = i then
Continue;
... | Give a code snippet in #Delphi
There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_number_generator_(device) | Random number generator (device) | Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| #Tcl | Tcl | package require Tcl 8.5
# Allow override of device name
proc systemRandomInteger {{device "/dev/random"}} {
set f [open $device "rb"]
binary scan [read $f 4] "I" x
close $f
return $x
} | Give a code snippet in #Tcl
Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Java | Java | import java.util.Arrays;
public class GroupStage{
//team left digit vs team right digit
static String[] games = {"12", "13", "14", "23", "24", "34"};
static String results = "000000";//start with left teams all losing
private static boolean nextResult(){
if(results.equals("222222")) return f... | Give a code snippet in #Java
It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #BASIC256 | BASIC256 |
# rot13 Cipher v2.0
# basic256 1.1.4.0
# 2101031238
dec$ = ""
TYPE$ = "cleartext "
ctext$ = ""
sp = 0
iOffset = 13 #offset assumed TO be 13 - uncomment LINE 11 TO change
INPUT "For decrypt enter " + "<d> " + " -- else press enter > ",dec$
# INPUT "Enter offset > ", iOffset
IF dec$ = "d" OR dec$ = ... | Give a code snippet in #BASIC256
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Sidef | Sidef | func isleap(year) {
if (year %% 100) {
return (year %% 400);
}
return (year %% 4);
} | Give a code snippet in #Sidef
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/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Batch_File | Batch File | @echo off
setlocal ENABLEDELAYEDEXPANSION
set n=15
set /A nn=n+1
for /L %%i in (0,1,%nn%) do set t.%%i=0
set t.1=1
for /L %%i in (1,1,%n%) do (
set /A ip=%%i+1
for /L %%j in (%%i,-1,1) do (
set /A jm=%%j-1
set /A t.%%j=t.%%j+t.!jm!
)
set /A t.!ip!=t.%%i
for /L %%j in (!ip!,-1,1) do (
... | Give a code snippet in #Batch_File
Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_length | Array length | Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
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 befo... | #NGS | NGS | echo(len(['apple', 'orange']))
# same
echo(['apple', 'orange'].len()) | Give a code snippet in #NGS
Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Raku | Raku | my @c = gather for ^10 -> $i {
take { $i * $i }
}
.().say for @c.pick(*); # call them in random order | Give a code snippet in #Raku
Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring | Substring |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Scheme | Scheme | (define s "Hello, world!")
(define n 5)
(define m (+ n 6))
(display (substring s n m))
(newline)
(display (substring s n))
(newline)
(display (substring s 0 (- (string-length s) 1)))
(newline)
(display (substring s (string-index s #\o) m))
(newline)
(display (substring s (string-contains s "lo") m))
(newline) | Give a code snippet in #Scheme
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.