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/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary... | #Kotlin | Kotlin | // version 1.1.2
const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
fun encodeNegBase(n: Long, b: Int): String {
require(b in -62 .. -1)
if (n == 0L) return "0"
val out = mutableListOf<Char>()
var nn = n
while (nn != 0L) {
var rem = (nn % b).toInt()
... | Give a code snippet in #Kotlin
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card mu... | #PicoLisp | PicoLisp | (de *Suits
Club Diamond Heart Spade )
(de *Pips
Ace 2 3 4 5 6 7 8 9 10 Jack Queen King )
(de mkDeck ()
(mapcan
'((Pip) (mapcar cons *Suits (circ Pip)))
*Pips ) )
(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) ) | Give a code snippet in #PicoLisp
Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the curren... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Haskell | Haskell | import Network.BSD
main = do hostName <- getHostName
putStrLn hostName | Give a code snippet in #Haskell
Task
Find the name of the host on which the routine is running.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem | Primality by Wilson's theorem | Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
| #Haskell | Haskell | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
p... | Give a code snippet in #Haskell
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #VBA | VBA |
Option Explicit
Sub Main()
Dim s() As String, i As Long
Debug.Print "list of 10 passwords : "
'do a list of 10 passwords with password's lenght = 21 and visually similar = False
s = Gp(10, 21, False)
'return
Debug.Print "1- with password's lenght = 21 and visually similar = False :"
... | Give a code snippet in #VBA
Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use sys... | #BBC_BASIC | BBC BASIC | VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 mode
*FONT Arial Unicode MS,36
PRINT CHR$(&E2)+CHR$(&96)+CHR$(&B3) | Give a code snippet in #BBC_BASIC
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Not... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/functi... | #R | R | seq(from = -2, to = 2, by = 1)#Output: -2 -1 0 1 2
seq(from = -2, to = 2, by = 0)#Fails: "invalid '(to - from)/by'"
seq(from = -2, to = 2, by = -1)#Fails: As in the notes above - "Specifying to - from and by of opposite signs is an error."
seq(from = -2, to = 2, by = 10)#Output: -2
seq(from = 2, to = -2, by = 1)#Fai... | Give a code snippet in #R
Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to sel... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Racket | Racket |
#lang racket
(define (forward-difference list)
(for/list ([x (cdr list)] [y list]) (- x y)))
(define (nth-forward-difference n list)
(for/fold ([list list]) ([n n]) (forward-difference list)))
(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)
| Give a code snippet in #Racket
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Break_OO_privacy | Break OO privacy | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is... | #PicoLisp | PicoLisp | (class +Example)
# "_name"
(dm T (Name)
(=: "_name" Name) )
(dm string> ()
(pack "Hello, I am " (: "_name")) )
(====) # Close transient scope
(setq Foo (new '(+Example) "Eric")) | Give a code snippet in #PicoLisp
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming too... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Phix | Phix | without js -- file i/o
sequence sizes = {1},
res = {0}
atom t1 = time()+1
function store_res(string filepath, sequence dir_entry)
if not find('d', dir_entry[D_ATTRIBUTES]) then
atom size = dir_entry[D_SIZE]
integer sdx = 1
while size>sizes[sdx] do
if sdx=length(sizes) ... | Give a code snippet in #Phix
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #FOCAL | FOCAL | 01.10 A "HOW MANY",M
01.20 S B(0)=1;S B(1)=0
01.30 F Z=1,M;D 4;D 2
01.40 Q
02.10 S X=0;S Y=0
02.15 I (B(X)),2.5
02.17 S CN=0
02.20 S CN=CN+1
02.25 S X=X+1
02.30 I (FABS(B(X)-B(X-1))),2.2
02.35 S C(Y)=CN;S C(Y+1)=B(X-1)
02.40 S Y=Y+2
02.45 G 2.15
02.50 S C(Y)=0
02.55 F X=0,Y;S B(X)=C(X)
03.10 I (A-9)3.2;T "9";R
03.2... | Give a code snippet in #FOCAL
The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int PLAYERS = 2, MAX_POINT... | Give a code snippet in #C.2B.2B
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Delphi | Delphi |
program Element_insertion;
{$APPTYPE CONSOLE}
uses
System.SysUtils,Boost.LinkedList;
var
List:TLinkedList<Integer>;
Node:TLinkedListNode<Integer>;
begin
List := TLinkedList<Integer>.Create;
Node:= List.Add(5);
List.AddAfter(Node,7);
List.AddAfter(Node,15);
Writeln(List.ToString);
List.Free;
Re... | Give a code snippet in #Delphi
Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE ENTRY_SIZE="3"
TYPE TRIPLE=[BYTE a,b,c]
TYPE TRIPLES=[
PTR buf ;BYTE ARRAY
BYTE count]
PTR FUNC GetItemAddr(TRIPLES POINTER arr BYTE index)
PTR addr
addr=arr.buf+index*ENTRY_SIZE
RETURN (addr)
PROC PrintTriples(TRIPLES POINTER arr)
INT i
TRIPLE POINTER t
FOR i=0 TO arr.cou... | Give a code snippet in #Action.21
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\... | 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... | #VBScript | VBScript | Dim lookupTable(170), returnTable(170), currentPosition, input
currentPosition = 0
Do While True
input = InputBox("Please type a number (-1 to quit):")
MsgBox "The factorial of " & input & " is " & factorial(CDbl(input))
Loop
Function factorial (x)
If x = -1 Then
WScript.Quit 0
End If
Dim temp
temp = lookup... | Give a code snippet in #VBScript
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #REXX | REXX | /*REXX program test if a (REXX) variable is defined or not defined. */
tlaloc = "rain god of the Aztecs." /*assign a value to the Aztec rain god.*/
/*check if the rain god is defined. */
y= 'tlaloc'
if symbol(y)=="VAR" then say y ' is defined.'
... | Give a code snippet in #REXX
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Attractive_numbers | Attractive numbers | A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) is also prime.
Task
Show sequence items up to 120.... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[AttractiveNumberQ]
AttractiveNumberQ[n_Integer] := FactorInteger[n][[All, 2]] // Total // PrimeQ
Reap[Do[If[AttractiveNumberQ[i], Sow[i]], {i, 120}]][[2, 1]] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
A number is an attractive number if the number of its prime factors (whether distinct or not) is also prime.
Example
The number 20, whose prime decomposition is 2 × 2 × 5, is an attractive number because the number of its prime factors (3) ... | 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... | #Go | Go | package main
import "math"
import "fmt"
// user-defined function, per task. Other math functions used are built-in.
func cube(x float64) float64 { return math.Pow(x, 3) }
// ffType and compose function taken from Function composition task
type ffType func(float64) float64
func compose(f, g ffType) ffType {
... | Give a code snippet in #Go
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 func... | 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 ... | #SenseTalk | SenseTalk | put multiply(3,7) as words
to multiply num1, num2
return num1 * num2
end multiply
| Give a code snippet in #SenseTalk
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 distr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Babel | Babel | main: { [2 3 5 7 11 13] sp }
sum! : { <- 0 -> { + } eachar }
product!: { <- 1 -> { * } eachar }
sp!:
{ dup
sum %d cr <<
product %d cr << }
Result:
41
30030 | Give a code snippet in #Babel
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Ursala | Ursala | #import std
#import cli
#executable ('parameterized','')
myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-! | Give a code snippet in #Ursala
Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Pascal | Pascal | program HelloWorldAnimatedGUI;
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
Interfaces, // this includes the LCL widgetset
Forms,
Classes,
Controls,
StdCtrls,
ExtCtrls;
type
{ TFrmHelloWorldAnim }
TFrmHelloWorldAnim = class(TForm)
constructor CreateNew(AOwner: TComponent... | Give a code snippet in #Pascal
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Yabasic | Yabasic | ;assumes this runs inline
org &1000 ;program start
main:
call GetInput ;unimplemented input get routine, returns key press in accumulator
cp 'Y' ;compare to ascii capital Y
ret z ;return to BASIC if equal
jp main ;loop back to main | Give a code snippet in #Yabasic
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalize... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a ... | #Fortran | Fortran | program Normal_Distribution
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer, parameter :: r64 = selected_real_kind(15)
integer(i64), parameter :: samples = 1000000_i64
real(r64) :: mean, stddev
real(r64) :: sumn = 0, sumnsq = 0
integer(i64) :: n = 0
integer(i64) :: bin(-50:50)... | Give a code snippet in #Fortran
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform rand... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Isabelle | Isabelle | theory Scratch
imports Main
begin
text‹
Given the function we want to execute multiple times is of
type \<^typ>‹unit ⇒ unit›.
›
fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where
"pure_repeat _ 0 = ()"
| "pure_repeat f (Suc n) = f (pure_repeat f n)"
text‹
Functions are pure in Isabelle. They don't have side ... | Give a code snippet in #Isabelle
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Oz | Oz | declare
class Example
meth init skip end
meth foo {System.showInfo foo} end
meth bar {System.showInfo bar} end
meth otherwise(Msg)
{System.showInfo "Unknown method "#{Label Msg}}
if {Width Msg} > 0 then
{System.printInfo "Arguments: "}
{System.show {Rec... | Give a code snippet in #Oz
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #PARI.2FGP | PARI/GP | rk4(f,dx,x,y)={
my(k1=dx*f(x,y), k2=dx*f(x+dx/2,y+k1/2), k3=dx*f(x+dx/2,y+k2/2), k4=dx*f(x+dx,y+k3));
y + (k1 + 2*k2 + 2*k3 + k4) / 6
};
rate(x,y)=x*sqrt(y);
go()={
my(x0=0,x1=10,dx=.1,n=1+(x1-x0)\dx,y=vector(n));
y[1]=1;
for(i=2,n,y[i]=rk4(rate, dx, x0 + dx * (i - 1), y[i-1]));
print("x\ty\trel. err.\n----... | Give a code snippet in #PARI.2FGP
Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
Thi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Simula | Simula | BEGIN
CLASS MyClass(instanceVariable);
INTEGER instanceVariable;
BEGIN
PROCEDURE doMyMethod(n);
INTEGER n;
BEGIN
Outint(instanceVariable, 5);
Outtext(" + ");
Outint(n, 5);
Outtext(" = ");
Outint(instanceVariable + n, 5);
... | Give a code snippet in #Simula
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the cl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort | Sorting algorithms/Insertion sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Raku | Raku | sub insertion_sort ( @a is copy ) {
for 1 .. @a.end -> $i {
my $value = @a[$i];
my $j;
loop ( $j = $i-1; $j >= 0 and @a[$j] > $value; $j-- ) {
@a[$j+1] = @a[$j];
}
@a[$j+1] = $value;
}
return @a;
}
my @data = 22, 7, 2, -5, 8, 4;
say 'input = ' ~ @data;
... | Give a code snippet in #Raku
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/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #Harbour | Harbour | cSource := "Hello World"
cDestination := cSource | Give a code snippet in #Harbour
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Scilab | Scilab | for e=["a","b","c"]
printf("%s\n",e)
end | Give a code snippet in #Scilab
Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loop... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #IDL | IDL |
print, FILE_TEST('input.txt')
print, FILE_TEST(PATH_SEP()+'input.txt')
print, FILE_TEST('docs', /DIRECTORY)
print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)
| Give a code snippet in #IDL
Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Arturo | Arturo | quickSort: function [items][
if 2 > size items -> return items
pivot: first items
left: select slice items 1 (size items)-1 'x -> x < pivot
right: select slice items 1 (size items)-1 'x -> x >= pivot
((quickSort left) ++ pivot) ++ quickSort right
]
print quickSort [3 1 2 8 5 7 9 4 6] | Give a code snippet in #Arturo
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typica... | #OCaml | OCaml | open Complex
let print_complex z =
Printf.printf "%f + %f i\n" z.re z.im
let () =
let a = { re = 1.0; im = 1.0 }
and b = { re = 3.14159; im = 1.25 } in
print_complex (add a b);
print_complex (mul a b);
print_complex (inv a);
print_complex (neg a);
print_complex (conj a) | Give a code snippet in #OCaml
A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displayst... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary... | #Scala | Scala | object NegativeBase {
val digits = ('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z')
def intToStr(n: Int, b: Int): String = {
def _fromInt(n: Int): List[Int] = {
if (n == 0) {
Nil
} else {
val r = n % b
val rp = if (r < 0) r + b else r
val m = -(n - rp)/b
rp :: _... | Give a code snippet in #Scala
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
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 |... | #ABAP | ABAP |
report z_integer_comparison.
parameters: a type int4, b type int4.
data(comparison_result) = cond string(
when a < b " can be replaced by a lt b
then |{ a } is less than { b }|
when a = b " can be replaced by a eq b
then |{ a } is equal to { b }|
when a > b " can be replaced by a gt b
then |{ a } is g... | Give a code snippet in #ABAP
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#include "vbcompat.bi"
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len... | Give a code snippet in #FreeBASIC
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #BASIC | BASIC | DECLARE SUB factor (what AS INTEGER)
REDIM SHARED factors(0) AS INTEGER
DIM i AS INTEGER, L AS INTEGER
INPUT "Gimme a number"; i
factor i
PRINT factors(0);
FOR L = 1 TO UBOUND(factors)
PRINT ","; factors(L);
NEXT
PRINT
SUB factor (what AS INTEGER)
DIM tmpint1 AS INTEGER
DIM L0 AS INTEGER, L1 AS ... | Give a code snippet in #BASIC
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/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the... | #Lingo | Lingo | chars = ["A", "ö", "Ж", "€", "𝄞"]
put "Character Unicode (int) UTF-8 (hex) Decoded"
repeat with c in chars
ba = bytearray(c)
put col(c, 12) & col(charToNum(c), 16) & col(ba.toHexString(1, ba.length), 14) & ba.readRawString(ba.length)
end repeat | Give a code snippet in #Lingo
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes rep... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem | Primality by Wilson's theorem | Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
| #BASIC | BASIC | function wilson_prime(n)
fct = 1
for i = 2 to n-1
fct = (fct * i) mod n
next i
if fct = n-1 then return True else return False
end function
print "Primes below 100" & Chr(10)
for i = 2 to 100
if wilson_prime(i) then print i; " ";
next i
end | Give a code snippet in #BASIC
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #LSL | LSL | integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
state_entry() {
list lst = [];
integer x = 0;
for(x=0 ; x<MAX_ELEMENTS ; x++) {
lst += llFrand(MAX_VALUE);
}
llOwnerSay("lst=["+llList2CSV(lst)+"]");
llOwnerSay("Geometric Mean: "+(string)llList... | Give a code snippet in #LSL
Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an establ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #PicoLisp | PicoLisp | (for (N . Str) '("Enjoy" "Rosetta" "Code")
(task (- N) (rand 1000 4000) # Random start time 1 .. 4 sec
Str Str # Closure with string value
(println Str) # Task body: Print the string
(task @) ) ) # and st... | Give a code snippet in #PicoLisp
Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in you... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k... | #Racket | Racket | #lang racket
(require math/number-theory)
(define (second-bernoulli-number n)
(if (= n 1) 1/2 (bernoulli-number n)))
(define (faulhaber-row:formulaic p)
(let ((p+1 (+ p 1)))
(reverse
(for/list ((j (in-range p+1)))
(* (/ p+1) (second-bernoulli-number j) (binomial p+1 j))))))
(define (sum-k^p:fo... | Give a code snippet in #Racket
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Perl | Perl | # Class method
MyClass->classMethod($someParameter);
# Equivalently using a class name
my $foo = 'MyClass';
$foo->classMethod($someParameter);
# Instance method
$myInstance->method($someParameter);
# Calling a method with no parameters
$myInstance->anotherMethod;
# Class and instance method calls are made behin... | Give a code snippet in #Perl
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Objeck | Objeck | class RepString {
function : Main(args : String[]) ~ Nil {
strings := ["1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1"];
each(i : strings) {
string := strings[i];
repstring := RepString(string);
if(repstring->Size() > 0) {
... | Give a code snippet in #Objeck
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at lea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, sho... | #Elixir | Elixir | defmodule Word_wrap do
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
lines_assemble( rest, max_line_length, String.length(word), word, [] )
|> Enum.join( "\n" )
end
defp lines_assemble( [], _, _, line, acc ), do: [line | acc] |> Enum.revers... | Give a code snippet in #Elixir
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or pro... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
#include <limits>
template<typename integer>
class prime_generator {
public:
integer next_prime();
integer count() const {
return count_;
}
private:
struct queue_item {
queue_item(integer prime... | Give a code snippet in #C.2B.2B
Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or pr... | 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... | #Nim | Nim |
# Brute force approach
import times
# assumes an array of non-decreasing positive integers
proc binarySearch(a : openArray[int], target : int) : int =
var left, right, mid : int
left = 0
right = len(a) - 1
while true :
if left > right : return 0 # no match found
mid = (left + right) div 2
if... | Give a code snippet in #Nim
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/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\m... | #Quackery | Quackery |
[ $ "bigrat.qky" loadfile ] now!
[ [] unrot
[ proper
2swap join unrot
over 0 != while
1/v again ]
2drop ] is cf ( n/d --> [ )
' [ [ 1 2 ]
[ 3 1 ]
[ 23 8 ]
[ 13 11 ]
[ 22 7 ]
[ -151 77 ]
[ 14142 10000 ]
[ 141421 100000 ]
[ 1... | Give a code snippet in #Quackery
Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #MiniScript | MiniScript | ordinal = function(n)
if n > 3 and n < 20 then return n + "th"
if n % 10 == 1 then return n + "st"
if n % 10 == 2 then return n + "nd"
if n % 10 == 3 then return n + "rd"
return n + "th"
end function
out = []
test = function(from, to)
for i in range(from, to)
out.push ordinal(i)
en... | Give a code snippet in #MiniScript
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixe... | #BASIC256 | BASIC256 | graphsize 30,30
call fill(rgb(255,0,0))
call setpixel(10,10,rgb(0,255,255))
print "pixel 10,10 is " + pixel(10,10)
print "pixel 20,20 is " + pixel(20,10)
imgsave "BASIC256_bitmap.png"
end
subroutine fill(c)
color c
rect 0,0,graphwidth, graphheight
end subroutine
subroutine setpixel(x,y,c)
color c
plot x,y
end sub... | Give a code snippet in #BASIC256
Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Logical_operations | Logical operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Vala | Vala | public class Program {
private static void print_logic (bool a, bool b) {
print ("a and b is %s\n", (a && b).to_string ());
print ("a or b is %s\n", (a || b).to_string ());
print ("not a %s\n", (!a).to_string ());
}
public static int main (string[] args) {
if (args.length < 3... | Give a code snippet in #Vala
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ECL | ECL |
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ADDit := A + B;
SUBTRACTit := A - B;
MULTIPLYit := A * B;
INTDIVIDEit := A DIV B; //INTEGER DIVISION
DIVIDEit := A / B; //standard division
Remainder := A % B;
EXPit := POWER(A,B);
DS := DATASET([{A,B,'A PLUS B is:',ADDit},
... | Give a code snippet in #ECL
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
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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 mathematics, sexy primes are prime numbers that differ from each ot... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
// TRUE denotes composite, FALSE denotes prime.
c[0] = TRUE;
c[1] = TRUE;
// no need to bother with even ... | Give a code snippet in #C
This page uses content from Wikipedia. The original article was at Sexy_prime. 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 mathematics, sexy primes are prime numbe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Transact-SQL | Transact-SQL | CREATE FUNCTION [dbo].[fn_CheckSEDOL]
( @SEDOL varchar(50) )
RETURNS varchar(7)
AS
BEGIN
declare @true bit = 1,
@false bit = 0,
@isSEDOL bit,
@sedol_weights varchar(6) ='131739',
@sedol_len int = LEN(@SEDOL),
@sum int = 0
if ((@sedol_len = 6))
begin
select @SEDOL = UPPER(@SEDOL)
Declare @vowels ... | Give a code snippet in #Transact-SQL
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #AppleScript | AppleScript | set src to "Hello"
set dst to src | Give a code snippet in #AppleScript
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
E... | 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... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
MODE DATA
$$ SET cardnumbers=*
49927398716
49927398717
1234567812345678
1234567812345670
$$ MODE TUSCRIPT
-> collecting information for output-format
SET length=MAX_LENGTH(cardnumbers)
SET adjust=length+2
LOOP c=cardnumbers
-> ">/" = any digit
SET cstring=STRINGS (c,":>/:")
SET creverse=REVERSE (cstr... | Give a code snippet in #TUSCRIPT
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/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 | #ReScript | ReScript | type document // abstract type for a document object
type context = { mutable fillStyle: string, }
@val external doc: document = "document"
@send external getElementById: (document, string) => Dom.element = "getElementById"
@send external getContext: (Dom.element, string) => context = "getContext"
@send external... | Give a code snippet in #ReScript
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/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #R | R | input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
ii <- ceiling(dims[1]/2)
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="") | Give a code snippet in #R
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Oforth | Oforth | : largestInt map(#asString) sortWith(#[ 2dup + -rot swap + > ]) sum asInteger ; | Give a code snippet in #Oforth
Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #AmigaE | AmigaE | PROC move(n, from, to, via)
IF n > 0
move(n-1, from, via, to)
WriteF('Move disk from pole \d to pole \d\n', from, to)
move(n-1, via, to, from)
ENDIF
ENDPROC
PROC main()
move(4, 1,2,3)
ENDPROC | Give a code snippet in #AmigaE
Task
Solve the Towers of Hanoi problem with recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #AWK | AWK |
$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'
| Give a code snippet in #AWK
Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Arr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #GAP | GAP | run := function()
local a, b, f;
f := InputTextUser();
Print("a =\n");
a := Int(Chomp(ReadLine(f)));
Print("b =\n");
b := Int(Chomp(ReadLine(f)));
Display(Concatenation(String(a), " + ", String(b), " = ", String(a + b)));
Display(Concatenation(String(a), " - ", String(b), " = ", String(a - b)));
Displ... | Give a code snippet in #GAP
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
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #Genie | Genie | [indent=4]
/*
Stack, in Genie, with GLib double ended Queues
valac stack.gs
*/
init
var stack = new Queue of int()
// push
stack.push_tail(2)
stack.push_tail(1)
// pop (and peek at top)
print stack.pop_tail().to_string()
print stack.peek_tail().to_string()
// empty
print ... | Give a code snippet in #Genie
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is ac... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Maple | Maple | for n do
print(n)
end do; | Give a code snippet in #Maple
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations li... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Phix | Phix | procedure print3(sequence a, b, c)
for i=1 to min({length(a),length(b),length(c)}) do
printf(1, "%s%s%g\n", {a[i], b[i], c[i]})
end for
end procedure
print3("abc","ABC",{1, 2, 3})
?columnize({"abc","ABC","1234"},{},' ')
| Give a code snippet in #Phix
Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this examp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newline_omission | Hello world/Newline omission | Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
| #FOCAL | FOCAL | TYPE "Goodbye, World!" | Give a code snippet in #FOCAL
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Stand... | 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
... | #Arturo | Arturo | bogoSort: function [items][
a: new items
while [not? sorted? a]-> shuffle 'a
return a
]
print bogoSort [3 1 2 8 5 7 9 4 6] | Give a code snippet in #Arturo
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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)
... | #make | make | MOD3 = 0
MOD5 = 0
ALL != jot 100
all: say-100
.for NUMBER in $(ALL)
MOD3 != expr \( $(MOD3) + 1 \) % 3; true
MOD5 != expr \( $(MOD5) + 1 \) % 5; true
. if "$(NUMBER)" > 1
PRED != expr $(NUMBER) - 1
say-$(NUMBER): say-$(PRED)
. else
say-$(NUMBER):
. endif
. if "$(MOD3)$(MOD5)" == "00"
@echo FizzBuzz
. elif "$(M... | Give a code snippet in #make
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.... | #Maple | Maple | isSmith := proc(n::posint)
local factors, sumofDigits, sumofFactorDigits, x;
if isprime(n) then
return false;
else
sumofDigits := add(x, x = convert(n, base, 10));
sumofFactorDigits := add(map(x -> op(convert(x, base, 10)), [op(NumberTheory:-PrimeFactors(n))]));
return evalb(sumofDigits = sumofFactorDigi... | Give a code snippet in #Maple
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Maxima | Maxima | /* Maxima allocates memory dynamically and uses a garbage collector.
Here is how to check available memory */
room();
3221/3221 72.3% 2 CONS RATIO COMPLEX STRUCTURE
272/307 61.6% FIXNUM SHORT-FLOAT CHARACTER RANDOM-STATE READTABLE SPICE
226/404 90.8% SYMBOL STREAM
1/2 3... | Give a code snippet in #Maxima
Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #PDP-11_Assembly | PDP-11 Assembly |
; "eight queens problem" benchmark test
.radix 16
.loc 0
nop ;
mov #scr,@#E800
mov #88C6,@#E802
; clear the display RAM
mov #scr,r0
mov #1E0,r1
cls: clr (r0)+
sob r1,cls
; display the initial counter value
... | Give a code snippet in #PDP-11_Assembly
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Wren | Wren | import "/fmt" for Fmt
var isPrime = Fn.new { |n|
if (n < 2) return false
if (n%2 == 0) return n == 2
var p = 3
while (p * p <= n) {
if (n%p == 0) return false
p = p + 2
}
return true
}
var tests = [2, 5, 12, 19, 57, 61, 97]
System.print("Are the following prime?")
for (test i... | Give a code snippet in #Wren
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #Go | Go | package main
// #include <string.h>
// #include <stdlib.h>
import "C"
import (
"fmt"
"unsafe"
)
func main() {
// a go string
go1 := "hello C"
// allocate in C and convert from Go representation to C representation
c1 := C.CString(go1)
// go string can now be garbage collected
go1 = "... | Give a code snippet in #Go
Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be ... | 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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Factor | Factor | USING: kernel math math.matrices prettyprint ;
: sierpinski ( n -- )
1 - { { 1 1 1 } { 1 0 1 } { 1 1 1 } } swap over [ kron ]
curry times [ 1 = "#" " " ? ] matrix-map simple-table. ;
3 sierpinski | Give a code snippet in #Factor
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/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #F.23 | F# |
// Define units of measure
[<Measure>] type k
[<Measure>] type f
[<Measure>] type c
[<Measure>] type r
// Define conversion functions
let kelvinToCelsius (t : float<k>) = ((float t) - 273.15) * 1.0<c>
let kelvinToFahrenheit (t : float<k>) = (((float t) * 1.8) - 459.67) * 1.0<f>
let kelvinToRankine (t : float<k>) = ... | Give a code snippet in #F.23
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 k... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring | Substring |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #VBA | VBA | Public Sub substring()
'(1) starting from n characters in and of m length;
'(2) starting from n characters in, up to the end of the string;
'(3) whole string minus last character;
'(4) starting from a known character within the string and of m length;
'(5) starting from a known substring within the string and of m leng... | Give a code snippet in #VBA
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
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Holidays_related_to_Easter | Holidays related to Easter | Task
Calculate the dates of:
Easter
Ascension Thursday
Pentecost
Trinity Sunday
Corpus Christi feast (for Catholic)
All Saints' Sunday (for Orthodox)
As an example, calculate for the first year of each century from;
years 400 to 2100 CE and for
years 2010 to 2020 CE.
Note
... | #PL.2FI | PL/I | (subscriptrange, size, fofl):
Easter: procedure options (main);
declare months(12) character (9) varying static initial (
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December');
declare (year, month, day) fixe... | Give a code snippet in #PL.2FI
Task
Calculate the dates of:
Easter
Ascension Thursday
Pentecost
Trinity Sunday
Corpus Christi feast (for Catholic)
All Saints' Sunday (for Orthodox)
As an example, calculate for the first year of each century from;
years 400 to 2100 CE and for
yea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Binomial is
function Binomial (N, K : Natural) return Natural is
Result : Natural := 1;
M : Natural;
begin
if N < K then
raise Constraint_Error;
end if;
if K > N/2 then -- Use symmetry
M := N - K;
else
... | Give a code snippet in #Ada
This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Move-to-front_algorithm | Move-to-front algorithm | Given a symbol table of a zero-indexed array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms... | #Go | Go | package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (... | Give a code snippet in #Go
Given a symbol table of a zero-indexed array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, fo... | #REXX | REXX | do j=i for t-i+1; ···
| Give a code snippet in #REXX
The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Sidef | Sidef | var auto = Automaton(30, [1] + 100.of(0));
10.times {
var sum = 0;
8.times {
sum = (2*sum + auto.cells[0]);
auto.next;
};
say sum;
}; | Give a code snippet in #Sidef
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting su... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program radixSort1.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a fil... | Give a code snippet in #ARM_Assembly
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Q... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #zkl | zkl | fcn colorGraph(nodeStr){ // "0-1 1-2 2-0 3"
numEdges,graph := 0,Dictionary(); // ( 0:(1,2), 1:L(0,2), 2:(1,0), 3:() )
foreach n in (nodeStr.split(" ")){ // parse string to graph
n=n - " ";
if(n.holds("-")){
a,b := n.split("-"); // keep as string
graph.appendV(a,b); graph.appendV(b,a);
numEdges... | Give a code snippet in #zkl
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 def... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Arturo | Arturo | cullen: function [n]->
inc n * 2^n
woodall: function [n]->
dec n * 2^n
print ["First 20 cullen numbers:" join.with:" " to [:string] map 1..20 => cullen]
print ["First 20 woodall numbers:" join.with:" " to [:string] map 1..20 => woodall] | Give a code snippet in #Arturo
A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯... | #J | J | require 'stats'
(mean,stddev) 1000 ?@$ 0
0.484669 0.287482
(mean,stddev) 10000 ?@$ 0
0.503642 0.290777
(mean,stddev) 100000 ?@$ 0
0.499677 0.288726 | Give a code snippet in #J
Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #AWK | AWK | BEGIN {
for (l = 0; l <= 2147483647; l++) {
printf("%o\n", l);
}
} | Give a code snippet in #AWK
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #C.2B.2B | C++ | #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir("."); //
boost::regex pattern("a.*"); // list all files starting with a
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
... | Give a code snippet in #C.2B.2B
Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Wa... | 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... | #Nemerle | Nemerle | using System.Console;
using System.Globalization;
module StringCase
{
Main() : void
{
def alpha = "alphaBETA";
WriteLine(alpha.ToUpper());
WriteLine(alpha.ToLower());
WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));
}
} | Give a code snippet in #Nemerle
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/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... | #Kotlin | Kotlin | // version 1.1.4
import java.util.Random
enum class DutchColors { RED, WHITE, BLUE }
fun Array<DutchColors>.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
fun Array<DutchColors>.sort() {
var lo = 0
var mid = 0
var hi = this.lastIndex
while (mid <= hi) ... | Give a code snippet in #Kotlin
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 c... | 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.
| #Crystal | Crystal | def sum_3_5_multiples(n)
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
puts sum_3_5_multiples(1000) | Give a code snippet in #Crystal
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/Fixed_length_records | Fixed length records | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encod... | #C.2B.2B | C++ | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
void reverse(std::istream& in, std::ostream& out) {
constexpr size_t record_length = 80;
char record[record_length];
while (in.read(record, record_length)) {
std::reverse(std::begin(record), std::end(record));
o... | Give a code snippet in #C.2B.2B
Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.JFrame
class Mandelbrot: JFrame("Mandelbrot Set") {
companion object {
private const val MAX_ITER = 570
private const val ZOOM = 150.0
}
private val img: BufferedImage
init {
... | Give a code snippet in #Kotlin
Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #Rust | Rust | let mut x = 0;
loop {
x += 1;
println!("{}", x);
if x % 6 == 0 { break; }
} | Give a code snippet in #Rust
Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Do... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Clio | Clio | fn identity-matrix n:
[0:n] -> * fn i:
[0:n] -> * if = i: 1
else: 0
5 -> identity-matrix -> * print | Give a code snippet in #Clio
Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Julia | Julia | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
for i in 1:100
print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
end
| Give a code snippet in #Julia
Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Compare_length_of_two_strings | Compare length of two strings |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #AutoHotkey | AutoHotkey | list := ["abcd","123456789","abcdef","1234567"]
sorted := []
for i, s in list
sorted[0-StrLen(s), s] := s
for l, obj in sorted
{
i := A_Index
for s, v in obj
{
if (i = 1)
result .= """" s """ has length " 0-l " and is the longest string.`n"
else if (i < sorted.Count())
... | Give a code snippet in #AutoHotkey
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Slate | Slate | #n := 1024.
[n isPositive] whileTrue:
[inform: number printString.
n := n // 2] | Give a code snippet in #Slate
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/Downwar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Off[Power::indet];(*Supress 0^0 warnings*)
Select[Range[5000], Total[IntegerDigits[#]^IntegerDigits[#]] == # &] | Give a code snippet in #Mathematica.2FWolfram_Language
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two ... | #Ring | Ring |
# Project : 2048 Game
load "stdlib.ring"
load "guilib.ring"
C_GAMETITLE = '2048 Game'
C_WINDOWBACKGROUND = "background-color: gray;"
if isMobile()
C_LABELFONTSIZE = "font-size:120px;"
C_BUTTONFONTSIZE = "font-size:160px;"
else
C_LABELFONTSIZE = "font-size:50px;"
C_BUTTONFONTSIZE = "font-size:80px;"
ok
... | Give a code snippet in #Ring
Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some m... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.