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/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...
#Avail
Avail
Assert: 7! = 5040;
Give a code snippet in #Avail 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Blue
Blue
global _start   : syscall ( num:eax -- result:eax ) syscall ;   : exit ( status:edi -- noret ) 60 syscall ; : bye ( -- noret ) 0 exit ;   : write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;   1 const stdout   : print ( buf len -- ) stdout write ;   : newline ( -- ) s" \n" print ; : println ( buf len -- ) print newli...
Give a code snippet in #Blue The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script n...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_staload.hats" // (* ****** ****** *)   fun MakeList ( sep: string ) : void = let // var count: int = 0 // val count = $UNSAFE.cast{ref(int)}(addr@count) // fun MakeItem ( item: string ) : void = let val () = !count := !count+1 in println! (!count, sep, item) end...
Give a code snippet in #ATS In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two n...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Common_Lisp
Common Lisp
(defun dot-product (a b) (apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))
Give a code snippet in #Common_Lisp Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program numberClassif64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "...
Give a code snippet in #AArch64_Assembly These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as...
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.
#HicEst
HicEst
  CHARACTER date="March 7 2009 7:30pm EST", am_pm, result*20   EDIT(Text=date, Parse=cMonth, GetPosition=next) month = 1 + EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', Right=cMonth, Count=',' ) READ(Text=date(next:)) day, year, hour, minute, am_pm hou...
Give a code snippet in #HicEst 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/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#LaTeX
LaTeX
\documentclass{minimal} \usepackage{tikz} \usetikzlibrary{shadings} \begin{document} \begin{tikzpicture} \shade[ball color=black] (0,0) circle (4); \end{tikzpicture} \end{document}
Give a code snippet in #LaTeX Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a De...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Futhark
Futhark
  fun main(as: [n]int, value: int): int = let low = 0 let high = n-1 loop ((low,high)) = while low <= high do -- invariants: value > as[i] for all i < low -- value < as[i] for all i > high let mid = (low+high) / 2 in if as[mid] > value then (low, mid - 1) else if as[mid] ...
Give a code snippet in #Futhark A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Elixir
Elixir
defmodule Subtractive do def new(seed) when seed in 0..999_999_999 do s = Enum.reduce(1..53, [1, seed], fn _,[a,b|_]=acc -> [b-a | acc] end) |> Enum.reverse |> List.to_tuple state = for i <- 1..55, do: elem(s, rem(34*i, 55)) {:ok, _pid} = Agent.start_link(fn -> state end, name: :Subtractiv...
Give a code snippet in #Elixir A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#DCL
DCL
$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" ) $ write sys$output f$fao( "!12*d" )
Give a code snippet in #DCL Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#PicoLisp
PicoLisp
: (pre? "ab" "abcd") -> "abcd" : (pre? "xy" "abcd") -> NIL   : (sub? "bc" "abcd") -> "abcd" : (sub? "xy" "abcd") -> NIL   : (tail (chop "cd") (chop "abcd")) -> ("c" "d") : (tail (chop "xy") (chop "abcd")) -> NIL     (de positions (Pat Str) (setq Pat (chop Pat)) (make (for ((I . L) (chop Str) L (cdr L)) ...
Give a code snippet in #PicoLisp 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#LiveCode
LiveCode
function reverseString S repeat with i = length(S) down to 1 put char i of S after R end repeat return R end reverseString
Give a code snippet in #LiveCode Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Em...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Scala
Scala
def cellularAutomata(s: String) = { def it = Iterator.iterate(s) ( generation => ("_%s_" format generation).iterator sliding 3 map (_ count (_ == '#')) map Map(2 -> "#").withDefaultValue("_") mkString )   (it drop 1) zip it takeWhile Function.tupled(_ != _) map (_._2) foreach println }
Give a code snippet in #Scala Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Vala
Vala
  using Gee;   void main(){ // declare HashMap var map = new HashMap<string, double?>();   // set 3 entries map["pi"] = 3.14; map["e"] = 2.72; map["golden"] = 1.62;   // iter...
Give a code snippet in #Vala Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#zkl
zkl
fcn fairShare(n,b){ // b<=36 n.pump(List,'wrap(n){ n.toString(b).split("").apply("toInt",b).sum(0)%b }) } foreach b in (T(2,3,5,11)){ println("%2d: %s".fmt(b,fairShare(25,b).pump(String,"%2d ".fmt))); }
Give a code snippet in #zkl The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs fo...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Scala
Scala
import org.bouncycastle.crypto.digests.RIPEMD160Digest   object RosettaRIPEMD160 extends App { val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new RIPEMD160Digest()) messageDigest.update(raw, 0, raw.length) val out = Array.fill[Byte](messageDigest.getDigestSize())(0) messageDigest.doFinal(out, ...
Give a code snippet in #Scala RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the AS...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Ursala
Ursala
#import nat   move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC   #show+   main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'>
Give a code snippet in #Ursala Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Perl
Perl
use strict;   sub halve { int((shift) / 2); } sub double { (shift) * 2; } sub iseven { ((shift) & 1) == 0; }   sub ethiopicmult { my ($plier, $plicand, $tutor) = @_; print "ethiopic multiplication of $plier and $plicand\n" if $tutor; my $r = 0; while ($plier >= 1) { $r += $plicand unless iseven($pl...
Give a code snippet in #Perl Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (7) BYTE INITIAL ('..... $'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = ...
Give a code snippet in #PL.2FM Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Modula-2
Modula-2
MODULE AlmostPrime; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE KPrime(n,k : INTEGER) : BOOLEAN; VAR p,f : INTEGER; BEGIN f := 0; p := 2; WHILE (f<k) AND (p*p<=n) DO WHILE n MOD p = 0 DO n := n DIV p; INC(f) EN...
Give a code snippet in #Modula-2 A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PureBasic
PureBasic
Procedure Recur(n) PrintN(str(n)) Recur(n+1) EndProcedure   Recur(1)
Give a code snippet in #PureBasic Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Phix
Phix
- Global variables start with an asterisk '*' - Functions and other global symbols start with a lower case letter - Locally bound symbols start with an upper case letter - Local functions start with an underscore '_' - Classes start with a plus-sign '+', where the first letter - is in lower case for abstract classes...
Give a code snippet in #Phix Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Scala
Scala
import java.awt._ import java.awt.image.BufferedImage   import javax.swing._   object BarnsleyFern extends App {   SwingUtilities.invokeLater(() => new JFrame("Barnsley Fern") {   private class BarnsleyFern extends JPanel { val dim = 640 val img = new BufferedImage(dim, dim, BufferedImage.TY...
Give a code snippet in #Scala A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Maple
Maple
p:=simplify(1-product(1-1/(2*n-k),k=0..n-1)); # p=1/2
Give a code snippet in #Maple The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start o...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func real Power(X, Y); \X raised to the Y power real X, Y; return Exp(Y*Ln(X));   real E, Pi; [Format(4, 16); \places shown before and after . E:= Exp(1.0); RlOut(0, E); CrLf(0); RlOut(0, Ln(E)); CrLf(0);...
Give a code snippet in #XPL0 Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "ma...
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...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "input" for Mouse   var RIGHT = true   class Animation { construct new() { Window.title = "Animation" _fore = Color.white }   init() { _text = "Hello World! " _frame = 0 Canvas.print(_text, 10, 10, _f...
Give a code snippet in #Wren 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 dem...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#J
J
isLeap=: 0 -/@:= 4 100 400 |/ ]
Give a code snippet in #J Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Plain_English
Plain English
\This prints Hello World within the CAL-4700 IDE. \...and backslashes are comments! To run: Start up. Write "Hello World!" to the console. Wait for the escape key. Shut down.
Give a code snippet in #Plain_English Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Sub Main() Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} Dim one As BigInteger = 1 Dim nine As BigInteger = 9   For ii = 2 To 9 Console.WriteLine("First 10 super-{0} numbers:", ii) ...
Give a code snippet in #Visual_Basic_.NET A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Emacs_Lisp
Emacs Lisp
"This is a string."
Give a code snippet in #Emacs_Lisp Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characte...
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Perl
Perl
print <<'HERE'; The 21 game. Each player chooses to add 1, 2, or 3 to a running total. The player whose turn it is when the total reaches 21 wins. Enter q to quit. HERE   my $total = 0;   while () { print "Running total is: $total\n"; my ($me,$comp); while () { print 'What number do you play> '; ...
Give a code snippet in #Perl 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#C.23
C#
using System;   class Program { static void Main(string[] args) { const int from = 1; const int to = 10;   int randomNumber = new Random().Next(from, to); int guessedNumber;   Console.Write("The number is between {0} and {1}. ", from, to); while (true) { ...
Give a code snippet in #C.23 Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hig...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Stata
Stata
while 1 { display "SPAM" }
Give a code snippet in #Stata Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Nim
Nim
  import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))  
Give a code snippet in #Nim Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and prod...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" #! huginn   import Algorithms as algo; import Mathematics as math; import RegularExpressions as re;   make_game( rndGen_ ) { board = ""; for ( i : algo.range( 4 ) ) { board += ( " " + string( character( rndGen_.next() + integer( '1' ) ) ) ); } return ( board.strip(...
Give a code snippet in #Huginn The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four d...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Picat
Picat
go => N = 5, foreach(I in 1..N) foreach(_J in 1..I) print("*") end, nl end.
Give a code snippet in #Picat “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#MMIX
MMIX
A IS 17 B IS 34   pliar IS $255 % designating main registers pliand GREG acc GREG str IS pliar % reuse reg $255 for printing   LOC Data_Segment GREG @ BUF OCTA #3030303030303030 % reserve a buffer that is big enough to hold OCTA #3030303030303030 % a max (signed) 64 bit integer: OCTA #3030300a00000000 % 2^63 ...
Give a code snippet in #MMIX Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#CoffeeScript
CoffeeScript
# Find the n nth-roots of 1 nth_roots_of_unity = (n) -> (complex_unit_vector(2*Math.PI*i/n) for i in [1..n])   complex_unit_vector = (rad) -> new Complex(Math.cos(rad), Math.sin(rad))   class Complex constructor: (@real, @imag) -> toString: -> round_z = (n) -> if Math.abs(n) < 0.00005 then 0 else n ...
Give a code snippet in #CoffeeScript The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Burlesque
Burlesque
607rz2en{J4{J.*2.-2{th}c!**-..%}#R2.-E!n!it}f[2+]{2\/**-.}m[p^
Give a code snippet in #Burlesque Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) )...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Scala
Scala
class Example { def foo(x: Int): Int = 42 + x }   object Main extends App { val example = new Example   val meth = example.getClass.getMethod("foo", classOf[Int])   assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.") println(s"Successfully completed with...
Give a code snippet in #Scala Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Nemerle
Nemerle
def isTerm = System.Console.IsOutputRedirected;
Give a code snippet in #Nemerle Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
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...
#Transd
Transd
#lang transd   class Point : { x: Double(), y: Double(), @init: (λ v Vector<Double>() (= x (get v 0)) (= y (get v 1))), print: (λ (textout "Point(" x "; " y ")\n" )) }   MainModule: { v_: [[1.0, 2.0], [3.0, 4.0]],   _start: (λ // creating an instance of class (with pt Point([5.0, 6.0]) ...
Give a code snippet in #Transd 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/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Perl
Perl
use XML::XPath qw();   my $x = XML::XPath->new('<inventory ... </inventory>');   [$x->findnodes('//item[1]')->get_nodelist]->[0]; print $x->findnodes_as_string('//price'); $x->findnodes('//name')->get_nodelist;
Give a code snippet in #Perl Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #4...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Perl
Perl
  use warnings; use strict;   for my $testcase ( 0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000 ) { my @vlq = vlq_encode($testcase); printf "%8s %12s %8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq); }   sub vlq_encode { my @vlq; my $binary...
Give a code snippet in #Perl Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert t...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Julia
Julia
using Images, FileIO   function main(h::Integer, w::Integer, side::Bool=false) W0 = w >> 1 H0 = h >> 1 @inline function motecolor(x::Integer, y::Integer) h = clamp(180 * (atan2(y - H0, x - W0) / π + 1.0), 0.0, 360.0) return HSV(h, 0.5, 0.5) end   img = zeros(RGB{N0f8}, h, w) img[...
Give a code snippet in #Julia Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initia...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#PicoLisp
PicoLisp
(de commonPath (Lst Chr) (glue Chr (make (apply find (mapcar '((L) (split (chop L) Chr)) Lst) '(@ (or (pass <>) (nil (link (next))))) ) ) ) )
Give a code snippet in #PicoLisp Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as th...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Emacs_Lisp
Emacs Lisp
(let* ((integer-width (* 65536 16)) ; raise bignum limit from 65536 bits to avoid overflow error (answer (number-to-string (expt 5 (expt 4 (expt 3 2))))) (length (length answer))) (message "%s has %d digits" (if (> length 40) (format "%s...%s" (substring answer 0 20) (subst...
Give a code snippet in #Emacs_Lisp Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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   ...
#F.23
F#
open System.IO   let rec getAllFiles dir pattern = seq { yield! Directory.EnumerateFiles(dir, pattern) for d in Directory.EnumerateDirectories(dir) do yield! getAllFiles d pattern }   getAllFiles "c:\\temp" "*.xml" |> Seq.iter (printfn "%s")
Give a code snippet in #F.23 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Vala
Vala
  void main(){ const int from = 1; const int to = 100;   int random = Random.int_range(from, to); int guess = 0;   while (guess != random){ stdout.printf("Guess the target number that's between %d and %d.\n", from, to);   string? num = stdin.read_line (); num.canon("0123456789", '!'); // replaces any charac...
Give a code snippet in #Vala Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hig...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Sidef
Sidef
func bearingAngleDiff(b1, b2) { (var b = ((b2 - b1 + 720) % 360)) > 180 ? (b - 360) : b }   printf("%25s %25s %25s\n", "B1", "B2", "Difference") printf("%25s %25s %25s\n", "-"*20, "-"*20, "-"*20)     for b1,b2 in ([ 20, 45 -45, ...
Give a code snippet in #Sidef Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Common_Lisp
Common Lisp
;;; brownian.lisp ;;; sbcl compile: first load and then (sb-ext:save-lisp-and-die "brownian" :executable t :toplevel #'brownian::main) (ql:quickload "cl-gd")   (defpackage #:brownian (:use #:cl #:cl-gd)) (in-package #:brownian)   (defvar *size* 512) (defparameter bitmap (make-array *size*)) (dotimes (i *size*) (set...
Give a code snippet in #Common_Lisp Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Ada
Ada
-- Version for sqlite with GNATCOLL.SQL_Impl; use GNATCOLL.SQL_Impl; with GNATCOLL.SQL.Exec; use GNATCOLL.SQL.Exec; with GNATCOLL.SQL.Sqlite; use GNATCOLL.SQL;   procedure Prepared_Query is   DB_Descr : Database_Description; Conn  : Database_Connection; Query  : Prepared_Statement; --sqlite does no...
Give a code snippet in #Ada SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don'...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#zkl
zkl
# Pyramid solver # [151] # [ ] [ ] # [ 40] [ ] [ ] # [ ] [ ] [ ] [ ] #[ X ] [ 11] [ Y ] [ 4 ] [ Z ] # Known: X - Y + Z = 0   p:=T( L(151), L(Void,Void), L(40,Void,Void), L(Void,Void,Void,Void), L("X", 11, "Y", 4, "Z") ); addlConstraint:=Dictionary( "X",1, "Y",-1, "Z",1, ...
Give a code snippet in #zkl This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#D
D
void main() /*@safe*/ { import std.array: empty, replace; import std.string: representation, assumeUTF;   // String creation (destruction is usually handled by // the garbage collector). ubyte[] str1;   // String assignments. str1 = "blah".dup.representation; // Hex string, same as "\x00...
Give a code snippet in #D Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#CLU
CLU
fusc = iter () yields (int) q: array[int] := array[int]$[1] yield(0) yield(1)   while true do x: int := array[int]$reml(q) array[int]$addh(q,x) yield(x)   x := x + array[int]$bottom(q) array[int]$addh(q,x) yield(x) end end fusc   longest_fusc = iter ()...
Give a code snippet in #CLU Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition star...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Lingo
Lingo
fp = xtra("fileIO").new() fp.openFile(_movie.path & "input.txt", 1) fileSize = fp.getLength() repeat while TRUE str = fp.readLine() if str.char[1] = numtochar(10) then delete char 1 of str if the last char of str = numtochar(13) then delete the last char of str put str if fp.getPosition()>=fileSize then exit ...
Give a code snippet in #Lingo Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#F.23
F#
  pCache |> Seq.filter(fun n->isPrime((n-1)/2)) |> Seq.take 35 |> Seq.iter (printf "%d ")  
Give a code snippet in #F.23 Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Slate
Slate
se@(SceneElement traits) doWithRestart: block [ block handlingCases: {Abort -> [| :_ | ^ Nil]} ].
Give a code snippet in #Slate Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#GLSL
GLSL
  vec3 a = vec3(3, 4, 5),b = vec3(4, 3, 5),c = vec3(-5, -12, -13);   float dotProduct(vec3 a, vec3 b) { return a.x*b.x+a.y*b.y+a.z*b.z; }   vec3 crossProduct(vec3 a,vec3 b) { vec3 c = vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y- a.y*b.x);   return c; }   float scalarTripleProduct(vec3 a,vec3 b,vec3 c) { retu...
Give a code snippet in #GLSL A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of num...
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 |...
#Raku
Raku
my Int $a = get.floor; my Int $b = get.floor;   say 'sum: ', $a + $b; say 'difference: ', $a - $b; say 'product: ', $a * $b; say 'integer quotient: ', $a div $b; say 'remainder: ', $a % $b; say 'exponentiation: ', $a**$b;
Give a code snippet in #Raku Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Rockstar
Rockstar
  Listen to A number Listen to B Say A number plus B  
Give a code snippet in #Rockstar A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separ...
christopher/rosetta-code
http://rosettacode.org/wiki/War_card_game
War card game
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell Poker hand_analyser Go Fish...
#Lua
Lua
-- main.lua function newGame () -- new deck local deck = {} for iSuit = 1, #CardSuits do for iRank = 1, #CardRanks do local card = { iSuit = iSuit, iRank = iRank, suit = CardSuits[iSuit], rank = iRank, name = CardRanks[iRank] .. CardSuits[iSuit] } local i = math.random (#deck + 1) t...
Give a code snippet in #Lua War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#EchoLisp
EchoLisp
  ;; By decreasing order of performance ;; 1) user definition : lambda and closure   (define (ucompose f g ) (lambda (x) ( f ( g x)))) (ucompose sin cos) → (🔒 λ (_x) (f (g _x)))   ;; 2) built-in compose : lambda   (compose sin cos) → (λ (_#:g1002) (#apply-compose (#list #cos #sin) _#:g1002))   ;; 3) compiled com...
Give a code snippet in #EchoLisp Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   ...
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.
#C.2B.2B
C++
#include <thread> #include <iostream> #include <vector> #include <random> #include <chrono>   int main() { std::random_device rd; std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed. std::uniform_int_distribution<> dist(1,1000); std::vector<std::thread> threads;   for(const auto& str: {"...
Give a code snippet in #C.2B.2B 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn perm(A){ // should verify A is square numRows:=A.rows; Utils.Helpers.permute(numRows.toList()).reduce( // permute(0,1,..numRows) 'wrap(s,pm){ s + numRows.reduce('wrap(x,i){ x*A[i,pm[i]] },1.0) }, 0.0) } test:=fcn(A){ println...
Give a code snippet in #zkl For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Modula-2
Modula-2
MODULE CaesarCipher; FROM Conversions IMPORT IntToStr; FROM Terminal IMPORT WriteString, WriteLn, ReadChar;   TYPE String = ARRAY[0..64] OF CHAR;   PROCEDURE Encrypt(p : String; key : CARDINAL) : String; VAR e : String; VAR i,t : CARDINAL; VAR c : CHAR; BEGIN FOR i:=0 TO HIGH(p) DO IF p[i]=0C THEN BREAK; EN...
Give a code snippet in #Modula-2 Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Pascal
Pascal
program munchhausennumber; {$IFDEF FPC}{$MODE objFPC}{$Optimization,On,all}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; type tdigit = byte; const MAXBASE = 17;   var DgtPotDgt : array[0..MAXBASE-1] of NativeUint; dgtCnt : array[0..MAXBASE-1] of NativeInt; cnt: NativeUint;   function convertToString(n:N...
Give a code snippet in #Pascal Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1...
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 |...
#Groovy
Groovy
def comparison = { a, b -> println "a ? b = ${a} ? ${b} = a ${a < b ? '<' : a > b ? '>' : a == b ? '==' : '?'} b" }
Give a code snippet in #Groovy 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/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#ATS
ATS
#define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)   #include "share/atspre_define.hats" #include "share/atspre_staload.hats"   (********************************************************************) (* *) (* Declarations. ...
Give a code snippet in #ATS Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has b...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#OCaml
OCaml
let left_pos s len = let rec aux i = if i >= len then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (succ i) | _ -> Some i in aux 0   let right_pos s len = let rec aux i = if i < 0 then None else match s.[i] with | ' ' | '\n' | '\t' | '\r' -> aux (pred i) | _ -> So...
Give a code snippet in #OCaml Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace re...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#AWK
AWK
  #!/bin/awk -f function randchar(){ return substr(charset,randint(length(charset)+1),1) } function mutate(gene,rate ,l,newgene){ newgene = "" for (l=1; l < 1+length(gene); l++){ if (rand() < rate) newgene = newgene randchar() else newgene = newgene substr(gene,l,1) } return newgene } function fitness(gene,tar...
Give a code snippet in #AWK Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its a...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Ruby
Ruby
magic_number = 9*8*7 div = 9876432.div(magic_number) * magic_number candidates = div.step(0, -magic_number)   res = candidates.find do |c| digits = c.digits (digits & [0,5]).empty? && digits == digits.uniq end   puts "Largest decimal number is #{res}"
Give a code snippet in #Ruby Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   ...
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...
#RapidQ
RapidQ
DECLARE SUB PaintCanvas   CREATE form AS QForm Width = 640 Height = 480 CREATE canvas AS QCanvas Height = form.ClientHeight Width = form.ClientWidth OnPaint = PaintCanvas END CREATE END CREATE   SUB PaintCanvas ' Fill background canvas.FillRect(0, 0, canvas.Width, canvas.Height, &H...
Give a code snippet in #RapidQ 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Picat
Picat
main => print("Enter an expression: "), Str = read_line(), Exp = parse_term(Str), Res is Exp, printf("Result = %w\n", Res).  
Give a code snippet in #Picat Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a si...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Sidef
Sidef
struct Point {x, y}; var point = Point(1, 2); say point.y; #=> 2
Give a code snippet in #Sidef Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. R...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Emacs_Lisp
Emacs Lisp
(setq my-variable (with-temp-buffer (insert-file-contents "foo.txt") (buffer-string)))
Give a code snippet in #Emacs_Lisp Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Eiffel
Eiffel
  1. 1.23 1e-5 .5 1.23E4  
Give a code snippet in #Eiffel Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF...
christopher/rosetta-code
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#C
C
/* man-or-boy.c */ #include <stdio.h> #include <stdlib.h>   // --- thunks typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG;   // --- lambdas int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; }   // --- helper in...
Give a code snippet in #C Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Lingo
Lingo
on modPow (b, e, m) bits = getBits(e) sq = 1 repeat while TRUE tb = bits[1] bits.deleteAt(1) sq = sq*sq if tb then sq=sq*b sq = sq mod m if bits.count=0 then return sq end repeat end   on getBits (n) bits = [] f = 1 repeat while TRUE bi...
Give a code snippet in #Lingo A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before s...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Kotlin
Kotlin
// version 1.2.10   import java.math.BigInteger import java.math.BigDecimal import java.math.MathContext   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bdZero = BigDecimal.ZERO val context = MathContext.UNLIMITED   fun gcd(a: BigInteger, b: BigInteger): BigInteger = if (b == bigZero) a else gcd(b...
Give a code snippet in #Kotlin An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Prolog
Prolog
  assert( mymap(key1,value1) ). assert( mymap(key2,value1) ).  
Give a code snippet in #Prolog Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Co...
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 ...
#AutoHotkey
AutoHotkey
MsgBox % multiply(10,2)   multiply(multiplicand, multiplier) { Return (multiplicand * multiplier) }
Give a code snippet in #AutoHotkey 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 dist...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Arturo
Arturo
text: "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="   print decode text
Give a code snippet in #Arturo See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output w...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#XPL0
XPL0
code ChOut=8, IntOut=11;   func SelfDesc(N); \Returns 'true' if N is self-describing int N; int Len, \length = number of digits in N I, D; char Digit(10), Count(10);   proc Num2Str(N); \Convert integer N to string in Digit int N; int R; [N:= N/10; ...
Give a code snippet in #XPL0 Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when dig...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Fortran
Fortran
WRITE(...) FIRST,LAST,IF (UNIQUE) THEN "Distinct values only" ELSE "Repeated values allowed" FI // "."
Give a code snippet in #Fortran 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#MAXScript
MAXScript
-- Here deleteFile "input.txt" -- Root deleteFile "\input.txt"
Give a code snippet in #MAXScript Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#C.2B.2B
C++
#include <iostream> #include <cstdlib> if (object == 0) { std::cout << "object is null"; }
Give a code snippet in #C.2B.2B Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lan...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Factor
Factor
42 .  ! 42
Give a code snippet in #Factor
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#SNOBOL4
SNOBOL4
*** GNOME SORT ***************************************************************** * GNOME(V) -- gnome sort of the numerical vector V. *** HELPER FUNCTIONS *********************************************************** * IDXMAX(V) -- highest index of vector V. * IDXMIN(V) -- lowest index of vector V. * NUMBER(V) --...
Give a code snippet in #SNOBOL4 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Wren
Wren
import "random" for Random   var rand = Random.new()   var knuthShuffle = Fn.new { |a| var i = a.count - 1 while (i >= 1) { var j = rand.int(i + 1) var t = a[i] a[i] = a[j] a[j] = t i = i - 1 } }   var tests = [ [], [10], [10, 20], [10, 20, 30] ] for (a in tests) { ...
Give a code snippet in #Wren The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#C.23
C#
using System; using System.Linq;   class Program { static double Horner(double[] coefficients, double variable) { return coefficients.Reverse().Aggregate( (accumulator, coefficient) => accumulator * variable + coefficient); }   static void Main() { Console.WriteLine(H...
Give a code snippet in #C.23 A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   -- MAYAN NUMBERS ------------------------------------------   -- mayanNumber:: Int -> [[String]] on mayanNumber(n) showIntAtBase(20, my mayanDigit, n, {}) end mayanNumber   -- mayanDigit :: Int -> String on mayanDigit(n) if 0 < n...
Give a code snippet in #AppleScript Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Elixir
Elixir
  iex(1)> :crypto.hash(:sha, "A string") <<110, 185, 174, 8, 151, 66, 9, 104, 174, 225, 10, 43, 9, 92, 82, 190, 197, 150, 224, 92>>  
Give a code snippet in #Elixir SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to id...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Sidef
Sidef
func make_list(separator = ') ') {   var count = 1 func make_item(item) { [count++, separator, item].join }   <first second third>.map(make_item).join("\n") }   say make_list('. ')
Give a code snippet in #Sidef In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two...
christopher/rosetta-code
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Phix
Phix
-- demo\rosetta\SQL-based_authentication.exw without js -- (file i/o) include pSQLite.e include md5.exw sqlite3_stmt pAddUser = NULL procedure add_user(sqlite3 db, string name, pw) if pAddUser=NULL then pAddUser = sqlite3_prepare(db,"INSERT INTO users (username,pass_salt,pass_md5) VALUES(:name, :salt, :m...
Give a code snippet in #Phix This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_IN...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#Go
Go
package main   import ( "fmt" "strconv" )   const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" )   var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", }   const ( m0 = " Θ " m5 = "────" )   func dec2vig(n uint64...
Give a code snippet in #Go Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Prolog
Prolog
% Reference: https://en.wikipedia.org/wiki/Lah_number#Identities_and_relations   :- dynamic unsigned_lah_number_cache/3.   unsigned_lah_number(N, N, 1):-!. unsigned_lah_number(_, 0, 0):-!. unsigned_lah_number(N, K, 0):- K > N, !. unsigned_lah_number(N, K, L):- unsigned_lah_number_cache(N, K, L), !. unsigned_lah_num...
Give a code snippet in #Prolog Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly...
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 |...
#Relation
Relation
  program factors(num) relation fact insert 1 set i = 2 while i < num / 2 if num / i = floor(num/i) insert i end if set i = i + 1 end while insert num print end program  
Give a code snippet in #Relation 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Sidef
Sidef
var data = <<'EOF'.lines.map{ <name id salary dept> ~Z .split(',') -> flat.to_h } Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E412...
Give a code snippet in #Sidef Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[memory, MemoryGet, MemorySet, MemorySubtract] memory = {15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0}; MemoryGet[addr_] := memory[[addr + 1]] MemorySet[addr_, value_] := memory[[addr + 1]] = value MemorySubtract[addr1...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory...
christopher/rosetta-code