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/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.
| #Clean | Clean | module SelectFromArray
import StdEnv | Give a code snippet in #Clean
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/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #PHL | PHL | module helloworld;
extern printf;
@Integer main [
printf("Hello world!");
return 0;
] | Give a code snippet in #PHL
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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
... | #Rust | Rust | let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba"); | Give a code snippet in #Rust
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als... | #Python | Python | from __future__ import print_function
import sys
# following two must remain in the same order
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \
tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \
tk_Putc, tk_Lparen, tk_Rparen, tk_L... | Give a code snippet in #Python
Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/lexical_analyzer | Compiler/lexical analyzer | Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als... | #Euphoria | Euphoria | include std/io.e
include std/map.e
include std/types.e
include std/convert.e
constant true = 1, false = 0, EOF = -1
enum tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq,
tk_Gtr, tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While,
tk_Print, tk_Putc, tk... | Give a code snippet in #Euphoria
Definition from Wikipedia:
Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #REXX | REXX | roman: procedure
arg number
/* handle only 1 to 3999, else return ? */
if number >= 4000 | number <= 0 then return "?"
romans = " M CM D CD C XC L XL X IX V IV I"
arabic = "1000 900 500 400 100 90 50 40 10 9 5 4 1"
result = ""
do i = 1 to words(romans)
do while number >= word(arabic,i)
r... | Give a code snippet in #REXX
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a valu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Maxima | Maxima | ackermann(m, n) := if integerp(m) and integerp(n) then ackermann[m, n] else 'ackermann(m, n)$
ackermann[m, n] := if m = 0 then n + 1
elseif m = 1 then 2 + (n + 3) - 3
elseif m = 2 then 2 * (n + 3) - 3
elseif m = 3 then 2^(n + 3) - 3
elseif n ... | Give a code snippet in #Maxima
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Aime | Aime | # prints "97"
o_integer('a');
o_byte('\n');
# prints "a"
o_byte(97);
o_byte('\n'); | Give a code snippet in #Aime
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).
Conve... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:... | #Raku | Raku | .say for sort ~«dir | Give a code snippet in #Raku
Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #F.23 | F# |
let copy()=let n,g=stdin,stdout
let rec fN()=match n.ReadLine() with "EOF"->g.Write "" |i->g.WriteLine i; fN()
fN()
copy()
| Give a code snippet in #F.23
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| 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 ... | #Liberty_BASIC | Liberty BASIC | print isPalindrome("In girum imus nocte et consumimur igni")
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S"))
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC"))
function isPalindrome(string$)
isPalindrome = 1
for i = 1 to int(len(string$... | Give a code snippet in #Liberty_BASIC
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 (pos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Julia | Julia | randn(1000) * 0.5 + 1 | Give a code snippet in #Julia
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also trivalent, ternary, or trinary... | #Maple | Maple | tv := [true, false, FAIL];
NotTable := Array(1..3, i->not tv[i] );
AndTable := Array(1..3, 1..3, (i,j)->tv[i] and tv[j] );
OrTable := Array(1..3, 1..3, (i,j)->tv[i] or tv[j] );
XorTable := Array(1..3, 1..3, (i,j)->tv[i] xor tv[j] );
ImpliesTable := Array(1..3, 1..3, (i,j)->tv[i] implies tv[j] ); | Give a code snippet in #Maple
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat... | #Quackery | Quackery | [ ' stack nested nested
' share nested join
swap nested join
dup dup 0 peek put ] is recursive ( x --> x )
[ over 2 < iff
[ 2drop 1 ] done
dip [ dup 1 - ] do * ] is factorial ( n x --> n )
[ over 2 < iff drop done
swap 1 - tuck 1 -
over do dip do + ] is fibonacci ( n x --... | Give a code snippet in #Quackery
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Active_object | Active object | In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync... | #PicoLisp | PicoLisp | (load "@lib/math.l")
(class +Active)
# inp val sum usec
(dm T ()
(unless (assoc -100 *Run) # Install timer task
(task -100 100 # Update objects every 0.1 sec
(mapc 'update> *Actives) ) )
(=: inp '((U) 0)) # Set zero input function
(=: val 0) ... | Give a code snippet in #PicoLisp
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of suc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #Ada | Ada | with Ada.Text_IO;
with Ada.Strings.Fixed;
procedure Kaprekar2 is
use Ada.Strings.Fixed;
To_Digit : constant String := "0123456789abcdefghijklmnopqrstuvwxyz";
type Int is mod 2 ** 64;
subtype Base_Number is Int range 2 .. 36;
From_Digit : constant array (Character) of Int :=
('0' => 0,
... | Give a code snippet in #Ada
A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fraction_reduction | Fraction reduction | There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simp... | #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FractionReduction {
public static void main(String[] args) {
for ( int size = 2 ; size <= 5 ; size++ ) {
reduce(size);
}
}
private... | Give a code snippet in #Java
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16... | 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
... | #Mond | Mond | fun quicksort( arr, cmp )
{
if( arr.length() < 2 )
return arr;
if( !cmp )
cmp = ( a, b ) -> a - b;
var a = [ ], b = [ ];
var pivot = arr[0];
var len = arr.length();
for( var i = 1; i < len; ++i )
{
var item = arr[i];
if( cmp( item, pivot ) < cmp( pivot... | Give a code snippet in #Mond
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/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
≤... | #Oforth | Oforth | import: mapping
System.Console accept words map( #>integer) reduce( #+ ) printcr . | Give a code snippet in #Oforth
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, separat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Go | Go | package main
import "fmt"
import "time"
func main() {
for year := 2008; year <= 2121; year++ {
if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==
time.Sunday {
fmt.Printf("25 December %d is Sunday\n", year)
}
}
} | Give a code snippet in #Go
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 200... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there... | #Haskell | Haskell | import Data.Numbers.Primes (primes)
-- generates consecutive subsequences defined by given equivalence relation
consecutives equiv = filter ((> 1) . length) . go []
where
go r [] = [r]
go [] (h : t) = go [h] t
go (y : ys) (h : t)
| y `equiv` h = go (h : y : ys) t
| otherwise = (y : ys) : go ... | Give a code snippet in #Haskell
Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for pr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Haskell | Haskell | let q s = putStrLn (s ++ show s) in q "let q s = putStrLn (s ++ show s) in q " | Give a code snippet in #Haskell
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Factor | Factor | USING: formatting math.functions ;
5 3 2 ^ ^
"5 3 2 ^ ^ %d\n" printf
5 3 ^ 2 ^
"5 3 ^ 2 ^ %d\n" printf | Give a code snippet in #Factor
This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
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
... | #Smalltalk | Smalltalk | #(7 5 2 9 0 -1) asSortedCollection | Give a code snippet in #Smalltalk
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 |
Quic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #JavaScript | JavaScript | // returns a new matrix
Matrix.prototype.mult = function(other) {
if (this.width != other.height) {
throw "error: incompatible sizes";
}
var result = [];
for (var i = 0; i < this.height; i++) {
result[i] = [];
for (var j = 0; j < other.width; j++) {
var sum = 0;
... | Give a code snippet in #JavaScript
Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Common_Lisp | Common Lisp | ;;A macro was used to ensure that the filter is inlined.
;;Larry Hignight. Last updated on 7/3/2012.
(defmacro kaprekar-number-filter (n &optional (base 10))
`(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))
(defun test (&key (start 1) (stop 10000) (base 10) (collect t))
(let ((count 0)
(nums))
(loop f... | Give a code snippet in #Common_Lisp
Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star | Pseudo-random numbers/Xorshift star | Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bits of value shifted left or ri... | #Raku | Raku | class Xorshift-star {
has $!state;
submethod BUILD ( Int :$seed where * > 0 = 1 ) { $!state = $seed }
method next-int {
$!state +^= $!state +> 12;
$!state +^= $!state +< 25 +& (2⁶⁴ - 1);
$!state +^= $!state +> 27;
($!state * 0x2545F4914F6CDD1D) +> 32 +& (2³² - 1)
}
... | Give a code snippet in #Raku
Some definitions to help in the explanation
Floor operation
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Greatest integer less than or equal to a real number.
Bitwise Logical shift operators (c-inspired)
https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Binary bi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/JortSort | JortSort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Janet | Janet | (defn jortsort [xs]
(deep= xs (sorted xs)))
(print (jortsort @[1 2 3 4 5])) # true
(print (jortsort @[2 1 3 4 5])) # false | Give a code snippet in #Janet
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/Anti-primes | Anti-primes | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program antiprime64.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ NMAXI, 20
.equ MAXLINE, 5
/*********************************/
/* In... | Give a code snippet in #AArch64_Assembly
The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
Task
Generate and show here, the first twenty anti-primes.
Related tasks
Factors of an integer
Sieve of Eratosthenes... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #JavaScript | JavaScript | function Complex(r, i) {
this.r = r;
this.i = i;
}
Complex.add = function() {
var num = arguments[0];
for(var i = 1, ilim = arguments.length; i < ilim; i += 1){
num.r += arguments[i].r;
num.i += arguments[i].i;
}
return num;
}
Complex.multiply = function() {
var num = arguments[0];
for(var i = 1, ... | Give a code snippet in #JavaScript
A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\disp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #AutoHotkey | AutoHotkey | global U0 := Exception("First Exception")
global U1 := Exception("Second Exception")
foo()
foo(){
try
bar()
catch e
MsgBox % "An exception was raised: " e.Message
bar()
}
bar(){
baz()
}
baz(){
static calls := 0
if ( ++calls = 1 )
throw U0
else if ( calls = 2 )
throw U1
} | Give a code snippet in #AutoHotkey
Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var bellTriangle = Fn.new { |n|
var tri = List.filled(n, null)
for (i in 0...n) {
tri[i] = List.filled(i, null)
for (j in 0...i) tri[i][j] = BigInt.zero
}
tri[1][0] = BigInt.one
for (i in 2...n) {
tri[i][0] = tri[i-1][i-2]
... | Give a code snippet in #Wren
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #min | min | (over over + rolldown pop pick +) :next
(('print dip " " print! next) 25 times newline) :leo
"First 25 Leonardo numbers:" puts!
1 1 1 leo
"First 25 Leonardo numbers with add=0, L(0)=0, L(1)=1:" puts!
0 0 1 leo | Give a code snippet in #min
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L... | 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
⋮
⋮
⋮
⋱
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | IdentityMatrix[4] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
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
... | 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
... | #PL.2FI | PL/I | MRGEPKG: package exports(MERGESORT,MERGE,RMERGE);
DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */
MERGE: PROCEDURE (A,LA,B,LB,C,CMPFN);
DECLARE (A(*),B(*),C(*)) CHAR(*) VAR;
DECLARE (LA,LB) FIXED BIN(31) NONASGN;
DECLARE (I,J,K) FIXED BIN(31);
DECLARE CMPFN ENTRY(
NONASGN CHAR(*) VA... | Give a code snippet in #PL.2FI
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Tcl | Tcl | package require Tcl 8.5
# Build a grid
proc makeGrid {w h {treeProbability 0.5}} {
global grid gridW gridH
set gridW $w
set gridH $h
set grid [lrepeat $h [lrepeat $w " "]]
for {set x 0} {$x < $w} {incr x} {
for {set y 0} {$y < $h} {incr y} {
if {rand() < $treeProbability} {
lset grid $y $x... | Give a code snippet in #Tcl
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Sc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fast_Fourier_transform | Fast Fourier transform | Task
Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)... | #Racket | Racket |
#lang racket
(require math)
(array-fft (array #[1. 1. 1. 1. 0. 0. 0. 0.]))
| Give a code snippet in #Racket
Task
Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magn... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 ... | #Factor | Factor | USING: assocs grouping grouping.extras io kernel literals math
math.combinatorics math.ranges prettyprint project-euler.common
sequences sequences.extras sets ;
CONSTANT: digits $[ 2 9 [a..b] ]
: (colorful?) ( seq -- ? )
all-subseqs [ product ] map all-unique? ;
: colorful? ( n -- ? )
[ t ] [ number>digit... | Give a code snippet in #Factor
A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
E... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #Haskell | Haskell | import Numeric (showOct)
main :: IO ()
main =
mapM_
(putStrLn . flip showOct "")
[1 ..] | Give a code snippet in #Haskell
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.... | 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... | #Groovy | Groovy | import groovy.xml.MarkupBuilder
def createTable(columns, rowCount) {
def writer = new StringWriter()
new MarkupBuilder(writer).table(style: 'border:1px solid;text-align:center;') {
tr {
th()
columns.each { title -> th(title)}
}
(1..rowCount).each { row ->
... | Give a code snippet in #Groovy
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/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #ERRE | ERRE |
PROGRAM BRESENHAM
!$INCLUDE="PC.LIB"
PROCEDURE BRESENHAM
! === Draw a line using graphic coordinates
! Inputs are X1, Y1, X2, Y2: Destroys value of X1, Y1
dx=ABS(x2-x1) sx=-1
IF x1<x2 THEN sx=1
dy=ABS(y2-y1) sy=-1
IF y1<y2 THEN sy=1
er=-dy
IF dx>dy THEN er=dx
er=INT(er/2)
LOOP
PSET(x1,y1,1)
EXIT IF x1=x2 AN... | Give a code snippet in #ERRE
Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Nim | Nim | import random, sequtils, strformat, strutils
type Color {.pure.} = enum Red = "R", Black = "B"
proc `$`(s: seq[Color]): string = s.join(" ")
# Create pack, half red, half black and shuffle it.
var pack = newSeq[Color](52)
for i in 0..51: pack[i] = Color(i < 26)
pack.shuffle()
# Deal from pack into 3 stacks.
var... | Give a code snippet in #Nim
Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the ... | 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... | #Icon_and_Unicon | Icon and Unicon | procedure main() #: demonstrate various ways to sort a list and string
demosort(combsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure combsort(X,op) #: return sorted X
local gap,swapped,i
op := sortop(op,X) # select how and what we sort
swapp... | Give a code snippet in #Icon_and_Unicon
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... | 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
... | #HicEst | HicEst | CHARACTER string = "Hello World", tmp
L = LEN( string )
DO i = 1, L/2
tmp = string(i)
string(i) = string(L-i+1)
string(L-i+1) = tmp
ENDDO
WRITE(Messagebox, Name) string | Give a code snippet in #HicEst
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
Empt... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Arturo | Arturo | fileFrom: "input.txt"
fileTo: "output.txt"
docsFrom: "docs"
docsTo: "mydocs"
rename fileFrom fileTo
rename.directory docsFrom docsTo
rename join.path ["/" fileFrom]
join.path ["/" fileTo]
rename.directory join.path ["/" docsFrom]
join.path ["/" docsTo] | Give a code snippet in #Arturo
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Euphoria | Euphoria | function multiply( atom a, atom b )
return a * b
end function | Give a code snippet in #Euphoria
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func v2(n uint) (r float64) {
p := .5
for n > 0 {
if n&1 == 1 {
r += p
}
p *= .5
n >>= 1
}
return
}
func newV(base uint) func(uint) float64 {
invb := 1 / float64(base)
return func(n uint) (r float64) {
p := invb
... | Give a code snippet in #F.C5.8Drmul.C3.A6
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unbias_a_random_generator | Unbias a random generator |
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to create a function/method/sub... | #Lua | Lua |
local function randN(n)
return function()
if math.random() < 1/n then return 1 else return 0 end
end
end
local function unbiased(n)
local biased = randN (n)
return function()
local a, b = biased(), biased()
while a==b do
a, b = biased(), biased()
end
return a
end
end
local func... | Give a code snippet in #Lua
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
P
0
{\displaystyle P_{0}}
P
0
{\displaystyle P_{0}}
P
1
{\displaystyle P_{1}}
Task details
Use your language's random number generator to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #TorqueScript | TorqueScript | While(1)
echo("SPAM"); | Give a code snippet in #TorqueScript
Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
... | 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)
... | #Java | Java |
public class FizzBuzz {
public static void main(String[] args) {
for (int number = 1; number <= 100; number++) {
if (number % 15 == 0) {
System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
System.out.println("Fizz");
} else if (... | Give a code snippet in #Java
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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.
| #D | D | import std.exception: enforce;
int foo(in bool condition) pure nothrow
in {
// Assertions are used in contract programming.
assert(condition);
} out(result) {
assert(result > 0);
} body {
if (condition)
return 42;
// assert(false) is never stripped from the code, it generates an
// e... | Give a code snippet in #D
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/Quoting_constructs | Quoting constructs | Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati... | #Nim | Nim |
echo "A simple string."
echo "A simple string including tabulation special character \\t: \t."
echo """
First part of a multiple string,
followed by second part
and third part.
"""
echo r"A raw string containing a \."
# Interpolation in strings.
import strformat
const C = "constant"
const S = fmt"A string with ... | Give a code snippet in #Nim
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their ... | 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
... | #jq | jq | def rms: length as $length
| if $length == 0 then null
else map(. * .) | add | sqrt / $length
end ; | Give a code snippet in #jq
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/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 30
x = 2.5
y = 3
pad = 40
say
say 'Java Math constants & functions:'
say Rexx(' Euler''s number (e):').left(pad) Math.E
say Rexx(' Pi:').left(pad) Math.PI
say Rex... | Give a code snippet in #NetRexx
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in... | #Java | Java | public class Narc{
public static boolean isNarc(long x){
if(x < 0) return false;
String xStr = Long.toString(x);
int m = xStr.length();
long sum = 0;
for(char c : xStr.toCharArray()){
sum += Math.pow(Character.digit(c, 10), m);
}
return sum == x;
}
public static void main(String[] args){
for... | Give a code snippet in #Java
A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Phix | Phix | without js -- (threads)
procedure echo(string s)
sleep(rand(100)/100)
enter_cs()
puts(1,s)
puts(1,'\n')
leave_cs()
end procedure
constant threads = {create_thread(routine_id("echo"),{"Enjoy"}),
create_thread(routine_id("echo"),{"Rosetta"}),
create_thread(rou... | Give a code snippet in #Phix
Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your la... | 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... | #Scala | Scala | object ProbabilisticChoice extends App {
import scala.collection.mutable.LinkedHashMap
def weightedProb[A](prob: LinkedHashMap[A,Double]): A = {
require(prob.forall{case (_, p) => p > 0 && p < 1})
assume(prob.values.sum == 1)
def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A... | Give a code snippet in #Scala
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 flo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | $RecursionLimit=10^6 | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| 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... | #Quackery | Quackery | > quackery
Welcome to Quackery.
Enter "leave" to leave the shell.
Building extensions.
/O> ' tuck take
...
Quackery system damage detected.
Python reported: maximum recursion depth exceeded | Give a code snippet in #Quackery
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 de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two ... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/2048
use warnings;
use Tk;
my $N = shift // 4;
$N < 2 and $N = 2;
my @squares = 1 .. $N*$N;
my %n2ch = (' ' => ' ');
@n2ch{ map 2**$_, 1..26} = 'a'..'z';
my %ch2n = reverse %n2ch;
my $winner = '';
my @arow = 0 .. $N - 1;
my @acol = map $_ * $N, @arow;
my ... | Give a code snippet in #Perl
Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Dart | Dart | Iterable<int> primesMap() {
Iterable<int> oddprms() sync* {
yield(3); yield(5); // need at least 2 for initialization
final Map<int, int> bpmap = {9: 6};
final Iterator<int> bps = oddprms().iterator;
bps.moveNext(); bps.moveNext(); // skip past 3 to 5
int bp = bps.current;
int n ... | Give a code snippet in #Dart
Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or progr... | 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... | #PHP | PHP | $numbers = "49927398716 49927398717 1234567812345678 1234567812345670";
foreach (split(' ', $numbers) as $n)
echo "$n is ", luhnTest($n) ? 'valid' : 'not valid', '</br>';
function luhnTest($num) {
$len = strlen($num);
for ($i = $len-1; $i >= 0; $i--) {
$ord = ord($num[$i]);
if (($len - 1) ... | Give a code snippet in #PHP
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 t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #JavaScript | JavaScript | function isHarshad(n) {
var s = 0;
var n_str = new String(n);
for (var i = 0; i < n_str.length; ++i) {
s += parseInt(n_str.charAt(i));
}
return n % s === 0;
}
var count = 0;
var harshads = [];
for (var n = 1; count < 20; ++n) {
if (isHarshad(n)) {
count++;
harshads.pu... | Give a code snippet in #JavaScript
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The ... | 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... | #Swift | Swift | import Foundation
let monthWidth = 20
let monthGap = 2
let dayNames = "Su Mo Tu We Th Fr Sa"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
func rpad(string: String, width: Int) -> String {
return string.count >= width ? string
: String(repeating: " ", count: width - string.count)... | Give a code snippet in #Swift
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/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
roots(10)
end
procedure roots(n)
every n := 2 to 10 do
every writes(n | (str_rep((0 to (n-1)) * 2 * &pi / n)) | "\n")
end
procedure str_rep(k)
return " " || cos(k) || "+" || sin(k) || "i"
end | Give a code snippet in #Icon_and_Unicon
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Forth | Forth | : vector create ( n -- ) 0 do , loop does> ( n -- ) swap cells + @ execute ;
\ these are ( numerals -- numerals )
: ,I dup c@ C, ; : ,V dup 1 + c@ C, ; : ,X dup 2 + c@ C, ;
\ these are ( numerals -- )
:noname ,I ,X drop ; :noname ,V ,I ,I ,I drop ; :noname ,V ,I ,I drop ;
:noname ,V ,I dr... | Give a code snippet in #Forth
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a val... | 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)
... | #C | C | int i = 0 ; char B[88] ;
while ( i++ < 100 )
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B ); | Give a code snippet in #C
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Rust | Rust | fn fact(n:u32) -> u64 {
let mut f:u64 = n as u64;
for i in 2..n {
f *= i as u64;
}
return f;
}
fn choose(n: u32, k: u32) -> u64 {
let mut num:u64 = n as u64;
for i in 1..k {
num *= (n-i) as u64;
}
return num / fact(k);
}
fn main() {
println!("{}", choose(5,3));
} | Give a code snippet in #Rust
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #MUMPS | MUMPS | MENU(STRINGS,SEP)
;http://rosettacode.org/wiki/Menu
NEW I,A,MAX
;I is a loop variable
;A is the string read in from the user
;MAX is the number of substrings in the STRINGS list
;SET STRINGS="fee fie^huff and puff^mirror mirror^tick tock"
SET MAX=$LENGTH(STRINGS,SEP)
QUIT:MAX=0 ""
WRITEMENU
FOR I=1:1:MAX WRIT... | Give a code snippet in #MUMPS
Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the stri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo... | #Axe | Axe | 123→float{L₁}
float{L₁}→I | Give a code snippet in #Axe
Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/AB... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind | Stirling numbers of the second kind | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 ... | #J | J | test=: 1 i.~ (0 = *) , =
s2=: 0:`1:`($:&<: + ] * <:@:[ $: ])@.test M.
s2&>table i. 13
+----+--------------------------------------------------------------------+
|s2&>|0 1 2 3 4 5 6 7 8 9 10 11 12|
+----+------------------------------------------------------------------... | Give a code snippet in #J
Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #QB64 | QB64 | OPEN "knapsack.txt" FOR OUTPUT AS #1
N=7: L=5: a = 2^(N+1): RANDOMIZE TIMER 'knapsack.bas DANILIN
DIM L(N), C(N), j(N), q(a), q$(a), d(a)
FOR m=a-1 TO (a-1)/2 STEP -1: g=m: DO ' cipher 0-1
q$(m)=LTRIM$(STR$(g MOD 2))+q$(m)
g=g\2: LOOP UNTIL g=0
q$(m)=MID$(q$(m), 2, LEN(q$(m)))
NEXT
FOR i=1 TO N: L(i)=I... | Give a code snippet in #QB64
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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #LOLCODE | LOLCODE |
HAI
CAN HAS STDIO?
VISIBLE "Hello world!"
KTHXBYE
| Give a code snippet in #LOLCODE
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error... | christopher/rosetta-code | |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #jq | jq | $ jq -n 'now | [., todate]'
[
1437619000.970498,
"2015-07-23T02:36:40Z"
] | Give a code snippet in #jq
Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Dat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Factor | Factor | USING: io.encodings.ascii io.encodings.binary io.files ;
! to read entire file as binary
"foo.txt" binary file-contents
! to read entire file as lines of text
"foo.txt" ascii file-lines | Give a code snippet in #Factor
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incr... | 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... | #LOLCODE | LOLCODE | local bottles = 99
local function plural (bottles) if bottles == 1 then return '' end return 's' end
while bottles > 0 do
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print (bottles..' bottle'..plural(bottles)..' of beer')
print ('Take one down, pass it around')
bottles = bottle... | Give a code snippet in #LOLCODE
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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 |... | #Racket | Racket |
#lang racket
;; a naive version
(define (naive-factors n)
(for/list ([i (in-range 1 (add1 n))] #:when (zero? (modulo n i))) i))
(naive-factors 120) ; -> '(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)
;; much better: use `factorize' to get prime factors and construct the
;; list of results from that
(require math)... | Give a code snippet in #Racket
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/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
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
... | #PureBasic | PureBasic | Procedure KnuthShuffle (Array a(1))
Protected i, Size = ArraySize(a())
For i = 0 To Size
Swap a(i), a(Random(Size))
Next
EndProcedure
Procedure isSorted(Array a(1))
Protected i, Size = ArraySize(a())
For i = 1 To Size
If a(i) < a(i - 1)
ProcedureReturn #False
EndIf
Next
... | Give a code snippet in #PureBasic
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 |
Quic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Lasso | Lasso | dns_lookup('www.kame.net', -type='A') | Give a code snippet in #Lasso
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #68000_Assembly | 68000 Assembly | In addition, for nearby subroutines, BSR can be used in place of JSR to save data. There is also BRA (branch always) for unconditional local jumping, which the original 6502 didn't have.
| Give a code snippet in #68000_Assembly
Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #D | D |
program btm2ppm;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
Vcl.Graphics;
type
TBitmapHelper = class helper for TBitmap
public
procedure SaveAsPPM(FileName: TFileName);
end;
{ TBitmapHelper }
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName);
var
i, j, color... | Give a code snippet in #D
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| 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
| #UNIX_Shell | UNIX Shell | keys=( foo bar baz )
values=( 123 456 789 )
declare -A hash
for (( i = 0; i < ${#keys[@]}; i++ )); do
hash["${keys[i]}"]=${values[i]}
done
for key in "${!hash[@]}"; do
printf "%s => %s\n" "$key" "${hash[$key]}"
done | Give a code snippet in #UNIX_Shell
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/Unix/ls | Unix/ls | Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Example output
For the list of paths:... | #S-lang | S-lang | variable d = listdir(getcwd()), p;
foreach p (array_sort(d))
() = printf("%s\n", d[p] ); | Give a code snippet in #S-lang
Task
Write a program that will list everything in the current folder, similar to:
the Unix utility “ls” [1] or
the Windows terminal command “DIR”
The output must be sorted, but printing extended details and producing multi-column output is not required.
Examp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The ... | #Groovy | Groovy | enum Op {
ADD('+', 2),
SUBTRACT('-', 2),
MULTIPLY('*', 1),
DIVIDE('/', 1);
static {
ADD.operation = { a, b -> a + b }
SUBTRACT.operation = { a, b -> a - b }
MULTIPLY.operation = { a, b -> a * b }
DIVIDE.operation = { a, b -> a / b }
}
final String symbol
... | Give a code snippet in #Groovy
Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a s... | 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... | #Shiny | Shiny | text: '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$... | Give a code snippet in #Shiny
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 lef... | 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... | #Rust | Rust | vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0] | Give a code snippet in #Rust
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 |
Q... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Standard_ML | Standard ML | OS.Process.system "ls" | Give a code snippet in #Standard_ML
Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Uni... | #Euphoria | Euphoria | function reverse(sequence s, integer first, integer last)
object x
while first < last do
x = s[first]
s[first] = s[last]
s[last] = x
first += 1
last -= 1
end while
return s
end function
function nextPermutation(sequence s)
integer pos, last
object x
... | Give a code snippet in #Euphoria
Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations g... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fractran | Fractran | FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
... | #Common_Lisp | Common Lisp | (defun fractran (n frac-list)
(lambda ()
(prog1
n
(when n
(let ((f (find-if (lambda (frac)
(integerp (* n frac)))
frac-list)))
(when f (setf n (* f n))))))))
;; test
(defvar *primes-ft* '(17/91 78/85 19/51 23/38 29/33 77/29 ... | Give a code snippet in #Common_Lisp
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. 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)
Benford's law, also called the first-digit law, refers to the freque... | #SQL | SQL | -- Create table
CREATE TABLE benford (num INTEGER);
-- Seed table
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (2);
-- Populate table
INSERT INTO benford (num)
SELECT
ult + penult
FROM
(SELECT MAX(num) AS ult FROM benford),
(SELECT MAX(... | Give a code snippet in #SQL
This page uses content from Wikipedia. The original article was at Benford's_law. 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)
Benford's law, also called the first-di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Nim | Nim | const Limit = 100
var mcnuggets: array[0..Limit, bool]
for a in countup(0, Limit, 6):
for b in countup(a, Limit, 9):
for c in countup(b, Limit, 20):
mcnuggets[c] = true
for n in countdown(Limit, 0):
if not mcnuggets[n]:
echo "The largest non-McNuggets number is: ", n
break | Give a code snippet in #Nim
Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugg... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of thi... | #R | R | s <- " Ars Longa "
trimws(s)
[1] "Ars Longa"
trimws(s, "left")
[1] "Ars Longa "
trimws(s, "right")
[1] " Ars Longa" | Give a code snippet in #R
Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace remove... | christopher/rosetta-code | |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #M2000_Interpreter | M2000 Interpreter |
Module Puzzle15 {
00 BASE 1 : DEF RND(X)=RND
10 REM 15-PUZZLE GAME
20 REM COMMODORE BASIC 2.0
30 REM ********************************
40 GOSUB 400 : REM INTRO AND LEVEL
50 GOSUB 510 : REM SETUP BOARD
60 GOSUB 210 : REM PRINT PUZZLE
70 PRINT "TO MOVE A PIECE, ENTER ITS... | Give a code snippet in #M2000_Interpreter
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #VBScript | VBScript |
For h = 1 To 20
WScript.StdOut.Write "H(" & h & ") = " & Hamming(h)
WScript.StdOut.WriteLine
Next
WScript.StdOut.Write "H(" & 1691 & ") = " & Hamming(1691)
WScript.StdOut.WriteLine
Function Hamming(l)
Dim h() : Redim h(l) : h(0) = 1
i = 0 : j = 0 : k = 0
x2 = 2 : x3 = 3 : x5 = 5
For n = 1 To l-1
m = x2
If... | Give a code snippet in #VBScript
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write ... | #Phix | Phix | with javascript_semantics
enum X, Y
function shoelace(sequence s)
atom t = 0
if length(s)>2 then
s = append(deep_copy(s),s[1])
for i=1 to length(s)-1 do
t += s[i][X]*s[i+1][Y] - s[i+1][X]*s[i][Y]
end for
end if
return abs(t)/2
end function
constant test = {{3,4},{5,... | Give a code snippet in #Phix
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #XPL0 | XPL0 | Give a code snippet in #XPL0
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Deconvolution/1D | Deconvolution/1D | The convolution of two functions
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
of
an integer variable is defined as the function
G
{\displaystyle {\mathit {G}}}
satisfying
G
(
n
)
=
∑
m
=
−
∞
∞
F
(
m
)
H
(
n
−
m
)
{\displaystyle G(n)=\sum _{m=-\inft... | #Ursala | Ursala | #import std
#import nat
band = pad0+ ~&rSS+ zipt^*D(~&r,^lrrSPT/~<K33tx zipt^/~&r ~&lSNyCK33+ zipp0)^/~&rx ~&B->NlNSPC ~&bt
deconv = lapack..dgelsd^\~&l ~&||0.!**+ band
| Give a code snippet in #Ursala
The convolution of two functions
F
{\displaystyle {\mathit {F}}}
and
H
{\displaystyle {\mathit {H}}}
of
an integer variable is defined as the function
G
{\displaystyle {\mathit {G}}}
satisfying
G
(
n
)
=
∑
m
=
−
∞
∞
F
(
m
)
H
(
n
−
m
)
{\d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #Fortran | Fortran | Inspecting sums of proper divisors for 1 to 20000
Deficient 15043
Perfect! 4
Abundant 4953
| Give a code snippet in #Fortran
These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficie... | 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... | #Forth | Forth | : myloop 11 1 do i . loop cr ; myloop | Give a code snippet in #Forth
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 langua... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Agena | Agena | print( "Hello world!" ) | Give a code snippet in #Agena
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.