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/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #ALGOL_60 | ALGOL 60 | INTEGER I,J;
FOR I:=1 STEP 1 UNTIL 5 DO
BEGIN
FOR J:=1 STEP 1 UNTIL I DO
OUTTEXT("*");
OUTLINE
END
| Give a code snippet in #ALGOL_60
“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract stru... | 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... | #Bracmat | Bracmat | put$str$("5^3^2: " 5^3^2 "\n(5^3)^2: " (5^3)^2 "\n5^(3^2): " 5^(3^2) \n) | Give a code snippet in #Bracmat
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
Sho... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Heronian_triangles | Heronian triangles | Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
+
b
+
c
2
.
{\displaystyle s... | #Fortran | Fortran |
MODULE GREEK MATHEMATICIANS !Two millenia back and more.
CONTAINS
INTEGER FUNCTION GCD(I,J) !Greatest common divisor.
INTEGER I,J !Of these two integers.
INTEGER N,M,R !Workers.
N = MAX(I,J) !Since I don't want to damage I or J,
M = MIN(I,J) !These copies mig... | Give a code snippet in #Fortran
Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. 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)
The haversine formula is an equation important in navigation, g... | #FBSL | FBSL | #APPTYPE CONSOLE
PRINT "Distance = ", Haversine(36.12, -86.67, 33.94, -118.4), " km"
PAUSE
FUNCTION Haversine(DegLat1 AS DOUBLE, DegLon1 AS DOUBLE, DegLat2 AS DOUBLE, DegLon2 AS DOUBLE) AS DOUBLE
CONST radius = 6372.8
DIM dLat AS DOUBLE = D2R(DegLat2 - DegLat1)
DIM dLon AS DOUBLE = D2R(DegLon2 - DegLon1... | Give a code snippet in #FBSL
This page uses content from Wikipedia. The original article was at Haversine formula. 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)
The haversine formula is an equat... | 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 ... | #PL.2FI | PL/I |
/* 4-BIT ADDER */
TEST: PROCEDURE OPTIONS (MAIN);
DECLARE CARRY_IN BIT (1) STATIC INITIAL ('0'B) ALIGNED;
declare (m, n, sum)(4) bit(1) aligned;
declare i fixed binary;
get edit (m, n) (b(1));
put edit (m, ' + ', n, ' = ') (4 b, a);
do i = 4 to 1 by -1;
call full_adder ((carry_in), m(i),... | Give a code snippet in #PL.2FI
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/Heronian_triangles | Heronian triangles | Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
+
b
+
c
2
.
{\displaystyle s... | #Ada | Ada | with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;
procedure Heronian is
package Int_IO is new Ada.Text_IO.Integer_IO(Integer);
use Int_IO;
-- ----- Some math...
function GCD (A, B : in Natural) return Natural is (if B = 0 then A else GCD (B, A mod B));
... | Give a code snippet in #Ada
Hero's formula for the area of a triangle given the length of its three sides a, b, and c is given by:
A
=
s
(
s
−
a
)
(
s
−
b
)
(
s
−
c
)
,
{\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},}
where s is half the perimeter of the triangle; that is,
s
=
a
+
b
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
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
... | #Ruby | Ruby | ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']
p ary.uniq # => [1, 2, "redundant", [1, 2, 3]] | Give a code snippet in #Ruby
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/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #HicEst | HicEst | ! Strings and arrays must be declared.
! Everything else is 8-byte float, READ/WRITE converts
CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/
REAL, PARAMETER :: named_constant = 3.1415
REAL :: n=2, cols=4, vec(cols), mtx(n, cols)
DATA vec/2,3,4,5/, mtx/1,2,3.1415,4, 5,6,7,8/
named = ALIAS(alpha, beta, ga... | Give a code snippet in #HicEst
Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5... | #Delphi | Delphi |
program ProperDivisors;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections;
type
TProperDivisors = TArray<Integer>;
function GetProperDivisors(const value: Integer): TProperDivisors;
var
i, count: Integer;
begin
count := 0;
for i := 1 to value div 2 do
begin
... | Give a code snippet in #Delphi
The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass... | #Wren | Wren | import "/fmt" for Fmt
// 'cpx' returns integer index from 0 to 31 corresponding to compass point.
// Input heading h is in degrees. Note this index is a zero-based index
// suitable for indexing into the table of printable compass points,
// and is not the same as the index specified to be printed in the output.
var... | Give a code snippet in #Wren
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and dis... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
... | #Rust | Rust |
use std::env;
use std::io::{BufReader, Lines};
use std::io::prelude::*;
use std::fs::File;
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).unwrap();
for line in FastaIter::new(f) {
println!("{}", line);
}
}
struct FastaIter<T> {
buffer_lines: Lin... | Give a code snippet in #Rust
In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosett... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11... | #uBasic.2F4tH | uBasic/4tH | Push 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124
Push 0, 13 : Gosub _Read ' read 1st line of data
Push 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123
Push 14, 27 : Gosub _Read ' read 2nd line of data
Push 35, 113, 122, 42, 117, 119, 58, 10... | Give a code snippet in #uBasic.2F4tH
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32... | christopher/rosetta-code | |
http://rosettacode.org/wiki/QR_decomposition | QR decomposition | Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, as described in QR decompositi... | #Tcl | Tcl | package require Tcl 8.5
namespace path {::tcl::mathfunc ::tcl::mathop}
proc sign x {expr {$x == 0 ? 0 : $x < 0 ? -1 : 1}}
proc norm vec {
set s 0
foreach x $vec {set s [expr {$s + $x**2}]}
return [sqrt $s]
}
proc unitvec n {
set v [lrepeat $n 0.0]
lset v 0 1.0
return $v
}
proc I n {
set m [l... | Give a code snippet in #Tcl
Any rectangular
m
×
n
{\displaystyle m\times n}
matrix
A
{\displaystyle {\mathit {A}}}
can be decomposed to a product of an orthogonal matrix
Q
{\displaystyle {\mathit {Q}}}
and an upper (right) triangular matrix
R
{\displaystyle {\mathit {R}}}
, a... | 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... | #Burlesque | Burlesque |
ps^^-]to{"Int""Double"}\/~[\/L[1==?*
| Give a code snippet in #Burlesque
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:
Metric... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity | Abelian sandpile model/Identity | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by a... | #Wren | Wren | import "/fmt" for Fmt
class Sandpile {
static init() {
__neighbors = [
[1, 3], [0, 2, 4], [1, 5], [0, 4, 6], [1, 3, 5, 7], [2, 4, 8], [3, 7], [4, 6, 8], [5, 7]
]
}
// 'a' is a list of 9 integers in row order
construct new(a) {
_a = a
}
a { _a }
+(o... | Give a code snippet in #Wren
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Common_Lisp | Common Lisp |
(defparameter *s* "") ;; Binds dynamic variable *S* to the empty string ""
(let ((s "")) ;; Binds the lexical variable S to the empty string ""
(= (length s) 0) ;; Check if the string is empty
(> (length s) 0)) ;; Check if length of string is over 0 (that is: non-empty)
| Give a code snippet in #Common_Lisp
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ... | #Python | Python | def lcs(xstr, ystr):
"""
>>> lcs('thisisatest', 'testing123testing')
'tsitest'
"""
if not xstr or not ystr:
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return str(lcs(xs, ys)) + x
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len) | Give a code snippet in #Python
Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be stri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #360_Assembly | 360 Assembly | * value of F
L 2,F assigment r2=f
* reference (or address) of F
LA 3,F reference r3=@f
* referencing (or indexing) of reg3 (r3->f)
L 4,0(3) referencing r4=%r3=%@f=f | Give a code snippet in #360_Assembly
Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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.
| #Raku | Raku | raku -pe'.lines' | Give a code snippet in #Raku
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/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #PicoLisp | PicoLisp | (load "@lib/openGl.l")
(setq *JoyX 0.0 *JoyY 0.0)
(glutInit)
(glutInitDisplayMode (| GLUT_RGBA GLUT_DOUBLE GLUT_ALPHA GLUT_DEPTH))
(glutInitWindowSize 400 400)
(glutCreateWindow "Joystick")
(glClearColor 0.3 0.3 0.5 0)
(displayPrg
(glClear GL_COLOR_BUFFER_BIT)
(glBegin GL_LINES)
(glVertex2f *JoyX (- *... | Give a code snippet in #PicoLisp
The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the ext... | 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 ... | #Elena | Elena | import system'io;
import extensions;
extension op
{
validatePath()
= self.Available.iif("exists","not found");
}
public program()
{
console.printLine("input.txt file ",File.assign("input.txt").validatePath());
console.printLine("\input.txt file ",File.assign("\input.txt").validatePath()); ... | Give a code snippet in #Elena
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 wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #ProDOS | ProDOS | clearscurrentscreentext | Give a code snippet in #ProDOS
Task
Clear the terminal window.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #Python | Python | _suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
def nth(n):
return "%i'%s" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th')
if __name__ == '__main__':
for j in range(0,1001, 250):
print(' '.join(nth(i) for i in list(range(j, j+25)))) | Give a code snippet in #Python
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to sho... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #11l | 11l | V ascii_lowercase = ‘abcdefghij’
V digits = ‘0123456789’ // to get round ‘bug in MSVC 2017’[https://developercommunity.visualstudio.com/t/bug-with-operator-in-c/565417]
V n = 3
V board = [[0] * n] * n
F setbits(&board, count = 1)
L 0 .< count
board[random:(:n)][random:(:n)] (+)= 1
F fliprow(i)
L(j) ... | Give a code snippet in #11l
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move)... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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 |... | #Common_Lisp | Common Lisp | (defun factors (n &aux (lows '()) (highs '()))
(do ((limit (1+ (isqrt n))) (factor 1 (1+ factor)))
((= factor limit)
(when (= n (* limit limit))
(push limit highs))
(remove-duplicates (nreconc lows highs)))
(multiple-value-bind (quotient remainder) (floor n factor)
(when (zerop ... | Give a code snippet in #Common_Lisp
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Opera... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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.
| #EchoLisp | EchoLisp |
;; The file system is the browser local storage
;; It is divided into named stores (directories)
;; "user" is the default (home) store
; before : list of stores
(local-stores) → ("system" "user" "words" "reader" "info" "root")
(local-put-value "output.txt" "") → "output.txt" ; into "user"
(local-make-store "user... | Give a code snippet in #EchoLisp
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/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... | #Visual_Basic_.NET | Visual Basic .NET | Dim Value As String = "+123"
If IsNumeric(Value) Then
PRINT "It is numeric."
End If | Give a code snippet in #Visual_Basic_.NET
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:... | christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #LiveCode | LiveCode | put revXMLCreateTree(fld "FieldXML",true,true,false) into xmltree
// task 1
put revXMLEvaluateXPath(xmltree,"//item[1]") into nodepath
put revXMLText(xmltree,nodepath,true)
// task 2
put revXMLDataFromXPathQuery(xmltree,"//item/price",,comma)
// task 3
put revXMLDataFromXPathQuery(xmltree,"//name") into namenodes... | Give a code snippet in #LiveCode
Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Stor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
... | #Python | Python | command_table_text = \
"""Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPerca... | Give a code snippet in #Python
This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #REXX | REXX | /*REXX program uses the Minkowski question─mark function to convert a continued fraction*/
numeric digits 40 /*use enough dec. digits for precision.*/
say fmt( mink( 0.5 * (1+sqrt(5) ) ) ) fmt( 5/3 )
say fmt( minkI(-5/9) ) fmt( (sqrt(13) - 7) / 6)
say fmt( mink(... | Give a code snippet in #REXX
The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The d... | 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 ... | #Ring | Ring |
see "h(1) = 1" + nl
for nr = 1 to 19
see "h(" + (nr+1) + ") = " + hamming(nr) + nl
next
see "h(1691) = " + hamming(1690) + nl
see nl
func hamming limit
h = list(1690)
h[1] =1
x2 = 2 x3 = 3 x5 =5
i = 0 j = 0 k =0
for n =1 to limit
h[n] = min(x2, min(x3, x5))
if ... | Give a code snippet in #Ring
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 numbe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"log"
"math/big"
"sort"
"strings"
)
var testCases = []string{
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150... | Give a code snippet in #F.C5.8Drmul.C3.A6
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 sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #BASIC | BASIC |
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict specification
30 REM of the algorithm.
40 DEF FNF(N) = SQR(ABS(N))+5*N*N*N
50 DIM S(10)
60 PRINT "Enter 11 numbers."
70 FOR I = 0 TO 10
80 PRINT I+1; "- Enter number";
90 INPUT S(I)
100 NEXT I
110 PRINT
120 REM Reverse
130 FOR I = 0 TO 1... | Give a code snippet in #BASIC
The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Erlang | Erlang | -module(file_size).
-export([file_size/0]).
-include_lib("kernel/include/file.hrl").
file_size() ->
print_file_size("input.txt"),
print_file_size("/input.txt").
print_file_size(Filename) ->
case file:read_file_info(Filename) of
{ok, FileInfo} ->
io:format("~s ~p~n", [Filename, FileInfo#file_info... | Give a code snippet in #Erlang
Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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)
| #Wee_Basic | Wee Basic | let keycode=0
let number=1
print 1 "Press any key to generate a random number from 1 to 10.
while keycode=0
let number=number+1
let keycode=key()
rem The maximum number is the number in the "if number=" line with 1 taken away. For example, if this number was 11, the maximum number would be 10. *
if number=11
let number... | Give a code snippet in #Wee_Basic
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/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Clio | Clio |
fn factorial n:
if n <= 1: n
else:
n * (n - 1 -> factorial)
10 -> factorial -> print
| Give a code snippet in #Clio
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a nu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_sentence_type | Determine sentence type | Use these sentences:
"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it."
Task
Search for the last used punctuation in a sentence, and determine its type according to its punctuation.
Output one of these le... | #Go | Go | package main
import (
"fmt"
"strings"
)
func sentenceType(s string) string {
if len(s) == 0 {
return ""
}
var types []string
for _, c := range s {
if c == '?' {
types = append(types, "Q")
} else if c == '!' {
types = append(types, "E")
... | Give a code snippet in #Go
Use these sentences:
"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it."
Task
Search for the last used punctuation in a sentence, and determine its type according to its punctuat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Modula-2 | Modula-2 | MODULE LookAndSay;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Assign, Length;
CONST
MaxSize = 128;
Steps = 14;
VAR
buf1, buf2: ARRAY [0..MaxSize-1] OF CHAR;
step: CARDINAL;
PROCEDURE LookSay(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR count, inIdx, outIdx: CARDINAL;
... | Give a code snippet in #Modula-2
The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the seque... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked ... | #C | C | struct link *first;
// ...
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
// access data, e.g. with iter->data
} | Give a code snippet in #C
Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #PL.2FM | PL/M | 100H: /* READ A SPECIFIC LINE FROM A FILE */
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */
DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */
/* CP/M BDOS SYST... | Give a code snippet in #PL.2FM
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #PARI.2FGP | PARI/GP | callback(n)=n+n;
apply(callback, [1,2,3,4,5]) | Give a code snippet in #PARI.2FGP
Task
Take a combined set of elements and apply a function to each element.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Delphi | Delphi | program GuessTheNumber;
{$APPTYPE CONSOLE}
uses SysUtils;
var
theDigit : String ;
theAnswer : String ;
begin
Randomize ;
theDigit := IntToStr(Random(9)+1) ;
while ( theAnswer <> theDigit ) do Begin
Writeln('Please enter a digit between 1 and 10' ) ;
Readln(theAnswer);
End ;
Writeln('Congra... | Give a code snippet in #Delphi
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
... | #360_Assembly | 360 Assembly | * Selection sort 26/06/2016
SELECSRT CSECT
USING SELECSRT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
... | Give a code snippet in #360_Assembly
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/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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Rot13.bas"
110 DO
120 LINE INPUT PROMPT "Line: ":LINE$
130 PRINT ROT13$(LINE$)
140 LOOP UNTIL LINE$=""
150 DEF ROT13$(TEXT$)
160 LET RESULT$=""
170 FOR I=1 TO LEN(TEXT$)
180 LET CH$=TEXT$(I)
190 SELECT CASE CH$
200 CASE "A" TO "M","a" TO "m"
210 LET CH$=CHR$(ORD(CH$)+13)
220 C... | Give a code snippet in #IS-BASIC
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/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #Free_Pascal | Free Pascal | Public Sub Main()
Hello
Print CopyIt("Hello ", 6)
Print CopyIt("Hello ", 3, "!!")
End
'_____________________________________________________________________________________
Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String
Dim siCount As Short
Dim sNewString As String
For siCo... | Give a code snippet in #Free_Pascal
Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #C.23 | C# | public static class CherylsBirthday
{
public static void Main() {
var dates = new HashSet<(string month, int day)> {
("May", 15),
("May", 16),
("May", 19),
("June", 17),
("June", 18),
("July", 14),
("July", 16),
... | Give a code snippet in #C.23
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells A... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename... | #Rust | Rust | fn main() {
let exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"];
let filenames = [
"MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData",
"MyData_v1.0.tar.bz2",
"MyData_v1.0.bz2",
];
printl... | Give a code snippet in #Rust
File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Visual_Basic_.NET | Visual Basic .NET | Dim result As String, a As String = "pants", b As String = "glasses"
If a = b Then
result = "passed"
Else
result = "failed"
End If | Give a code snippet in #Visual_Basic_.NET
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptio... | 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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
sum[g_] := g + Total@IntegerDigits@g
ming[n_] := n - IntegerLength[n]*9
self[n_] := NoneTrue [Range[ming[n], n - 1], sum[#] == n &]
Module[{t = 1, x = 1},
Reap[
While[t <= 50,
If[self[x], Sow[x]; t++]; x++]
][[2, 1]]]
| Give a code snippet in #Mathematica.2FWolfram_Language
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Python | Python | class Node(object):
def __init__(self, data = None, prev = None, next = None):
self.prev = prev
self.next = next
self.data = data
def __str__(self):
return str(self.data)
def __repr__(self):
return repr(self.data)
def iter_forward(self):
c = self... | Give a code snippet in #Python
Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: C... | 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.
| #E | E | def base := timer.now()
for string in ["Enjoy", "Rosetta", "Code"] {
timer <- whenPast(base + entropy.nextInt(1000), fn { println(string) })
} | Give a code snippet in #E
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 langu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of th... | #PHP | PHP |
function validate($address){
$decoded = decodeBase58($address);
$d1 = hash("sha256", substr($decoded,0,21), true);
$d2 = hash("sha256", $d1, true);
if(substr_compare($decoded, $d2, 21, 4)){
throw new \Exception("bad digest");
}
return true;
}
functio... | Give a code snippet in #PHP
Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string | Strip control codes and extended characters from a string | Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters stripped
In ASCII, the control codes ... | #Gambas | Gambas | Public Sub Main()
Dim sString As String = "The\t \equick\n \fbrownfox \vcost £125.00 or €145.00 or $160.00 \bto \ncapture ©®"
Dim sStd, sExtend As String
Dim siCount As Short
For siCount = 32 To 126
sStd &= Chr(siCount)
Next
For siCount = 128 To 255
sExtend &= Chr(siCount)
Next
Print "Original string: -\t" &... | Give a code snippet in #Gambas
Task
Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
a string with control codes stripped (but extended characters not stripped)
a string with control codes and extended characters strippe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using ... | #Nim | Nim | const max = 1000
var a: array[max, int]
for n in countup(0, max - 2):
for m in countdown(n - 1, 0):
if a[m] == a[n]:
a[n + 1] = n - m
break
echo "The first ten terms of the Van Eck sequence are:"
echo a[..9]
echo "\nTerms 991 to 1000 of the sequence are:"
echo a[990..^1] | Give a code snippet in #Nim
The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Perl | Perl | print "\e[?25l"; # hide the cursor
print "Enter anything, press RETURN: "; # prompt shown
$input = <>; # but no cursor
print "\e[0H\e[0J\e[?25h"; # reset, visible again | Give a code snippet in #Perl
The task is to hide the cursor and show it again.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Gambas | Gambas | Public Sub Main()
Dim a1 As String[] = ["a", "b", "c"]
Dim a2 As String[] = ["A", "B", "C"]
Dim a3 As String[] = ["1", "2", "3"]
Dim siC As Short
For siC = 0 To a1.Max
Print a1[siC] & a2[siC] & a3[siC]
Next
End | Give a code snippet in #Gambas
Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this exa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail 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
... | #11l | 11l | F cocktailSort(&A)
L
L(indices) ((0 .< A.len-1).step(1), (A.len-2 .. 0).step(-1))
V swapped = 0B
L(i) indices
I A[i] > A[i + 1]
swap(&A[i], &A[i + 1])
swapped = 1B
I !swapped
R
V test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailSo... | Give a code snippet in #11l
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #M2000_Interpreter | M2000 Interpreter |
Module Pendulum {
back()
degree=180/pi
THETA=Pi/2
SPEED=0
G=9.81
L=0.5
Profiler
lasttimecount=0
cc=40 ' 40 ms every draw
accold=0
Every cc {
ACCEL=G*SIN(THETA*degree)/L/50
SPEED+=ACCEL/cc
THETA+=SPEED
Pe... | Give a code snippet in #M2000_Interpreter
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Euphoria | Euphoria | constant limit = 1000
sequence flags,primes
flags = repeat(1, limit)
for i = 2 to sqrt(limit) do
if flags[i] then
for k = i*i to limit by i do
flags[k] = 0
end for
end if
end for
primes = {}
for i = 2 to limit do
if flags[i] = 1 then
primes &= i
end if
end for
? pri... | Give a code snippet in #Euphoria
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Standard_ML | Standard ML | fun string_repeat (s, n) =
concat (List.tabulate (n, fn _ => s))
; | Give a code snippet in #Standard_ML
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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
... | #zkl | zkl | fcn group(scores){ // group like scores into one list --> list of lists
sink:=List();
scores.reduce('wrap(ps,sn,buf){
if(sn[0]!=ps){ sink.append(buf.copy()); buf.clear(); }
buf+sn;
sn[0];
},scores[0][0],buf:=List());
sink.append(buf);
}
fcn print(list,rank){
list.apply2('wrap(sn){ "%2s:... | Give a code snippet in #zkl
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Oz | Oz | declare
%% Helper function to read a file lazily.
%% Returns a lazy list of lines.
fun {ReadLines FN}
F = {New class $ from Open.file Open.text end init(name:FN)}
fun lazy {ReadNext}
case {F getS($)} of
false then nil
[] Line then
Line|{ReadNext}
end
en... | Give a code snippet in #Oz
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different ... | 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... | #8th | 8th | : gcd \ a b -- gcd
dup 0 n:= if drop ;; then
tuck \ b a b
n:mod \ b a-mod-b
recurse ;
: demo \ a b --
2dup "GCD of " . . " and " . . " = " . gcd . ;
100 5 demo cr
5 100 demo cr
7 23 demo cr
bye
| Give a code snippet in #8th
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 c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Pascal | Pascal | program SameNessOfChar;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;//Format
const
TestData : array[0..6] of String =
('',' ','2','333','.55','tttTTT','4444 444k');
function PosOfDifferentChar(const s: String):Native... | Give a code snippet in #Pascal
Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #NewLisp | NewLisp |
;;; Start by assigning n the integer square root of 269696
;;; minus 1 to be even
(setq n 518)
;;; Increment n by 2 till the last 6 digits of its square are 269696
(while (!= (% (* n n) 1000000) 269696)
(++ n 2))
;;; Show the result and its square
(println n "^2 = " (* n n))
| Give a code snippet in #NewLisp
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Scala | Scala | /* Ranges for variables of the primitive numeric types */
println(s"A Byte variable has a range of : ${Byte.MinValue} to ${Byte.MaxValue}")
println(s"A Short variable has a range of : ${Short.MinValue} to ${Short.MaxValue}")
println(s"An Int variable has a range of : ${Int.MinValue} to ${Int.MaxValue}")
prin... | Give a code snippet in #Scala
Task
Demonstrate how to specify the minimum size of a variable or a data type.
| 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 ... | #PicoLisp | PicoLisp | (de hamming (N)
(let (L (1) H)
(do N
(for (X L X (cadr X)) # Find smallest result
(setq H (car X)) )
(idx 'L H NIL) # Remove it
(for I (2 3 5) # Generate next results
(idx 'L (* I H) T) ) )
H ) )
(println (make (for N 20 (... | Give a code snippet in #PicoLisp
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/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #MACRO-10 | MACRO-10 |
TITLE SOCKET
COMMENT !
Socket Example ** PDP-10 Assembly Language (KJX 2022)
Assembler: MACRO-10 Operating System: TOPS-20 V7
On TOPS-20, TCP-connections are made by opening a special
file on the "TCP:" device (in this case "TCP:256"). Apart
from the funky filename, there is virtual... | Give a code snippet in #MACRO-10
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
... | #PARI.2FGP | PARI/GP | Sierpinski(n)={
my(s=2^n-1);
forstep(y=s,0,-1,
for(i=1,y,print1(" "));
for(x=0,s-y,
print1(if(bitand(x,y)," ","*"))
);
print()
)
};
Sierpinski(4) | Give a code snippet in #PARI.2FGP
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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.)
| #UNIX_Shell | UNIX Shell | function write {
_.to_s > "$1"
} | Give a code snippet in #UNIX_Shell
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/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PHP | PHP |
function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
| Give a code snippet in #PHP
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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
... | #Potion | Potion | rms = (series) :
total = 0.0
series each (x): total += x * x.
total /= series length
total sqrt
.
rms((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print | Give a code snippet in #Potion
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/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 ... | #11l | 11l | F multiply(a, b)
R a * b | Give a code snippet in #11l
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 fr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The ... | #VBScript | VBScript |
for i = 1 to 5000
if Munch(i) Then
Wscript.Echo i, "is a Munchausen number"
end if
next
'Returns True if num is a Munchausen number. This is true if the sum of
'each digit raised to that digit's power is equal to the given number.
'Example: 3435 = 3^3 + 4^4 + 3^3 + 5^5
Function Munch (num)
d... | Give a code snippet in #VBScript
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also se... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Sidef | Sidef | var rules = Hash(
l => 'lFrFl-F-rFlFr+F+lFrFl',
r => 'rFlFr+F+lFrFl-F-rFlFr',
)
var lsys = LSystem(
width: 500,
height: 500,
xoff: -50,
yoff: -50,
len: 5,
angle: 90,
color: 'dark green',
)
lsys.execute('l', 4, "peano_curve.png", rules) | Give a code snippet in #Sidef
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Wren | Wren | var squares = (1..18).map { |i| i * i }.toList
var combs = []
var results = []
// generate combinations of the numbers 0 to n-1 taken m at a time
var combGen = Fn.new { |n, m|
var s = List.filled(m, 0)
var last = m - 1
var rc // recursive closure
rc = Fn.new { |i, next|
var j = next
wh... | Give a code snippet in #Wren
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
... | #Ruby | Ruby |
MAX_ITERATIONS = 200_000
def setup
sketch_title 'Barnsley Fern'
no_loop
puts 'Be patient. This takes about 10 seconds to render.'
end
def draw
background 0
load_pixels
x0 = 0.0
y0 = 0.0
x = 0.0
y = 0.0
MAX_ITERATIONS.times do
r = rand(100)
if r < 85
x = 0.85 * x0 + 0.04 * y0
... | Give a code snippet in #Ruby
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
... | 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... | #Emacs_Lisp | Emacs Lisp | (while t
(message "SPAM")) | Give a code snippet in #Emacs_Lisp
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/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Prolog | Prolog | digit_sum(N, Base, Sum):-
digit_sum(N, Base, Sum, 0).
digit_sum(N, Base, Sum, S1):-
N < Base,
!,
Sum is S1 + N.
digit_sum(N, Base, Sum, S1):-
divmod(N, Base, M, Digit),
S2 is S1 + Digit,
digit_sum(M, Base, Sum, S2).
test_digit_sum(N, Base):-
digit_sum(N, Base, Sum),
writef('Sum o... | Give a code snippet in #Prolog
Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Ruby | Ruby | # hailstone.rb
module Hailstone
module_function
def hailstone n
seq = [n]
until n == 1
n = (n.even?) ? (n / 2) : (3 * n + 1)
seq << n
end
seq
end
end
if __FILE__ == $0
include Hailstone
# for n = 27, show sequence length and first and last 4 elements
hs27 = hailstone 27
p [... | Give a code snippet in #Ruby
The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared objec... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Maxima | Maxima | solve(a*x^2 + b*x + c = 0, x);
/* 2 2
sqrt(b - 4 a c) + b sqrt(b - 4 a c) - b
[x = - --------------------, x = --------------------]
2 a 2 a */
fpprec: 40$
solve(x^2 - 10^9*x + 1 = 0, x);
/* [x = ... | Give a code snippet in #Maxima
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #11l | 11l | L(filename) fs:list_dir(‘/foo/bar’)
I filename.ends_with(‘.mp3’)
print(filename) | Give a code snippet in #11l
Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, no... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Rust | Rust | // [dependencies]
// rug = "1.8"
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p +=... | Give a code snippet in #Rust
Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Delphi | Delphi |
program Discordian_date;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.DateUtils;
type
TDateTimeHelper = record helper for TDateTime
const
seasons: array of string = ['Chaos', 'Discord', 'Confusion', 'Bureaucracy',
'The Aftermath'];
weekday: array of string = ['Sweetmorn', 'Boomt... | Give a code snippet in #Delphi
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Wilson_primes_of_order_n | Wilson primes of order n | Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
Task
Calculate and show on thi... | #Java | Java | import java.math.BigInteger;
import java.util.*;
public class WilsonPrimes {
public static void main(String[] args) {
final int limit = 11000;
BigInteger[] f = new BigInteger[limit];
f[0] = BigInteger.ONE;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i < limit; ++... | Give a code snippet in #Java
Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #OCaml | OCaml | let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
let sum = List.fold_left ( + ) 0 lst
let () =
let rec aux acc i left right = function
| x::xs ->
let right = right - x in
let acc = if left = right then i::acc else acc in
aux acc (succ i) (left + x) right xs
| [] -> List.rev acc
in
let res = aux [] 0 0 ... | Give a code snippet in #OCaml
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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.
| #Kotlin | Kotlin | // version 1.1.2
fun recurse(i: Int) {
try {
recurse(i + 1)
}
catch(e: StackOverflowError) {
println("Limit of recursion is $i")
}
}
fun main(args: Array<String>) = recurse(0) | Give a code snippet in #Kotlin
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/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #OpenEdge.2FProgress | OpenEdge/Progress | FILE-INFO:FILE-NAME = 'c:/temp'.
MESSAGE
STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX | Give a code snippet in #OpenEdge.2FProgress
Task
Get and set the modification time of a file.
| 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.
| #Kotlin | Kotlin | // version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
operator fun Matrix.times(other: Matrix): Matrix {
val rows1 = this.size
val cols1 = this[0].size
val rows2 = other.size
val cols2 = other[0].size
require(cols1 == rows2)
val result = Matrix(rows1) { Vector(cols... | Give a code snippet in #Kotlin
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/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 ... | #PureBasic | PureBasic | Procedure spiralMatrix(size = 1)
Protected i, x = -1, y, count = size, n
Dim a(size - 1,size - 1)
For i = 1 To count
x + 1
a(x,y) = n
n + 1
Next
Repeat
count - 1
For i = 1 To count
y + 1
a(x,y) = n
n + 1
Next
For i = 1 To count
x - 1
a(x,y) = n
... | Give a code snippet in #PureBasic
Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | #ALGOL_68 | ALGOL 68 |
BEGIN
COMMENT
The task specifies
"Strictly speaking, this should not be solved by fixed-precision
numeric libraries where the precision has to be manually set to a
large value; although if this is the only recourse then it may be
used with a note explaining that the precision must be set manually
... | Give a code snippet in #ALGOL_68
Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
... | 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... | #Slate | Slate | (File newNamed: 'input.txt') renameTo: 'output.txt'.
(File newNamed: '/input.txt') renameTo: '/output.txt'.
(Directory newNamed: 'docs') renameTo: 'mydocs'.
(Directory newNamed: '/docs') renameTo: '/mydocs'. | Give a code snippet in #Slate
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 ri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Processing | Processing |
fill(0, 0, 0);
text("Goodbye, World!",0,height/2);
| Give a code snippet in #Processing
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #TPP | TPP | --color red
This is red
--color green
This is green
--color blue
This is blue
--color cyan
This is cyan
--color magenta
This is magenta
--color yellow
This is yellow | Give a code snippet in #TPP
Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to ca... | 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.
| #J | J | mp =: +/ .* NB. Matrix product
A =: ^/~>:i. 4 NB. Same A as in other examples (1 1 1 1, 2 4 8 16, 3 9 27 81,:4 16 64 256)
B =: %.A NB. Matrix inverse of A
'6.2' 8!:2 A mp B
1.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00 | Give a code snippet in #J
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/Humble_numbers | Humble numbers | Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above is:
humble = 2i × 3j × 5k... | #Perl | Perl | use strict;
use warnings;
use List::Util 'min';
#use bigint # works, but slow
use Math::GMPz; # this module gives roughly 16x speed-up
sub humble_gen {
my @s = ([1], [1], [1], [1]);
my @m = (2, 3, 5, 7);
@m = map { Math::GMPz->new($_) } @m; # comment out to NOT use Math::GMPz
return sub {
... | Give a code snippet in #Perl
Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Slate | Slate | (File newNamed: 'README') reader sessionDo: [| :input | input lines do: [| :line | inform: line]]. | Give a code snippet in #Slate
Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of... | #XBasic | XBasic |
' Trabb Pardo-Knuth algorithm
PROGRAM "tpkalgorithm"
VERSION "0.0001"
IMPORT "xma"
DECLARE FUNCTION Entry ()
INTERNAL FUNCTION SINGLE F(SINGLE n)
FUNCTION Entry ()
' Used "magic numbers" because of strict specification of the algorithm.
SINGLE s[10]
SINGLE tmp, r
UBYTE i
PRINT "Enter 11 numbers."
FO... | Give a code snippet in #XBasic
The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Java | Java | import java.util.*;
public class PenneysGame {
public static void main(String[] args) {
Random rand = new Random();
String compChoice = "", playerChoice;
if (rand.nextBoolean()) {
for (int i = 0; i < 3; i++)
compChoice += "HT".charAt(rand.nextInt(2));
... | Give a code snippet in #Java
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #J | J |
NB. z locale by default on path.
type_z_=: 3!:0
nameClass_z_=: 4!:0
signalError_z_=: 13!:8
NB. create a restricted object from an appropriate integer
create_restrict_ =: monad define
'Domain error: expected integer' assert 1 4 e.~ type y NB. or Boolean
'Domain error: not on [1,10]' assert (0 -.@:e. [: , (0&<*.<&... | Give a code snippet in #J
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.