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/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #Liberty_BASIC | Liberty BASIC | print "AND"
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") AND b( "; j; ")"
res =a( i) 'call always
if res <>0 then 'short circuit if 0
res = b( j)
end if
print "=>",res
next
next
print "---------------------------------"
print "OR"
for i = 0 to 1
f... | Give a code snippet in #Liberty_BASIC
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes consider... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function... | #PARI.2FGP | PARI/GP | f(a[..])=for(i=1,#a,print(a[i])) | Give a code snippet in #PARI.2FGP
Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #Go | Go | package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func main() {
const (
m, n = 15, 15
t = 1e4
minp, maxp, Δp = 0, 1, 0.1
)
rand.Seed(2) // Fixed seed for repeatable example grid
g := NewGrid(.5, m, n)
g.Percolate()
fmt.Println(g)
rand.Seed(time.Now().UnixNano()) //... | Give a code snippet in #Go
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #K | K |
/ List the dates of last Fridays of each month of
/ a given year
/ lastfridt.k
isleap: {(+/~x!' 4 100 400)!2}
wd: {(_jd x)!7}
dom: (31;28;31;30;31;30;31;31;30;31;30;31)
init: {:[isleap x;dom[1]::29;dom[1]::28]}
wdme: {[m;y]; init y; dt:(10000*y)+(100*m)+dom[m-1];jd::(_jd dt);mewd::(wd dt)}
lfd: {[m;y]; wdme[m;y];:[... | Give a code snippet in #K
Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of S... | #Haskell | Haskell | import Data.Ratio
import System.Environment
main = getArgs >>= printM . defaultArg
where
defaultArg as =
if null as
then 60
else read (head as)
printM m =
mapM_ (putStrLn . printP) .
takeWhile ((<= m) . fst) . filter (\(_, b) -> b /= 0 % 1) . zip [0 ..] $
bernoullis
printP (i, r)... | Give a code snippet in #Haskell
Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #Delphi | Delphi | defmodule Benfords_law do
def distribution(n), do: :math.log10( 1 + (1 / n) )
def task(total \\ 1000) do
IO.puts "Digit Actual Benfords expected"
fib(total)
|> Enum.group_by(fn i -> hd(to_char_list(i)) end)
|> Enum.map(fn {key,list} -> {key - ?0, length(list)} end)
|> Enum.sort
|> Enum.eac... | Give a code snippet in #Delphi
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #PicoLisp | PicoLisp | (de stepUp ()
(until (step1) # ('step1', because 'step' is a system function)
(stepUp) ) ) | Give a code snippet in #PicoLisp
From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #Bracmat | Bracmat | ( luhn
= sum odd even
. 0:?sum
& rev$!arg:?arg
& whl
' ( @( !arg
: %?odd
( %?even ?arg
| :?arg&0:?even
)
)
& !odd+mod$(2*!even.10)+div$(!even.5)+!sum:?sum
)
& mod$(!sum.10):0
)
& ... | Give a code snippet in #Bracmat
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order ... | 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.
| #Arturo | Arturo | sumMul35: function [n][
sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]
print sumMul35 1000 | Give a code snippet in #Arturo
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/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod=... | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <vector>
using std::abs;
using std::cout;
using std::pow;
using std::vector;
int main()
{
int prod = 1,
sum = 0,
x = 5,
y = -5,
z = -2,
one = 1,
three = 3,
seven = 7;
auto summingValues... | Give a code snippet in #C.2B.2B
Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARE... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #BCPL | BCPL | get "libhdr"
let corput(n, base, num, denom) be
$( let p = 0 and q = 1
until n=0
$( p := p * base + n rem base
q := q * base
n := n / base
$)
!num := p
!denom := q
until p=0
$( n := p
p := q rem p
q := n
$)
!num := !num / q
!denom := !de... | Give a code snippet in #BCPL
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\d... | 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... | #BASIC | BASIC | function StringRepeat$ (s$, n)
cad$ = ""
for i = 1 to n
cad$ += s$
next i
return cad$
end function
print StringRepeat$("rosetta", 1)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
end | Give a code snippet in #BASIC
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) ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbe... | #Go | Go | package main
import (
"flag"
"fmt"
"github.com/jbarham/primegen.go" // Sieve of Atkin implementation
"math"
)
// primeCache is a simple cache of small prime numbers, it very
// well might be faster to just regenerate them as needed.
type primeCache struct {
gen *primegen.Primegen
primes []uint64
}
func N... | Give a code snippet in #Go
An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emi... | 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 ... | #Icon_and_Unicon | Icon and Unicon | procedure timef(f) #: time a function f
local gcol,alloc,used,size,runtime,header,x,i
title := ["","total","static","string","block"] # headings
collect() # start with collected memory (before baseline)
every put(gcol := [], -&collections) ... | Give a code snippet in #Icon_and_Unicon
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 ti... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #FreeBASIC | FreeBASIC |
'From first principles (No external library)
Function _divide(n1 As String,n2 As String,decimal_places As Integer=10,dpflag As String="s") As String
Dim As String number=n1,divisor=n2
dpflag=Lcase(dpflag)
'For MOD
Dim As Integer modstop
If dpflag="mod" Then
If Len(n1)<Len(n2) Then Retur... | Give a code snippet in #FreeBASIC
Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Assertions | Assertions | Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| #Dyalect | Dyalect | var x = 42
assert(42, x) | Give a code snippet in #Dyalect
Assertions are a way of breaking out of code when there is an error or an unexpected input.
Some languages throw exceptions and some treat it as a break point.
Task
Show an assertion in your language by asserting that an integer variable is equal to 42.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Aikido | Aikido |
var names = {} // empty map
names["foo"] = "bar"
names[3] = 4
// initialized map
var names2 = {"foo": bar, 3:4}
// lookup map
var name = names["foo"]
if (typeof(name) == "none") {
println ("not found")
} else {
println (name)
}
// remove from map
delete names["foo"]
| Give a code snippet in #Aikido
Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #C.2B.2B | C++ | #include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
} | Give a code snippet in #C.2B.2B
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| christopher/rosetta-code | |
http://rosettacode.org/wiki/String_case | String case | Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not reversable.
Show any additional... | #Befunge | Befunge | "ATEBahpla" > : #v_ 25* , @ >48*-v
> :: "`"` \"{"\` * | > , v
> ^
^ < | Give a code snippet in #Befunge
Task
Take the string alphaBETA and demonstrate how to convert it to:
upper-case and
lower-case
Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.
Note: In some languages alphabets toLower and toUpper is not... | christopher/rosetta-code | |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Julia | Julia | using Nettle
labels = ["\"\" (empty string)", "\"a\"", "\"abc\"",
"\"message digest\"", "\"a...z\"",
"\"abcdbcde...nopq\"", "\"A...Za...z0...9\"",
"8 times \"1234567890\"", "1 million times \"a\""]
texts = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz",
"abcdbcdecdefde... | Give a code snippet in #Julia
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the AS... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #GB_BASIC | GB BASIC | 10 color 1
20 point 100,100 | Give a code snippet in #GB_BASIC
Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Java | Java | int i = 1024;
while(i > 0){
System.out.println(i);
i >>= 1; //also acceptable: i /= 2;
} | Give a code snippet in #Java
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #Racket | Racket | #lang racket/base
(require racket/match racket/string)
(define (linear-combination->string es)
(let inr ((es es) (i 1) (rv ""))
(match* (es rv)
[((list) "") "0"]
[((list) rv) rv]
[((list (? zero?) t ...) rv)
(inr t (add1 i) rv)]
[((list n t ...) rv)
(define ±n
(mat... | Give a code snippet in #Racket
Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
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 loop b... | #PARI.2FGP | PARI/GP | forstep(n=1,10,2,print(n)) | Give a code snippet in #PARI.2FGP
Task
Demonstrate a for-loop where the step-value is greater than one.
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #Oforth | Oforth | import: parallel
Object Class new: Semaphore(ch)
Semaphore method: initialize(n)
Channel newSize(n) dup := ch
#[ 1 over send drop ] times(n) drop ;
Semaphore method: acquire @ch receive drop ;
Semaphore method: release 1 @ch send drop ; | Give a code snippet in #Oforth
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times ... | #Quackery | Quackery | [ stack [ 0 0 0 0 0 0 0 ] ] is bins ( --> s )
[ 7 times
[ 0 bins take
i poke
bins put ] ] is emptybins ( --> )
[ bins share over peek
1+ bins take rot poke
bins put ] is bincrement ( n --> )
[ emptybins
ove... | Give a code snippet in #Quackery
This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing rand... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Kronecker_product_based_fractals | Kronecker product based fractals | This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the matrix (filled with 0/1) we ... | #zkl | zkl | var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
fcn kronecker(A,B){ //--> new Matrix
m,n, p,q := A.rows,A.cols, B.rows,B.cols;
r:=GSL.Matrix(m*p, n*q);
foreach i,j,k,l in (m,n,p,q){ r[p*i + k, q*j + l]=A[i,j]*B[k,l] }
r
}
fcn kfractal(M,n,fname){
R:=M;
do(n){ R=kronecker... | Give a code snippet in #zkl
This task is based on Kronecker product of two matrices.
If your language has no a built-in function for such product then you need to implement it first.
The essence of fractals is self-replication (at least, self-similar replications).
So, using n times self-product of the mat... | 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 ... | #Oz | Oz | fun{FibI N}
Temp = {NewCell 0}
A = {NewCell 0}
B = {NewCell 1}
in
for I in 1..N do
Temp := @A + @B
A := @B
B := @Temp
end
@A
end | Give a code snippet in #Oz
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 ge... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #AppleScript | AppleScript | on isqrt(x)
set q to 1
repeat until (q > x)
set q to q * 4
end repeat
set z to x
set r to 0
repeat while (q > 1)
set q to q div 4
set t to z - r - q
set r to r div 2
if (t > -1) then
set z to t
set r to r + q
end if
end ... | Give a code snippet in #AppleScript
Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Unbounded | Knapsack problem/Unbounded | A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La. Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it.
He knows that he can carry no more than 25 'weights' in total; and tha... | #Modula-3 | Modula-3 | MODULE Knapsack EXPORTS Main;
FROM IO IMPORT Put;
FROM Fmt IMPORT Int, Real;
TYPE Bounty = RECORD
value: INTEGER;
weight, volume: REAL;
END;
VAR totalWeight, totalVolume: REAL;
maxPanacea, maxIchor, maxGold, maxValue: INTEGER := 0;
n: ARRAY [1..3] OF INTEGER;
panacea, ichor, gold, sack, current: B... | Give a code snippet in #Modula-3
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La. Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it.
He knows that he can carry no more than ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #Vala | Vala | namespace CatalanNumbers {
public class CatalanNumberGenerator {
private static double factorial(double n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
public double first_method(double n) {
const double top_multiplier = 2;
return factorial(top_multiplier * n) /... | Give a code snippet in #Vala
Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Octave | Octave | function m = mode2(v)
sv = sort(v);
% build two vectors, vals and c, so that
% c(i) holds how many times vals(i) appears
i = 1; c = []; vals = [];
while (i <= numel(v) )
tc = sum(sv==sv(i)); % it would be faster to count
% them "by hand", since sv is sorted...
c = [c, tc];
... | Give a code snippet in #Octave
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #PicoLisp | PicoLisp | (in NIL # Guarantee reading from standard input
(let (Str (read) Num (read))
(prinl "The string is: \"" Str "\"")
(prinl "The number is: " Num) ) ) | Give a code snippet in #PicoLisp
User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #APL | APL | ⍝ Create a namespace ("hash")
X←⎕NS ⍬
⍝ Assign some names
X.this←'that'
X.foo←88
⍝ Access the names
X.this
that
⍝ Or do it the array way
X.(foo this)
88 that
⍝ Namespaces are first class objects
sales ← ⎕NS ⍬
sales.(prices quantities) ← (10... | Give a code snippet in #APL
Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, El... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #Nim | Nim | import fenv, strutils
proc `++`(a, b: float): tuple[lower, upper: float] =
let
a {.volatile.} = a
b {.volatile.} = b
orig = fegetround()
discard fesetround FE_DOWNWARD
result.lower = a + b
discard fesetround FE_UPWARD
result.upper = a + b
discard fesetround orig
proc ff(a: float): string = a... | Give a code snippet in #Nim
Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionall... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #FreeBASIC | FreeBASIC | ' person.bi file
Type Person
name As String
age As UInteger
Declare Operator Cast() As String
End Type
Operator Person.Cast() As String
Return "[" + This.name + ", " + Str(This.age) + "]"
End Operator | Give a code snippet in #FreeBASIC
Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Java | Java | import java.util.ArrayList;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
public class FindMissingPermutation {
public static void main(String[] args) {
Joiner joiner = Joiner.on("").skipNulls();
ImmutableSet<String> s = ImmutableSe... | Give a code snippet in #Java
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
... | 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 ... | #VBScript | VBScript | function multiply( multiplicand, multiplier )
multiply = multiplicand * multiplier
end function | Give a code snippet in #VBScript
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for d... | #Smalltalk | Smalltalk | Object subclass: Polynomial [
|coeffs|
Polynomial class >> new [ ^ super basicNew init ]
init [ coeffs := OrderedCollection new. ^ self ]
Polynomial class >> newWithCoefficients: coefficients [
|r|
r := super basicNew.
^ r initWithCoefficients: coefficients
]
initWithCoefficients: coefficients [... | Give a code snippet in #Smalltalk
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/First-class_functions | First-class functions | A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as retu... | #Python | Python | >>> # Some built in functions and their inverses
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> # First class functions allow run-time creation of functions from functions
>>> # return function compose(f,g... | Give a code snippet in #Python
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["AB... | #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
Sub Split(s As String, sep As String, result() As String)
Dim As Integer i, j, count = 0
Dim temp As String
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To Len(s) - 1
For j = 0 To Len(sep) - 1
If s[i] = sep[j] Then
count += 1
position(count) = ... | Give a code snippet in #FreeBASIC
Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
A... | 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... | #Excel | Excel | showAlphabet
=LAMBDA(az,
ENUMFROMTOCHAR(
MID(az, 1, 1)
)(
MID(az, 2, 1)
)
) | Give a code snippet in #Excel
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Phix | Phix | constant INVALID_UTF8 = #FFFD
function get_one_utf8_char(integer fn)
-- returns INVALID_UTF8 on error, else a string of 1..4 bytes representing one character
object res
integer headb, bytes, c
-- headb = first byte of utf-8 character:
headb = getc(fn)
if headb=-1 then return -1 end if
res = ""&headb... | Give a code snippet in #Phix
Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should suppor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Long_multiplication | Long multiplication | Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 is:
18,446,744,073,709,551,61... | #REXX | REXX | /*REXX program performs long multiplication on two numbers (without the "E"). */
numeric digits 300 /*be able to handle gihugeic input #s. */
parse arg x y . /*obtain optional arguments from the CL*/
if x=='' | x=="," then x= 2**64 ... | Give a code snippet in #REXX
Task
Explicitly implement long multiplication.
This is one possible approach to arbitrary-precision integer algebra.
For output, display the result of 264 * 264.
Optionally, verify your result against builtin arbitrary precision support.
The decimal representation of 264 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for d... | #REXX | REXX | /* REXX needed by some... */
z='1 -12 0 -42' /* Numerator */
n='1 -3' /* Denominator */
zx=z
nx=n copies('0 ',words(z)-words(n))
qx='' /* Quotient */
Do Until words(zx)<words(n)
Parse Value div(zx,nx) With q zx
qx=qx q
nx=subword(nx,1,words(nx)-1)
End
Say '('show(z)')/('show(n)')=('show... | Give a code snippet in #REXX
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
/* assumes a and b are always equal */
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
// calculate y for each x
y := make([]float64, a+1)
for x := 0; x <= a; x++ ... | Give a code snippet in #Go
A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a supe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ray-casting_algorithm | Ray-casting algorithm |
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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)
Given a point and a polygon, check if the point is inside or out... | #Python | Python | from collections import namedtuple
from pprint import pprint as pp
import sys
Pt = namedtuple('Pt', 'x, y') # Point
Edge = namedtuple('Edge', 'a, b') # Polygon edge from a to b
Poly = namedtuple('Poly', 'name, edges') # Polygon
_eps = 0.00001
_huge = sys.float_info.max
_tiny = sys.float_i... | Give a code snippet in #Python
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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)
Given a point and a polygon, che... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the foll... | #11l | 11l | F find_common_directory_path(paths, sep = ‘/’)
V pos = 0
L
L(path) paths
I pos < path.len & path[pos] == paths[0][pos]
L.continue
L pos > 0
pos--
I paths[0][pos] == sep
L.break
R paths[0][0.<pos]
pos++
print(find_common_... | Give a code snippet in #11l
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the dir... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Raku | Raku | sub carpet
{
(['#'], -> @c {
[
|@c.map({$_ x 3}),
|@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}),
|@c.map({$_ x 3})
]
} ... *).map: { .join("\n") };
}
say carpet[3];
# Same as above, structured as an array bound to a sequence, with a separate sub for clarity.
sub weave ( @... | Give a code snippet in #Raku
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## ... | 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
| #Wren | Wren | import "/pattern" for Pattern
var s = "This is a story about R2D2 and C3P0 who are best friends."
var p = Pattern.new("/u/d/u/d")
var matches = p.findAll(s)
System.print("Original string:\n%(" %(s)")")
System.print("\nThe following matches were found:")
matches.each{ |m| System.print(" %(m.text) at index %(m.inde... | Give a code snippet in #Wren
Task
match a string against a regular expression
substitute part of a string using a regular expression
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case... | #Julia | Julia |
const lim = 250
const pwr = 5
const p = [i^pwr for i in 1:lim]
x = zeros(Int, pwr-1)
y = 0
for a in combinations(1:lim, pwr-1)
b = searchsorted(p, sum(p[a]))
0 < length(b) || continue
x = a
y = b[1]
break
end
if y == 0
println("No solution found for power = ", pwr, " and limit = ", lim, ... | Give a code snippet in #Julia
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Icon_and_Unicon | Icon and Unicon | procedure shuffle(l)
repeat {
!l :=: ?l
suspend l
}
end
procedure sorted(l)
local i
if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1
end
procedure main()
local l
l := [6,3,4,5,1]
|( shuffle(l) & sorted(l)) \1 & every writes(" ",!l)
end | Give a code snippet in #Icon_and_Unicon
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (209... | #OCaml | OCaml | let to_vlq n =
let a, b = n lsr 7, n land 0x7F in
let rec aux n acc =
let x = (n land 0x7F) lor 0x80
and xs = n lsr 7 in
if xs > 0
then aux xs (x::acc)
else x::acc
in
aux a [b]
let to_num = List.fold_left (fun n x -> n lsl 7 + (x land 0x7F)) 0
let v_rep n =
Printf.printf "%d ->" n;
l... | Give a code snippet in #OCaml
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert ... | 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... | #GML | GML | n = argument0
j = 1
for(i = 1; i <= n; i += 1)
j *= i
return j | Give a code snippet in #GML
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #J | J | NB. character classes:
NB. 0: whitespace
NB. 1: "
NB. 2: \
NB. 3: [ ] , { } :
NB. 4: ordinary
classes=.3<. '"\[],{}:' (#@[ |&>: i.) a.
classes=.0 (I.a.e.' ',CRLF,TAB)} (]+4*0=])classes
words=:(0;(0 10#:10*".;._2]0 :0);classes)&;: NB. states:
0.0 1.1 2.1 3.1 4.1 NB. 0 whitespace
1.0 5.0 6.0 1... | Give a code snippet in #J
Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available,... | #FreeBASIC | FreeBASIC | ' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
Dim As Integer a(5) ' from s(0) to s(5)
Dim As Integer num = 1
Dim As String s(-num To num) ' s1(-1), s1(0) and s1(1)
Static As UByte c(5) ' create a array with 6 elements (0 to 5)
'dimension array and initializing it ... | Give a code snippet in #FreeBASIC
This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrat... | #PL.2FI | PL/I |
/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */
cvt: procedure options (main); /* 5 August 2015 */
declare interval float (15);
declare (unit, i, q controlled) fixed binary;
declare done bit (1) static initial ('0'b);
declare name (5) character (4) varying static ini... | Give a code snippet in #PL.2FI
Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g.... | 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 |... | #Z80_Assembly | Z80 Assembly | ld a,(&C000) ;load the accumulator with the value from the memory address &C000.
ld hl,&D000
ld e,(hl) ;load the E register with the byte at memory address &D000.
ld bc,(&E000) ;load the register pair BC from memory address &E000.
; This is the same as:
; ld a,(&E000)
; ld c,a
; ld a,(&E001)
; ld b,a
ld ... | Give a code snippet in #Z80_Assembly
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Oper... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_length | Array length | Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I befo... | #Arturo | Arturo | fruit: ["apple" "orange"]
print ["array length =" size fruit] | Give a code snippet in #Arturo
Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter freq... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #ALGOL_68 | ALGOL 68 | STRING s := "12345"; FILE f; INT i;
associate(f, s); get(f,i);
i+:=1;
s:=""; reset(f); put(f,i);
print((s, new line)) | Give a code snippet in #ALGOL_68
Task
Increment a numerical string.
| 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 ... | #Janet | Janet | (defmacro time
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
[body]
(with-syms [$start $val]
~(let [,$start (os/clock)
,$val ,body]
(eprint (- (os/clock) ,$start))
,$val)))
(time (os/sleep 0.5)) | Give a code snippet in #Janet
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... | 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... | #Raku | Raku | # 20201120 Raku programming solution
my \MAXITER = 151;
sub minkowski(\x) {
return x.floor + minkowski( x - x.floor ) if x > 1 || x < 0 ;
my $y = my $p = x.floor;
my ($q,$s,$d) = 1 xx 3;
my $r = $p + 1;
loop {
last if ( $y + ($d /= 2) == $y ) ||
( my $m = $p + $r) < ... | Give a code snippet in #Raku
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/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #Smalltalk | Smalltalk | Smalltalk at: #stepUp put: 0.
stepUp := [ [ step value ] whileFalse: [ stepUp value ] ]. | Give a code snippet in #Smalltalk
From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Haskell | Haskell | do {- ... -}
throwIO SomeException | Give a code snippet in #Haskell
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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
Write a function to compute the arithmetic-geomet... | #NewLISP | NewLISP |
(define (a-next a g) (mul 0.5 (add a g)))
(define (g-next a g) (sqrt (mul a g)))
(define (amg a g tolerance)
(if (<= (sub a g) tolerance)
a
(amg (a-next a g) (g-next a g) tolerance)
)
)
(define quadrillionth 0.000000000000001)
(define root-reciprocal-2 (div 1.0 (sqrt 2.0)))
(println
"To the nearest ... | Give a code snippet in #NewLISP
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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
Write a function... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks r... | #BASIC | BASIC | 10 LET Q$=CHR$(34): REM DOUBLEQUOTES
20 LET D$=Q$+Q$: REM A PAIR OF DOUBLEQUOTES
30 LET S$=Q$+"THIS IS A QUOTED STRING"+Q$
40 PRINT Q$;"HELLO";Q$:REM ADD QUOTES DURING OUTPUT | Give a code snippet in #BASIC
Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
IDYES = 6
ES_NUMBER = 8192
MB_YESNO = 4
form% = FN_newdialog("Rosetta Code", 100, 100, 100, 52, 8, 1000)
PROC_static(form%, "Value:", 100, 10, 10, 24, 14, 0)
PROC_editbox(form%, "0", 101, 40, 8, 52, 14, ES_NUMBER)
... | Give a code snippet in #BBC_BASIC
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and che... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Kotlin | Kotlin | /**
* A group of *members*.
* @author A Programmer.
* @since version 1.1.51.
*
* This class has no useful logic; it's just a documentation example.
*
* @param T the type of a member in this group.
* @property name the name of this group.
* @constructor Creates an empty group.
*/
class Group<T>(val name: Stri... | Give a code snippet in #Kotlin
See also
Related task: Comments
Related task: Here_document
| 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;... | #Wart | Wart | def (mid3 n)
withs (digits (with outstring # itoa
(pr abs.n))
max len.digits
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2) | Give a code snippet in #Wart
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 tes... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Order_by_pair_comparisons | Order by pair comparisons |
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
... | #Wren | Wren | import "/ioutil" for Input
import "/fmt" for Fmt
// Inserts item x in list a, and keeps it sorted assuming a is already sorted.
// If x is already in a, inserts it to the right of the rightmost x.
var insortRight = Fn.new{ |a, x, q|
var lo = 0
var hi = a.count
while (lo < hi) {
var mid = ((lo + hi... | Give a code snippet in #Wren
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/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous numb... | #C | C | #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
/* OK for 'small' numbers. */
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) ... | Give a code snippet in #C
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
353... | 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 ... | #Bracmat | Bracmat | ( ( oneOf
= operator
. !arg:%?operator ?arg
& ( @(!sjt:!operator ?arg)&(!operator.!arg)
| oneOf$!arg
)
)
& "a!===b=!=c":?unparsed
& "==" "!=" "=":?operators
& whl
' ( @( !unparsed
: ?nonOp [%(oneOf$!operators:(?operator.?unparsed))
)
& put$(!nonOp str$("{" !operat... | Give a code snippet in #Bracmat
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Julia | Julia | using Random
"""Useful constants for the colors to be selected for nodes of the graph"""
const colors4 = ["blue", "red", "green", "yellow"]
const badcolor = "black"
@assert(!(badcolor in colors4))
"""
struct graph
undirected simple graph
constructed from its name and a string listing of point to point connect... | Give a code snippet in #Julia
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
zigzag(5)
return
method zigzag(msize) public static
row = 1
col = 1
ziggy = Rexx(0)
loop j_ = 0 for msize * msize
ziggy[row, col] = j_
if (row + col) // 2 == 0 then do
if col < msize then -
col = c... | Give a code snippet in #NetRexx
Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to e... | 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... | #Clojure | Clojure | (def denomination-kind [1 5 10 25])
(defn- cc [amount denominations]
(cond (= amount 0) 1
(or (< amount 0) (empty? denominations)) 0
:else (+ (cc amount (rest denominations))
(cc (- amount (first denominations)) denominations))))
(defn count-change
"Calculates the number of time... | Give a code snippet in #Clojure
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
... | #Sparkling | Sparkling | # Computes conjugate transpose of M
let conjTransp = function conjTransp(M) {
return map(range(sizeof M[0]), function(row) {
return map(range(sizeof M), function(col) {
return cplx_conj(M[col][row]);
});
});
};
# Helper for cplxMatMul
let cplxVecScalarMul = function cplxVecScalarMul(A, B, row, col) {
var M ... | Give a code snippet in #Sparkling
Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Brilliant_numbers | Brilliant numbers | Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.
E.G.
3 × 3 (9) is a bri... | #Java | Java | import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) ... | Give a code snippet in #Java
Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10.
Brilliant numbers are useful in cryptography and when testing prime factoring algorithm... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #FreeBASIC | FreeBASIC |
'$lang: "qb"
Gosub subrutina
bucle:
Print "Bucle infinito"
Goto bucle
End
subrutina:
Print "En subrutina"
Sleep 100
Return
Sleep
| Give a code snippet in #FreeBASIC
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto constr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #RapidQ | RapidQ | FOR i=1 TO 100
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
PRINT IIF(LEN(t$), t$, i)
NEXT i | Give a code snippet in #RapidQ
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Modula-2 | Modula-2 | MODULE Menu;
FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard;
CONST StringLength = 100;
MenuSize = 4;
TYPE String = ARRAY[0..StringLength-1] OF CHAR;
VAR menu : ARRAY[0..MenuSize] OF String;
selection, index : CARDINAL;
BEGIN
menu[... | Give a code snippet in #Modula-2
Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Erlang | Erlang |
-module(ca).
-compile(export_all).
run(N,G) ->
run(N,G,0).
run(GN,G,GN) ->
io:fwrite("~B: ",[GN]),
print(G);
run(N,G,GN) ->
io:fwrite("~B: ",[GN]),
print(G),
run(N,next(G),GN+1).
print([]) ->
io:fwrite("~n");
print([0|T]) ->
io:fwrite("_"),
print(T);
print([1|T]) ->
io:fw... | Give a code snippet in #Erlang
Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curren... | 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
| #XPL0 | XPL0 | There are only three variable types: 32-bit signed integers (in the
32-bit version), IEEE-754 64-bit reals, and characters which are actually
32-bit addresses of (or pointers to) strings. When a 'char' variable is
subscripted, it accesses a single byte. All variable names must be
declared before they are used, for exam... | Give a code snippet in #XPL0
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/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #VBScript | VBScript |
Sub truncate(fpath,n)
'Check if file exist
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
'stream the input file
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1... | Give a code snippet in #VBScript
Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by crea... | 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
... | #Lasso | Lasso | define rms(a::staticarray)::decimal => {
return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size))
}
rms(generateSeries(1,10)->asStaticArray) | Give a code snippet in #Lasso
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/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... | #SQL | SQL |
-- variable table
DROP TABLE IF EXISTS var;
CREATE temp TABLE var ( VALUE VARCHAR(1000) );
INSERT INTO var(VALUE) SELECT 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';
-- select
WITH recursive
ints(num) AS
(
SELECT 1
UNION ALL
SELECT num+1
FROM ints
WHERE num+1 <= LENGTH((SELECT VALUE ... | Give a code snippet in #SQL
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 functi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Kotlin | Kotlin |
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.JFrame
import javax.swing.JPanel
class JuliaPanel : JPanel() {
init {
preferredSize = Dimension(800, 600)
background = Color.white
}
private val maxIterations = 300
private val zoom = 1
private val moveX =... | Give a code snippet in #Kotlin
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #JavaScript | JavaScript | function swap(arr) {
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
} | Give a code snippet in #JavaScript
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides gene... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod=... | #Perl | Perl | use constant one => 1;
use constant three => 3;
use constant seven => 7;
use constant x => 5;
use constant yy => -5; # 'y' conflicts with use as equivalent to 'tr' operator (a carry-over from 'sed')
use constant z => -2;
my $prod = 1;
sub from_to_by {
my($begin,$end,$skip) = @_;
my $n = 0;
... | Give a code snippet in #Perl
Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED a... | 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... | #Phix | Phix | atom i=42, n=1
while n<=42 do
if is_prime(i) then
printf(1,"n = %-2d %,19d\n", {n, i})
n += 1
i += i-1
end if
i += 1
end while
| Give a code snippet in #Phix
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:
... | 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... | #Logo | Logo | ; We'll just use words for the balls
make "colors {red white blue}
; to get a mapping from colors back to a numeric value,
; we make variables out of the color names (e.g. the variable
; "red" has value "1").
foreach arraytolist :colors [
make ? #
]
; Make a random list of a given size
to random_balls :n
local ... | Give a code snippet in #Logo
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 col... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 6 ПП 04
П7 КПП7 В/О
1 В/О | Give a code snippet in #.D0.9C.D0.9A-61.2F52
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #S-lang | S-lang | private variable mx, mxkey, modedat;
define find_max(key) {
if (modedat[key] > mx) {
mx = modedat[key];
mxkey = {key};
}
else if (modedat[key] == mx) {
list_append(mxkey, key);
}
}
define find_mode(indat)
{
% reset [file/module-scope] globals:
mx = 0, mxkey = {}, modedat = Assoc_Type[Int_Typ... | Give a code snippet in #S-lang
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if p... | 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 |... | #Delphi | Delphi | pMyPointer : Pointer ; | Give a code snippet in #Delphi
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/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #Applesoft_BASIC | Applesoft BASIC | 10 INPUT "GIMME A NUMBER! "; N
20 GOSUB 100"NUMBER NAME
30 PRINT R$
40 END
100 REMNUMBER NAME
110 IF R$ = "" THEN FOR I = 0 TO 10 : READ S$(I), T$(I), U$(I), V$(I) : NEXT
120 IF N = 0 THEN R$ = "ZERO" : RETURN
130 R$ = "" : D = 10 : C = 100 : M = 1E3
140 A = ABS(N)
150 FOR U = 0 TO D
160 H = A - C * INT(A / C)
17... | Give a code snippet in #Applesoft_BASIC
Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other... | christopher/rosetta-code | |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #C.2B.2B | C++ | #include <cctype>
#include <iomanip>
#include <iostream>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <variant>
namespace s_expr {
enum class token_type { none, left_paren, right_paren, symbol, string, number };
enum class char_type { left_paren, right_paren, quote, escape, space,... | Give a code snippet in #C.2B.2B
S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable da... | 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... | #zkl | zkl | fcn fact(n){[2..n].reduce('*,1)}
fcn factTail(n,N=1) { // tail recursion
if (n == 0) return(N);
return(self.fcn(n-1,n*N));
} | Give a code snippet in #zkl
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #JoCaml | JoCaml | let random_wait n = Unix.sleep (Random.int n);;
let print s m = Printf.printf "philosopher %s is %s\n" s m; flush(stdout);;
let will_eat s = print s "eating"; random_wait 10;;
let will_think s = print s "thinking"; random_wait 20; print s "hungry";;
(* a,b,c,d,e are thinking philosophers; ah,bh,ch,dh,eh are the sam... | Give a code snippet in #JoCaml
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eat... | 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
... | #Prolog | Prolog |
product(A, B, C) :- C is A*B.
pair(X, Y, X-Y).
egcd(_, 0, 1, 0) :- !.
egcd(A, B, X, Y) :-
divmod(A, B, Q, R),
egcd(B, R, S, X),
Y is S - Q*X.
modinv(A, B, X) :-
egcd(A, B, X, Y),
A*X + B*Y =:= 1.
crt_fold(A, M, P, R0, R1) :- % system of equations of (x = a) (mod m); p = M/m
modinv(P, M... | Give a code snippet in #Prolog
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
{\display... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Nim | Nim | import sugar, std/monotimes, times
type Func[T] = (T) -> T
func cube(n: int): int = n * n * n
proc benchmark[T](n: int; f: Func[T]; arg: T): seq[Duration] =
result.setLen(n)
for i in 0..<n:
let m = getMonoTime()
discard f(arg)
result[i] = getMonoTime() - m
echo "Timings (nanoseconds):"
for time ... | Give a code snippet in #Nim
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #M2000_Interpreter | M2000 Interpreter |
Module checkit {
class Vector {
\\ by default are double
a,b,c
Property ToString$ {
Value {
link parent a,b,c to a,b,c
value$=format$("({0}, {1}, {2})",a,b,c)
... | Give a code snippet in #M2000_Interpreter
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a t... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.