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/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.
... | #Ring | Ring |
nr = 0
for i = 1 to 200
if kaprekar(i)
nr += 1
if i < 201 see "" + nr + " : " + i + nl ok ok
next
see "total kaprekar numbers under 200 = " + nr + nl
func kaprekar n
s = pow(n,2)
x = floor(log(s)) + 1
t = pow(10,x)
while true
t /= 10
if t<=n exit ok
... | Give a code snippet in #Ring
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Pascal | Pascal | program B10_num;
//numbers having only digits 0 and 1 in their decimal representation
//see https://oeis.org/A004290
//Limit of n= 2^19
{$IFDEF FPC} //fpc 3.0.4
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$codealign proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,gmp; //Format
const
Limit = 256*256*8;... | Give a code snippet in #Pascal
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #FreeBASIC | FreeBASIC | Dim As String charS(4)
charS(1) = "0123456789"
charS(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charS(3) = "abcdefghijklmnopqrstuvwxyz"
charS(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~"
charS(0) = charS(1) + charS(2) + charS(3) + charS(4)
Dim As Integer howBig, howMany
Do
Print !"------ Password Generator ------\n"
Input... | Give a code snippet in #FreeBASIC
Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+... | 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 ... | #M2000_Interpreter | M2000 Interpreter |
Module Game2048 {
\\ 10% 4 and 90% 2
Def GetTlleNumber()=If(Random(10)<2->4, 2)
\\ tile
Def Tile$(x)=If$(x=0->"[ ]", format$("[{0::-4}]", x))
\\ empty board
BoardTileRight=lambda (x, y)->x+y*4
BoardTileLeft=lambda (x, y)->3-x+y*4
BoardTileUp=lambda (x, y)->x*4+y
... | Give a code snippet in #M2000_Interpreter
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 dire... | 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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | L[0,L0_:1,___]:=L0
L[1,L0_:1,L1_:1,___]:=L1
L[n_,L0_:1,L1_:1,add_:1]:=L[n-1,L0,L1,add]+L[n-2,L0,L1,add]+add
L/@(Range[25]-1)
L[#,0,1,0]&/@(Range[25]-1) | Give a code snippet in #Mathematica.2FWolfram_Language
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #Perl | Perl | package Singleton;
use strict;
use warnings;
my $Instance;
sub new {
my $class = shift;
$Instance ||= bless {}, $class; # initialised once only
}
sub name {
my $self = shift;
$self->{name};
}
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
}
package main;
my $s1 = Singl... | Give a code snippet in #Perl
A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble 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
... | #ALGOL_68 | ALGOL 68 | MODE DATA = INT;
PROC swap = (REF[]DATA slice)VOID:
(
DATA tmp = slice[1];
slice[1] := slice[2];
slice[2] := tmp
);
PROC sort = (REF[]DATA array)VOID:
(
BOOL sorted;
INT shrinkage := 0;
FOR size FROM UPB array - 1 BY -1 WHILE
sorted := TRUE;
shrinkage +:= 1;
FOR i FROM LWB array TO size DO
... | Give a code snippet in #ALGOL_68
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Clojure | Clojure | (def plus-a-hundred (partial + 100))
(assert (=
(plus-a-hundred 1)
101))
| Give a code snippet in #Clojure
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative exa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #Modula-3 | Modula-3 | MODULE ByteLength EXPORTS Main;
IMPORT IO, Fmt, Text;
VAR s: TEXT := "Foo bar baz";
BEGIN
IO.Put("Byte length of s: " & Fmt.Int((Text.Length(s) * BYTESIZE(s))) & "\n");
END ByteLength. | Give a code snippet in #Modula-3
Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FactorInteger[2016] => {{2, 5}, {3, 2}, {7, 1}} | Give a code snippet in #Mathematica.2FWolfram_Language
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or colle... | 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
... | #Elixir | Elixir | defmodule Sort do
def stooge_sort(list) do
stooge_sort(List.to_tuple(list), 0, length(list)-1) |> Tuple.to_list
end
defp stooge_sort(tuple, i, j) do
if (vj = elem(tuple, j)) < (vi = elem(tuple, i)) do
tuple = put_elem(tuple,i,vj) |> put_elem(j,vi)
end
if j - i > 1 do
t = div(j - i + ... | Give a code snippet in #Elixir
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/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 ... | #TXR | TXR | @(define multiply (a b out))
@(bind out @(* a b))
@(end)
@(multiply 3 4 result) | Give a code snippet in #TXR
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/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #min | min | (1 2 3) (4 "apple" 6) concat print | Give a code snippet in #min
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Undersc... | #Julia | Julia |
using FreqTables
txt = read("les-mis.txt", String)
words = split(replace(txt, r"\P{L}"i => " "))
table = sort(freqtable(words); rev=true)
println(table[1:10]) | Give a code snippet in #Julia
Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define wh... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Dyalect | Dyalect | func isPrime(number) {
if number <= 1 {
return false
}
else if number % 2 == 0 {
return number == 2
}
var i = 3
while (i * i) < number {
if number % i == 0 {
return false
}
i += 2
}
return true
}
var i = 42
var n = 0
while n <... | Give a code snippet in #Dyalect
Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop whic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th... | #Rust | Rust | use std::cmp::Ordering;
use std::io::BufRead;
/// Compares the length of two strings by iterating over their characters
/// together until either string has run out.
fn compare(a: &str, b: &str) -> Ordering {
let mut a = a.chars();
let mut b = b.chars();
loop {
match (a.next(), b.next()) {
... | Give a code snippet in #Rust
Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challeng... | 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
... | #Kotlin | Kotlin | // version 1.1.3
import java.math.BigInteger
class Fraction(val num: BigInteger, val denom: BigInteger) {
operator fun times(n: BigInteger) = Fraction (n * num, denom)
fun isIntegral() = num % denom == BigInteger.ZERO
}
fun String.toFraction(): Fraction {
val split = this.split('/')
return Fract... | Give a code snippet in #Kotlin
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 initi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
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 |... | #AutoHotkey | AutoHotkey | ; Create a variable with 4 bytes size and show it's machine address.
VarSetCapacity(var, 4, 0)
pAddress := &var
MsgBox Machine address: %pAddress%
; pAddress contains the memory address.
; Write a number and read it back.
NumPut(123456, pAddress+0, 0, "UInt")
MsgBox % "Contents of *pAdd... | Give a code snippet in #AutoHotkey
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 Operat... | 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... | #Applesoft_BASIC | Applesoft BASIC | 0
19
-3
29.59
-239.4
1E10
1.9E+09
-6.66E-32
| Give a code snippet in #Applesoft_BASIC
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 expressi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #Ruby | Ruby | Point = Struct.new(:x,:y)
pt = Point.new(6,7)
puts pt.x #=> 6
pt.y = 3
puts pt #=> #<struct Point x=6, y=3>
# The other way of accessing
pt = Point[2,3]
puts pt[:x] #=> 2
pt['y'] = 5
puts pt #=> #<struct Point x=2, y=5>
pt.each_pair{|member, value| puts "#{member} : #{value}"}
... | Give a code snippet in #Ruby
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc ::tcl::mathfunc::ipart x {expr {int($x)}}
proc ::tcl::mathfunc::fpart x {expr {$x - int($x)}}
proc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}}
proc drawAntialiasedLine {image colour p1 p2} {
lassign $p1 x1 y1
lassign $p2 x2 y2
set steep [expr {abs... | Give a code snippet in #Tcl
Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or co... | #Wren | Wren | import "/big" for BigRat
import "/complex" for Complex
import "/rat" for Rat
import "/fmt" for Fmt
var tests1 = [25.000000, 24.999999, 25.000100]
var tests2 = ["-2.1e120"]
var tests3 = [-5e-2, 0/0, 1/0]
var tests4 = [Complex.fromString("5.0+0.0i"), Complex.fromString("5-5i")]
var tests5 = [Rat.new(24, 8), Rat.new(-5,... | Give a code snippet in #Wren
Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
... | #11l | 11l | V values = [Float(-2), -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
F normd(x) {R fmod(x, 360)}
F normg(x) {R fmod(x, 400)}
F normm(x) {R fmod(x, 6400)}
F normr(x) {R fmod(x, (2 * math:pi))}
F d2g(x) {R normd(x) * 10 / 9}
F d2m(x) {R normd(x) * 160 / 9}
F d2r(x) {R normd(x) * math:pi / 180}
F ... | Give a code snippet in #11l
This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360... | 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... | #Maxima | Maxima | /* Time and date in a formatted string */
timedate();
"2012-08-27 20:26:23+10:00"
/* Time in seconds elapsed since 1900/1/1 0:0:0 */
absolute_real_time();
/* Time in seconds since Maxima was started */
elapsed_real_time();
elapsed_run_time(); | Give a code snippet in #Maxima
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Five_weekends | Five weekends | The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at leas... | #k | k |
cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar
is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays
m:__dj[cal_j]%100 / label the months
mi:&15=+/'is_we[=m] / group by month and sum the weekend d... | Give a code snippet in #k
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there sh... | 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... | #Yorick | Yorick | func looksay(input) {
// Special case: one digit
if(strlen(input) == 1)
return "1" + input;
// Convert string into an array of digits
digits = strchar(input)(:-1);
// Find indices where each run starts
w = where(digits(dif));
start = numberof(w) ? grow(1, w+1) : [1];
// Find leng... | Give a code snippet in #Yorick
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 sequenc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Perl | Perl | use strict;
use warnings;
use List::Util qw(min);
sub levenshtein_distance_alignment {
my @s = ('^', split //, shift);
my @t = ('^', split //, shift);
my @A;
@{$A[$_][0]}{qw(d s t)} = ($_, join('', @s[1 .. $_]), ('~' x $_)) for 0 .. $#s;
@{$A[0][$_]}{qw(d s t)} = ($_, ('-' x $_), join '', @t[1... | Give a code snippet in #Perl
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #UNIX_Shell | UNIX Shell | function count_change {
local -i amount=$1 coin j
local ways=(1)
shift
for coin; do
for (( j=coin; j <= amount; j++ )); do
let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
done
done
echo "${ways[amount]}"
}
count_change 100 25 10 5 1
count_change 100000 100 50 25 10 5 1 | Give a code snippet in #UNIX_Shell
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels ... | 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... | #Erlang | Erlang |
no_argument()
one_argument( Arg )
optional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] )
variable_arguments( [Arg1, Arg2 | Rest] )
names_arguments([{name1, Arg1}, {another_name, Another}] )
% Statement context?
% First class context?
Result = obtain_result( Arg1 )
% No way to distinguish builtin/user funct... | Give a code snippet in #Erlang
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 v... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
var array integer: board is 8 times 0;
var integer: solutionNum is 0;
const func boolean: safe (in integer: y) is func
result
var boolean: safe is TRUE;
local
var integer: i is 1;
begin
while i < y and safe do
safe := board[y - i] <> board[y] and
board... | Give a code snippet in #Seed7
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #Objective-C | Objective-C | -(long)fibonacci:(int)position
{
long result = 0;
if (position < 2) {
result = position;
} else {
result = [self fibonacci:(position -1)] + [self fibonacci:(position -2)];
}
return result;
} | Give a code snippet in #Objective-C
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Long_year | Long year | Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| #AWK | AWK |
# syntax: GAWK -f LONG_YEAR.AWK
BEGIN {
for (cc=19; cc<=21; cc++) {
printf("%2d00-%2d99: ",cc,cc)
for (yy=0; yy<=99; yy++) {
ccyy = sprintf("%02d%02d",cc,yy)
if (is_long_year(ccyy)) {
printf("%4d ",ccyy)
}
}
printf("\n")
}
#
printf("\n%4d-%4d: ",by... | Give a code snippet in #AWK
Most years have 52 weeks, some have 53, according to ISO8601.
Task
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never gener... | #E | E | while (true) {
def a := entropy.nextInt(20)
print(a)
if (a == 10) {
println()
break
}
println(" ", entropy.nextInt(20))
} | Give a code snippet in #E
Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Pike | Pike | string foo = "The quick brown fox jumps over the lazy dog";
write("0x%x\n", Gz.crc32(foo)); | Give a code snippet in #Pike
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #J | J | thru=: <. + i.@(+*)@-~
thru&.(a.&i.)/'az'
abcdefghijklmnopqrstuvwxyz | Give a code snippet in #J
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reli... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_decimal_number_to_rational | Convert decimal number to rational | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not always possible to do this... | #zkl | zkl | fcn real2Rational(r,bound){
if (r == 0.0) return(0,1);
if (r < 0.0){
result := real2Rational(-r, bound);
return(-result[0],result[1]);
} else {
best,bestError := 1,(1.0).MAX;
foreach i in ([1 .. bound + 1]){
error := (r*i - (r*i).round()).abs();
if (error < bestError) best,be... | Give a code snippet in #zkl
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #F.23 | F# | let isSemiprime (n: int) =
let rec loop currentN candidateFactor numberOfFactors =
if numberOfFactors > 2 then numberOfFactors
elif currentN = candidateFactor then numberOfFactors+1
elif currentN % candidateFactor = 0 then loop (currentN/candidateFactor) candidateFactor (numberOfFactors+1)
... | Give a code snippet in #F.23
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Raku | Raku | given $*DISTRO {
when .is-win {
my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
run($cmd);
}
default { # most POSIX environments
use Log::Syslog::Native;
my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);
$logger.inf... | Give a code snippet in #Raku
Task
Write script status to the Windows Event Log
| 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... | #Ruby | Ruby | include Math
Radius = 6371 # rough radius of the Earth, in kilometers
def spherical_distance(start_coords, end_coords)
lat1, long1 = deg2rad *start_coords
lat2, long2 = deg2rad *end_coords
2 * Radius * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2))
end
def deg2rad(lat... | Give a code snippet in #Ruby
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/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Groovy | Groovy | def rleEncode(text) {
def encoded = new StringBuilder()
(text =~ /(([A-Z])\2*)/).each { matcher ->
encoded.append(matcher[1].size()).append(matcher[2])
}
encoded.toString()
}
def rleDecode(text) {
def decoded = new StringBuilder()
(text =~ /([0-9]+)([A-Z])/).each { matcher ->
d... | Give a code snippet in #Groovy
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a fun... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Scilab | Scilab | trunk = 1; //trunk length
ratio = 0.8; //size ratio between two consecutive branches
depth = 9; //final number of branch levels
orign = 0; //origin of the tree (should be complex)
angle = 45*%pi/180; //angle between two branches [rad]
trunk_angle... | Give a code snippet in #Scilab
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #TI-89_BASIC | TI-89 BASIC | ∑(1/x^2,x,1,1000) | Give a code snippet in #TI-89_BASIC
Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #JavaScript | JavaScript | const dutchNationalFlag = () => {
/**
* Return the name of the given number in this way:
* 0 = Red
* 1 = White
* 2 = Blue
* @param {!number} e
*/
const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';
/**
* Given an array of numbers return true if each number is bigger than
* or t... | Give a code snippet in #JavaScript
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #IS-BASIC | IS-BASIC | 100 PROGRAM "ISBN13.bas"
110 DO
120 PRINT :INPUT PROMPT "ISBN-13 code: ":IS$
130 IF IS$="" THEN EXIT DO
140 IF ISBN(IS$) THEN
150 PRINT "Ok."
160 ELSE
170 PRINT "CRC error."
180 END IF
190 LOOP
200 DEF TRIM$(S$)
210 LET T$=""
220 FOR I=1 TO LEN(S$)
230 IF S$(I)>CHR$(47) AND S$(I)<CHR$(58) THEN... | Give a code snippet in #IS-BASIC
Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Racket | Racket |
#lang racket/gui
;; One of 'left or 'right
(define direction 'left)
;; Set up the GUI
(define animation-frame%
(class frame%
(super-new [label "Animation"])
;; reverse direction on a click
(define/override (on-subwindow-event win evt)
(when (send evt button-down?)
(... | Give a code snippet in #Racket
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Neko | Neko | /** ... **/ | Give a code snippet in #Neko
See also
Related task: Comments
Related task: Here_document
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
DIM sum AS INTEGER
FOR DIM i = 1 TO n - 1
IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN
INCR(sum, i)
END IF
NEXT
RETURN sum
END FUNCTION
PRINT sumOfThreeFiveMultiples(1000)
PAUSE
| Give a code snippet in #FBSL
Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Grayscale_image | Grayscale image | Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color u... | #Euler_Math_Toolbox | Euler Math Toolbox |
>A=loadrgb("mona.jpg");
>insrgb(A);
>function grayscale (A) ...
${r,g,b}=getrgb(A);
$c=0.2126*r+0.7152*g+0.0722*b;
$return rgb(c,c,c);
$endfunction
>insrgb(grayscale(A));
>insrgb(A|grayscale(A));
| Give a code snippet in #Euler_Math_Toolbox
Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backwar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Perl | Perl | use ntheory qw/chinese/;
say chinese([2,3], [3,5], [2,7]); | Give a code snippet in #Perl
Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displayst... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(... | #Python | Python | import mysql.connector
import hashlib
import sys
import random
DB_HOST = "localhost"
DB_USER = "devel"
DB_PASS = "devel"
DB_NAME = "test"
def connect_db():
''' Try to connect DB and return DB instance, if not, return False '''
try:
return mysql.connector.connect(host=DB_HOST, use... | Give a code snippet in #Python
This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #Raku | Raku | use Math::Primesieve;
my %conspiracy;
my $upto = 1_000_000;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.n-primes($upto+1);
@primes[^($upto+1)].reduce: -> $a, $b {
my $d = $b % 10;
%conspiracy{"$a → $d count:"}++;
$d;
}
say "$_ \tfrequency: {($_.value/$upto*100).round(.01)} %" for %conspiracy... | Give a code snippet in #Raku
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferenc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of p... | #D | D | import std.stdio, std.algorithm, std.range, std.functional;
auto aMean(T)(T data) pure nothrow @nogc {
return data.sum / data.length;
}
auto gMean(T)(T data) pure /*@nogc*/ {
return data.reduce!q{a * b} ^^ (1.0 / data.length);
}
auto hMean(T)(T data) pure /*@nogc*/ {
return data.length / data.reduce!q... | Give a code snippet in #D
Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/Integer | Literals/Integer | Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be interpreted by the compiler or... | #Neko | Neko | /**
Integer literals, in Neko
Base 10 and Base 16, no leading zero octal in Neko
*/
var num = 2730
if (num == 02730) $print("base 10, even with leading zero\n")
if (num == 0xAAA) $print("base 16, with leading 0x or 0X\n") | Give a code snippet in #Neko
Some programming languages have ways of expressing integer literals in bases other than the normal base ten.
Task
Show how integer literals can be expressed in as many bases as your language allows.
Note: this should not involve the calling of any functions/methods, but should be ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper... | #Pascal | Pascal | $ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private
| Give a code snippet in #Pascal
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. 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)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Check [ Abstract ]
{
ClassMethod CUSIP(x As %String) As %Boolean
{
SET x=$TRANSLATE(x," ")
// https://leiq.bus.umich.edu/res_codes_cusip.htm
IF x'?8UNP1N QUIT 0
SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1), t=0
FOR i=1:1:$LENGTH(x) {
SET n=$EXTRACT(x,i)
IF n'=+n SET n=$CASE(n,"*":36,"@":37,"#":38,:$... | Give a code snippet in #Cach.C3.A9_ObjectScript
This page uses content from Wikipedia. The original article was at CUSIP. 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)
A CUSIP is a nine-char... | 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.
| #BQN | BQN | {𝕊1+•Show 𝕩}0
0
1
.
.
.
4094
Error: Stack overflow
at {𝕊1+•Show 𝕩}0
| Give a code snippet in #BQN
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/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Julia | Julia |
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end
| Give a code snippet in #Julia
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative examp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #Julia | Julia | import Base: convert, promote_rule, show, conj, abs, +, -, *
immutable Quaternion{T<:Real} <: Number
q0::T
q1::T
q2::T
q3::T
end
Quaternion(q0::Real,q1::Real,q2::Real,q3::Real) = Quaternion(promote(q0,q1,q2,q3)...)
convert{T}(::Type{Quaternion{T}}, x::Real) =
Quaternion(convert(T,x), zero(T), ... | Give a code snippet in #Julia
Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Groovy | Groovy | def list = [25, 30, 1, 450, 3, 78]
def random = new Random();
(0..3).each {
def i = random.nextInt(list.size())
println "list[${i}] == ${list[i]}"
} | Give a code snippet in #Groovy
Demonstrate how to pick a random element from a list.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #GEORGE | GEORGE | read (n) print ;
0
1, n rep (i)
read print dup mult +
]
print | Give a code snippet in #GEORGE
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #Haskell | Haskell | price_fraction n
| n < 0 || n > 1 = error "Values must be between 0 and 1."
| n < 0.06 = 0.10
| n < 0.11 = 0.18
| n < 0.16 = 0.26
| n < 0.21 = 0.32
| n < 0.26 = 0.38
| n < 0.31 = 0.44
| n < 0.36 = 0.50
| n < 0.41 = 0.54
| n < 0.46 = 0.58
| n < 0.51 = 0.62
| n < 0.56 = 0.66
| n < 0.61 = 0.70
... | Give a code snippet in #Haskell
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, whic... | #Haskell | Haskell | scs :: Eq a => [a] -> [a] -> [a]
scs [] ys = ys
scs xs [] = xs
scs xss@(x:xs) yss@(y:ys)
| x == y = x : scs xs ys
| otherwise = ws
where
us = scs xs yss
vs = scs xss ys
ws | length us < length vs = x : us
| otherwise = y : vs
main = putStrLn $ scs "abcbdab" "bdcaba" | Give a code snippet in #Haskell
The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl... | #Ursala | Ursala | #import std
#import nat
num_to_string "b" = ||'0'! (-: num digits--letters)*+ @NiX ~&r->l ^|rrPlCrlPX/~& division\"b"
string_to_num "b" = @x =>0 sum^|/(-:@rlXS num digits--letters) product/"b" | Give a code snippet in #Ursala
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Dyalect | Dyalect | #t // <boolean> true
#f // <boolean> false | Give a code snippet in #Dyalect
Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Phix | Phix | without js -- (no input redirection in a browser!)
printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
| Give a code snippet in #Phix
Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Logo | Logo | to move :n :from :to :via
if :n = 0 [stop]
move :n-1 :from :via :to
(print [Move disk from] :from [to] :to)
move :n-1 :via :to :from
end
move 4 "left "middle "right | Give a code snippet in #Logo
Task
Solve the Towers of Hanoi problem with recursion.
| 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... | #Tcl | Tcl | # ASCII
puts [scan "a" %c] ;# ==> 97
puts [format %c 97] ;# ==> a
# Unicode is the same
puts [scan "π" %c] ;# ==> 960
puts [format %c 960] ;# ==> π | Give a code snippet in #Tcl
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).
Conver... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Rust | Rust | use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
const HEIGHT: usize = 16;
#[derive(Clone, Copy, PartialEq)]
struct Cell {
col: usize,
row: usize,
}
impl Cell {
fn from(col: usize, row: usize) -> Cell {
Cell {col, row}
}
}
struct Maze {
cells: [[bool; HEIGHT]; W... | Give a code snippet in #Rust
Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #PicoLisp | PicoLisp | (de deleteLines (File Start Cnt)
(let L (in File (make (until (eof) (link (line)))))
(if (> (+ (dec 'Start) Cnt) (length L))
(quit "Not enough lines")
(out File
(mapc prinl (cut Start 'L))
(mapc prinl (nth L (inc Cnt))) ) ) ) ) | Give a code snippet in #PicoLisp
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Bounded | Knapsack problem/Bounded | A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th... | #Haskell | Haskell | inv = [("map",9,150,1), ("compass",13,35,1), ("water",153,200,2), ("sandwich",50,60,2),
("glucose",15,60,2), ("tin",68,45,3), ("banana",27,60,3), ("apple",39,40,3),
("cheese",23,30,1), ("beer",52,10,3), ("cream",11,70,1), ("camera",32,30,1),
-- what to do if we end up taking one trouser?
("tshirt",24,15,2), ("trou... | Give a code snippet in #Haskell
A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature. So he needs some items during the trip. Food, clothing, etc. He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg w... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Haskell | Haskell | main = return () | Give a code snippet in #Haskell
Task
Create the simplest possible program that is still considered "correct."
| 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 ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const array string: prog is [](
"$ include \"seed7_05.s7i\";",
"const array string: prog is [](",
"const proc: main is func",
" local var integer: number is 0;",
" begin",
" for number range 1 to 2 do writeln(prog[number]); end for;",
" for number range 1 to 11 do",
" writeln(lite... | Give a code snippet in #Seed7
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/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Gambas | Gambas | Public Sub Main()
Dim sDict As String = File.Load(User.Home &/ "unixdict.txt") 'Store the 'Dictionary'
Dim sOrdered As New String[] 'To store ordered words
Dim sHold As New String[] 'General store
Dim sTemp As String ... | Give a code snippet in #Gambas
An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file local... | 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... | #Vlang | Vlang | fn main() { panic(0) } | Give a code snippet in #Vlang
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #MATLAB | MATLAB | function testEval
fprintf('Expressions:\n')
x = eval('5+10^2')
eval('y = (x-100).*[1 2 3]')
eval('z = strcat(''my'', '' string'')')
try
w eval(' = 45')
catch
fprintf('Runtime error: interpretation of w is a function\n\n')
end
% eval('v') = 5
% Invalid at compile-time ... | Give a code snippet in #MATLAB
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mean_time_of_day | Averages/Mean time of day | Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute ... | #Run_BASIC | Run BASIC | global pi
pi = acs(-1)
Print "Average of:"
for i = 1 to 4
read t$
print t$
a = time2angle(t$)
ss = ss+sin(a)
sc = sc+cos(a)
next
a = atan2(ss,sc)
if a < 0 then a = a + 2 * pi
print "is ";angle2time$(a)
end
data "23:00:17", "23:40:20", "00:12:45", "00:17:19"
function nn$(n)
nn$ = right$("0"... | Give a code snippet in #Run_BASIC
Task[edit]
A particular activity of bats occurs at these times of the day:
23:00:17, 23:40:20, 00:12:45, 00:17:19
Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the id... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #MiniScript | MiniScript | lines = ["==========================================",
"| ---------- Ice and Fire ------------ |",
"| |",
"| fire, in end will world the say Some |",
"| ice. in say Some |",
"| desire of tasted I've what From |",
"| fire. f... | Give a code snippet in #MiniScript
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by... | 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... | #zkl | zkl | // http://stackoverflow.com/revisions/10733621/4
fcn postponed_sieve(){ # postponed sieve, by Will Ness
vm.yield(2); vm.yield(3); # original code David Eppstein,
vm.yield(5); vm.yield(7); # ActiveState Recipe 2002
D:=Dictionary();
ps:=Utils.Generator(postpone... | Give a code snippet in #zkl
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 progra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Death_Star | Death Star |
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
| #POV-Ray | POV-Ray | camera { perspective location <0.0 , .8 ,-3.0> look_at 0
aperture .1 blur_samples 20 variance 1/100000 focal_point 0}
light_source{< 3,3,-3> color rgb 1}
sky_sphere { pigment{ color rgb <0,.2,.5>}}
plane {y,-5 pigment {color rgb .54} normal {hexagon} }
difference {
sphere { 0,1 }
sphere { <-1,1,-1>,... | Give a code snippet in #POV-Ray
Task
Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.
(This will basically produce a shape like a "death star".)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
write language ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
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 |... | #Shale | Shale | #!/usr/local/bin/shale
aVariable var // Create aVariable
aVariable 0 = // Regular assignment.
aVariable "aVariable = %d\n" printf // Print aVariable
aPointer var // Create aPointer
aPointer aVariable &= // Pointer a... | Give a code snippet in #Shale
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/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could ... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SECTION test
LOOP n=1,999999
rest=MOD (n,1000)
IF (rest==0) Print n
ENDLOOP
ENDSECTION
time_beg=TIME ()
DO test
time_end=TIME ()
interval=TIME_INTERVAL (seconds,time_beg,time_end)
PRINT "'test' start at ",time_beg
PRINT "'test' ends at ",time_end
PRINT "'test' takes ",interval," seconds"
| Give a code snippet in #TUSCRIPT
Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
betw... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Delphi | Delphi |
program Write_entire_file;
{$APPTYPE CONSOLE}
uses
System.IoUtils;
begin
TFile.WriteAllText('filename.txt', 'This file contains a string.');
end. | Give a code snippet in #Delphi
Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #PARI.2FGP | PARI/GP | show(n)={
my(t=1);
while(n>1,
print1(n",");
n=if(n%2,
3*n+1
,
n/2
);
t++
);
print(1);
t
};
len(n)={
my(t=1);
while(n>1,
if(n%2,
t+=2;
n+=(n>>1)+1
,
t++;
n>>=1
)
);
t
};
show(27)
r=0;for(n=1,1e5,t=len(n);if(t>r,r=t;ra=n));print(ra"... | Give a code snippet in #PARI.2FGP
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) ... | 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... | #TransFORTH | TransFORTH | : FACTORIAL
1 SWAP
1 + 1 DO
I * LOOP ; | Give a code snippet in #TransFORTH
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 o... | 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)
... | #Haskell | Haskell | import Data.List (scanl')
import Diagrams.Backend.Rasterific.CmdLine
import Diagrams.Prelude
import System.Random
type Pt = (Double, Double)
-- Four affine transformations used to produce a Barnsley fern.
f1, f2, f3, f4 :: Pt -> Pt
f1 (x, y) = ( 0, 0.16 * y)
f2 (x, y) = ( 0.85 * x... | Give a code snippet in #Haskell
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/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #PL.2FI | PL/I |
/* The entire command line except the command word itself is passed */
/* to the parameter variable in PL/I. */
program: procedure (command_line) options (main);
declare command_line character (100) varying;
...
end program;
| Give a code snippet in #PL.2FI
Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate ... | #Swift | Swift | extension String {
func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) {
var matches = [Substring]()
var matched = [(String, (String.Index, String.Index))]()
var i = startIndex
var lastMatch = startIndex
main: while i != endIndex {
for ... | Give a code snippet in #Swift
It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task i... | 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 ... | #Bracmat | Bracmat | ( "string of ☺☻♥♦⌂, may include control
characters and other ilk.\L\D§►↔◄
Rødgrød med fløde"
: ?string1
: ?string2
& :?newString
& whl
' ( @(!string1:?clean (%@:<" ") ?string1)
& !newString !clean:?newString
)
& !newString !string1:?newString
& out$(str$("Control characters stripped:
" str$!newString))... | Give a code snippet in #Bracmat
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 stripp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Maxima | Maxima | USER>write 3e145
30000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
USER>write 3e146
<MAXNUMBER>
| Give a code snippet in #Maxima
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
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 |... | #Raku | Raku | my $foo = 42; # place a reference to 42 in $foo's item container
$foo++; # deref $foo name, then increment the container's contents to 43
$foo.say; # deref $foo name, then $foo's container, and call a method on 43.
$foo := 42; # bind a direct ref to 42
$foo++; # ERROR, cannot modify i... | Give a code snippet in #Raku
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #C.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include<cstdio>
using namespace std;
void Pascal_Triangle(int size) {
int a[100][100];
int i, j;
//first row and first coloumn has the same value=1
for (i = 1; i <= size; i++) {
a[i][1] = a[1][i] = 1;
}
//Generate the full Triangle
for (i = 2; i <= size; i++) {
... | Give a code snippet in #C.2B.2B
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is eith... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Shiny | Shiny | str: 'I am a string' | Give a code snippet in #Shiny
Task
match a string against a regular expression
substitute part of a string using a regular expression
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Topological_sort | Topological 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
... | #Ada | Ada | with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
-- a Node_Index is a number from 1, 2, 3, ... and the representative of a node
type Graph_Type is tagged private;
... | Give a code snippet in #Ada
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/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... | #Lua | Lua | -- Return a table of the proper divisors of n
function propDivs (n)
if n < 2 then return {} end
local divs, sqr = {1}, math.sqrt(n)
for d = 2, sqr do
if n % d == 0 then
table.insert(divs, d)
if d ~= sqr then table.insert(divs, n/d) end
end
end
table.sort(divs)... | Give a code snippet in #Lua
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 divisor... | 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.
| #Prolog | Prolog | ?- assert((fun(X, Y) :- Y is 2 * X)).
true.
?- maplist(fun, [1,2,3,4,5], L).
L = [2,4,6,8,10].
| Give a code snippet in #Prolog
Task
Take a combined set of elements and apply a function to each element.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #Processing | Processing | boolean play = true;
int cellSize = 10;
int cols, rows;
int lastCell = 0;
int sample = 10;
// Game of life board
int[][] grid;
void setup() {
size(800, 500);
noStroke();
// Calculate cols, rows and init array
cols = width/cellSize;
rows = height/cellSize;
grid = new int[cols][rows];
init(-1); // randomi... | Give a code snippet in #Processing
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Set | Set |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #Ol | Ol |
; test set
(define set1 '(1 2 3 4 5 6 7 8 9))
(define set2 '(3 4 5 11 12 13 14))
(define set3 '(4 5 6 7))
(define set4 '(1 2 3 4 5 6 7 8 9))
; union
(print (union set1 set2))
; ==> (1 2 6 7 8 9 3 4 5 11 12 13 14)
; intersection
(print (intersect set1 set2))
; ==> (3 4 5)
; difference
(print (diff set1 set2))
; ... | Give a code snippet in #Ol
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set crea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #Seed7 | Seed7 | $include "seed7_05.s7i";
const func string: middle3 (in integer: number) is func
result
var string: middle3 is "";
begin
middle3 := str(abs(number));
if not odd(length(middle3)) or length(middle3) < 3 then
middle3 := "error";
else
middle3 := middle3[succ((length(middle3) - 3) div 2) le... | Give a code snippet in #Seed7
Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be te... | 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... | #Nim | Nim | import strutils
for i in 0 ..< int.high:
echo toOct(i, 16) | Give a code snippet in #Nim
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/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.
| #Smalltalk | Smalltalk | |f|
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] . | Give a code snippet in #Smalltalk
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.