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/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "stdio.s7i"; include "wrinum.s7i";   const proc: main is func local var integer: number is 0; begin for number range 1 to 999999 do writeln(str(ENGLISH, number)); end for; end func;
Give a code snippet in #Seed7 Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than posi...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Euphoria
Euphoria
include get.e   function val(sequence s) sequence x x = value(s) return x[2] end function   sequence s   s = "12345" s = sprintf("%d",{val(s)+1})
Give a code snippet in #Euphoria Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Ruby
Ruby
include Math   class Integer   def permutation(k) (self-k+1 .. self).inject( :*) end   def combination(k) self.permutation(k) / (1 .. k).inject( :*) end   def big_permutation(k) exp( lgamma_plus(self) - lgamma_plus(self -k)) end   def big_combination(k) exp( lgamma_plus(self) - lgamma_plu...
Give a code snippet in #Ruby This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia....
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Common_Lisp
Common Lisp
;;; Single-file/interactive setup; large applications should define an ASDF system instead   (let* ((display (open-default-display)) (screen (display-default-screen display)) (root-window (screen-root screen)) (black-pixel (screen-black-pixel screen)) (white-pixel (screen-white-pixel screen)...
Give a code snippet in #Common_Lisp Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Conjugate_transpose
Conjugate transpose
Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( M H ) j i = M i j ...
#Factor
Factor
USING: kernel math.functions math.matrices sequences ; IN: rosetta.hermitian   : conj-t ( matrix -- conjugate-transpose ) flip [ [ conjugate ] map ] map ;   : hermitian-matrix? ( matrix -- ? ) dup conj-t = ;   : normal-matrix? ( matrix -- ? ) dup conj-t [ m. ] [ swap m. ] 2bi = ;   : unitary-matrix? ( matri...
Give a code snippet in #Factor Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Excel
Excel
  =ROMAN(2013,0)  
Give a code snippet in #Excel Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a val...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Phix
Phix
with javascript_semantics function additive(string p) return is_prime(sum(sq_sub(p,'0'))) end function sequence res = filter(apply(get_primes_le(500),sprint),additive) printf(1,"%d additive primes found: %s\n",{length(res),join(shorten(res,"",6))})
Give a code snippet in #Phix Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry: ...
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...
#Wren
Wren
import "/fmt" for Fmt   var a a = Fn.new { |k, x1, x2, x3, x4, x5| var b b = Fn.new { k = k - 1 return a.call(k, b, x1, x2, x3, x4) } return (k <= 0) ? x4.call() + x5.call() : b.call() }   System.print(" k a") for (k in 0..20) { Fmt.print("$2d : $ d", k, a.call(k, Fn.new { 1 }, Fn...
Give a code snippet in #Wren 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Program (myprogram.exe) invoke as follows: ' myprogram -c "alpha beta" -h "gamma"   Print "The program was invoked like this => "; Command(0) + " " + Command(-1) Print Print "Press any key to quit" Sleep
Give a code snippet in #FreeBASIC Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Java
Java
  package rosettacode;   import java.util.StringTokenizer;   public class WordWrap { int defaultLineWidth=80; int defaultSpaceWidth=1; void minNumLinesWrap(String text) { minNumLinesWrap(text,defaultLineWidth); } void minNumLinesWrap(String text,int LineWidth) { StringTokeni...
Give a code snippet in #Java 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 provi...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Julia
Julia
using UnicodePlots   spiral(θ, a=0, b=1) = @. b * θ * cos(θ + a), b * θ * sin(θ + a)   x, y = spiral(1:0.1:10) println(lineplot(x, y))
Give a code snippet in #Julia The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Modula-3
Modula-3
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
Give a code snippet in #Modula-3 The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algor...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#11l
11l
F get_prime_factors(=li) I li == 1 R ‘1’ E V res = ‘’ V f = 2 L I li % f == 0 res ‘’= f li /= f I li == 1 L.break res ‘’= ‘ x ’ E f++ R res   L(x) 1..17 print(‘#4: #.’.format(x, get_prime_...
Give a code snippet in #11l Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would b...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#ERRE
ERRE
  PROGRAM DISTRIBUTION   ! ! for rosettacode.org !   ! formulas taken from TI-59 Master Library manual   CONST NUM_ITEM=1000   !VAR SUMX#,SUMX2#,R1#,R2#,Z#,I%   DIM A#[1000]   BEGIN ! seeds random number generator with system time RANDOMIZE(TIMER)   PRINT(CHR$(12);)  !CLS SUMX#=0 SUMX2#=0   FOR I%=1 TO NUM...
Give a code snippet in #ERRE Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related ...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o...
#Haskell
Haskell
{-# LANGUAGE DeriveFunctor #-}   import Control.Comonad import Data.InfList (InfList (..), (+++)) import qualified Data.InfList as Inf   data Cells a = Cells (InfList a) a (InfList a) deriving Functor   view n (Cells l x r) = reverse (Inf.take n l) ++ [x] ++ (Inf.take n r)   fromList [] = fromList [0] fromList (x:x...
Give a code snippet in #Haskell The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#zkl
zkl
"Smiles"[1,*] //-->miles "Smiles"[0,-1] //-->Smile "Smiles"[1,-1] //-->mile
Give a code snippet in #zkl The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#GEORGE
GEORGE
  0 (s) 1, 1000 rep (i) s 1 i dup × / + (s) ; ] P  
Give a code snippet in #GEORGE Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = ...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Common_Lisp
Common Lisp
(defparameter *n* 9516311845790656153499716760847001433441357) (defparameter *e* 65537) (defparameter *d* 5617843187844953170308463622230283376298685)   ;; magic (defun encode-string (message) (parse-integer (reduce #'(lambda (x y) (concatenate 'string x y)) (loop for c across message collect (format nil "~2,'0...
Give a code snippet in #Common_Lisp Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encr...
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...
#Delphi
Delphi
type TFunc<T> = reference to function: T;   function C(x: Integer): TFunc<Integer>; begin Result := function: Integer begin Result := x; end; end;   function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer; var b: TFunc<Integer>; begin b := function: Integer begin Dec(k); Result := ...
Give a code snippet in #Delphi 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#Ring
Ring
load "stdlib.ring" rod = ["|", "/", "-", "\"] for n = 1 to len(rod) see rod[n] + nl sleep(0.25) system("cls") next
Give a code snippet in #Ring Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the p...
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 ...
#PowerShell
PowerShell
Write-Host ([Math]::E) Write-Host ([Math]::Pi) Write-Host ([Math]::Sqrt(2)) Write-Host ([Math]::Log(2)) Write-Host ([Math]::Exp(2)) Write-Host ([Math]::Abs(-2)) Write-Host ([Math]::Floor(3.14)) Write-Host ([Math]::Ceiling(3.14)) Write-Host ([Math]::Pow(2, 3))
Give a code snippet in #PowerShell 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#11l
11l
T Zeckendorf Int dLen dVal = 0   F (x = ‘0’) V q = 1 V i = x.len - 1 .dLen = i I/ 2 L i >= 0 .dVal = .dVal + (x[i].code - ‘0’.code) * q q = q * 2 i = i - 1   F a(n) V i = n L I .dLen < i .dLen = i V j = (.dVal >> (i...
Give a code snippet in #11l This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation ...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#D
D
import std.stdio, std.array;   /** This amb function takes a comparison function and the possibilities that need to be checked.*/ //string[] amb(in bool function(in string, in string) pure comp, const(string)[] amb(in bool function(in string, in string) pure comp, in string[][] options, ...
Give a code snippet in #D Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). ...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#PowerBASIC
PowerBASIC
$matchtext = "Goodbye London!" $repltext = "Hello New York!"   FUNCTION PBMAIN () AS LONG DIM L0 AS INTEGER, filespec AS STRING, linein AS STRING   L0 = 1 WHILE LEN(COMMAND$(L0)) filespec = DIR$(COMMAND$(L0)) WHILE LEN(filespec) OPEN filespec FOR BINARY AS 1 line...
Give a code snippet in #PowerBASIC Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Plain_English
Plain English
true false
Give a code snippet in #Plain_English Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#REXX
REXX
/* REXX ************************************************************** * 15.11.2012 Walter Pachl - my own solution * 16.11.2012 Walter Pachl generalized n prisoners + w killing distance * and s=number of survivors * 09.05.2013 Walter Pachl accept arguments n w s and fix output * ...
Give a code snippet in #REXX Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. hickerson-series.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC . DATA DIVISION. WORKING-STORAGE SECTION. 01 n PIC 99 COMP.   01 h PIC Z(19)9.9(10)....
Give a code snippet in #COBOL The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_constant_0.5772...
Euler's constant 0.5772...
Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ f...
#Sidef
Sidef
# 100 decimals of precision local Num!PREC = 4*100 say Num.EulerGamma
Give a code snippet in #Sidef Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simp...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#COBOL
COBOL
  identification division. program-id. multiple-values.   environment division. configuration section. repository. function multiples function all intrinsic.   REPLACE ==:linked-items:== BY == 01 a usage binary-long. 01 b pic x(10). 01...
Give a code snippet in #COBOL Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Apache_Derby
Apache Derby
CREATE TABLE Address ( addrID INTEGER PRIMARY KEY generated BY DEFAULT AS IDENTITY, addrStreet VARCHAR(50) NOT NULL, addrCity VARCHAR(50) NOT NULL, addrState CHAR(2) NOT NULL, addrZip CHAR(10) NOT NULL );  
Give a code snippet in #Apache_Derby Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the s...
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...
#jq
jq
$ jq -n '"Hello", if 1 then error else 2 end' "Hello"
Give a code snippet in #jq 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/de...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Lasso
Lasso
define odd_word_processor(str::string) => { local( isodd = false, pos = 1, invpos = 1, lastpos = 1 ) while(#str->get(#pos) != '.' && #pos <= #str->size) => { if(not #str->isAlpha(#pos)) => { not #isodd ? #isodd = true | #isodd = false } if(#isodd) => { #lastpos = 1 #invpos = 1 while...
Give a code snippet in #Lasso Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only on...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Scheme
Scheme
  (import (scheme base) (scheme write))   ;; convert number to a list of digits, in desired base (define (number->list n base) (let loop ((res '()) (num n)) (if (< num base) (cons num res) (loop (cons (remainder num base) res) (quotient num base)))))   ;; return the ...
Give a code snippet in #Scheme Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2   R FUNCTION TO CALC POP COUNT INTERNAL FUNCTION(N) ENTRY TO POPCNT. RSLT = 0 PCTNUM = N LOOP PCTNXT = PCTNUM/2 RSLT = RSLT + PCTNUM-PCTNXT*2 ...
Give a code snippet in #MAD Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Common_Lisp
Common Lisp
(deftype one-to-ten () '(integer 1 10))
Give a code snippet in #Common_Lisp Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#J
J
require'general/misc/prompt'   genboard=:3 :0 b=. ?~16 if. 0<C.!.2 b do. b=. (<0 _1)C. b end. a: (b i.0)} <"0 b )   done=: (<"0]1+i.15),a:   shift=: |.!._"0 2 taxi=: |:,/"2(_1 1 shift i.4 4),_1 1 shift"0 1/ i.4 4   showboard=:3 :0 echo 'current board:' echo 4 4$y )   help=:0 :0   Slide a number block ...
Give a code snippet in #J Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#RapidQ
RapidQ
SUBI printAll (...) FOR i = 1 TO ParamValCount PRINT ParamVal(i) NEXT i FOR i = 1 TO ParamStrCount PRINT ParamStr$(i) NEXT i END SUBI   printAll 4, 3, 5, 6, 4, 3 printAll 4, 3, 5 printAll "Rosetta", "Code", "Is", "Awesome!"
Give a code snippet in #RapidQ Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. ...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#REXX
REXX
/*REXX program displays (draws) a pixel at a specified screen location in the color red.*/ parse upper version !ver . !pcrexx= 'REXX/PERSONAL'==!ver | 'REXX/PC'==!ver /*obtain the REXX interpreter version. */ parse arg x y txt CC . /*obtain optional arguments from the CL*/ if x=='' | x==","...
Give a code snippet in #REXX 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/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Ada
Ada
# -*- coding: utf-8 -*- # COMMENT REQUIRES: MODE VALUE = ~; # For example: # MODE VALUE = UNION(INT, REAL, COMPL) END COMMENT   MODE LINKNEW = STRUCT ( LINK next, prev, VALUE value );   MODE LINK = REF LINKNEW;   SKIP
Give a code snippet in #Ada Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#ALGOL_W
ALGOL W
begin  % simple list type  % record IntList( integer val; reference(IntList) next );    % find the maximum element of an IntList, returns 0 for an empty list  % integer procedure maxElement( reference(IntList) value list ) ; begin ...
Give a code snippet in #ALGOL_W Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Stata
Stata
clear all set obs 10 gen x=_n ameans x   Variable | Type Obs Mean [95% Conf. Interval] -------------+--------------------------------------------------------------- x | Arithmetic 10 5.5 3.334149 7.665851 | Geometric 10 4....
Give a code snippet in #Stata Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldo...
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...
#Scala
Scala
import java.awt.Graphics import java.awt.image.BufferedImage   import javax.swing.JFrame   import scala.collection.mutable.ListBuffer   object BrownianTree extends App { val rand = scala.util.Random   class BrownianTree extends JFrame("Brownian Tree") with Runnable { setBounds(100, 100, 400, 300) val img = ...
Give a code snippet in #Scala 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/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#QBasic
QBasic
SUB perms (n) DIM a(0 TO n - 1), c(0 TO n - 1)   FOR j = 0 TO n - 1 a(j) = j + 1 PRINT a(j); NEXT j PRINT   i = 0 WHILE i < n IF c(i) < i THEN IF (i AND 1) = 0 THEN SWAP a(0), a(i) ELSE SWAP a(c(i)), a(i) ...
Give a code snippet in #QBasic Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Axiom
Axiom
expr := x^3-3*x^2+2*x solve(expr,x)
Give a code snippet in #Axiom Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Julia
Julia
  function countunicode() englishlettercodes = [Int(c) for c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] count = 0 az = "" AZ = "" for i in 0:0xffffff if is_assigned_char(i) count += 1 end if i in englishlettercodes c = Char(i) ...
Give a code snippet in #Julia Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Wren
Wren
$ ./wren \\/"- \_/ wren v0.2.0 > var f = Fn.new { |s1, s2, sep| s1 + sep + sep + s2 } > f.call("Rosetta", "Code", ":") Rosetta::Code > ^C $
Give a code snippet in #Wren Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#REXX
REXX
/*REXX program converts CSV ───► HTML table representing the CSV data. */ arg header_ . /*obtain an uppercase version of args. */ wantsHdr= (header_=='HEADER') /*is the arg (low/upp/mix case)=HEADER?*/ ...
Give a code snippet in #REXX Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Swift
Swift
import Foundation   precedencegroup ExponentiationGroup { higherThan: MultiplicationPrecedence }   infix operator ** : ExponentiationGroup infix operator ±   func ±(_ lhs: Double, _ rhs: Double) -> UncertainDouble { UncertainDouble(value: lhs, error: rhs) }   struct UncertainDouble { var value: Double var error: ...
Give a code snippet in #Swift If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then  ...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#PHP
PHP
<?php $data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects $data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays   $sample = array( "blue" => array(1,2), "ocean" => "water" ); $json_string = json_encode($sample); ...
Give a code snippet in #PHP Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#PicoLisp
PicoLisp
: (setq A (1 2 3) B '(a b c)) -> (a b c) : (conc A B) # Concatenate lists in 'A' and 'B' -> (1 2 3 a b c) : A -> (1 2 3 a b c) # Side effect: List in 'A' is modified!
Give a code snippet in #PicoLisp Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/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) ...
#EasyLang
EasyLang
color 060 for i range 200000 r = randomf if r < 0.01 nx = 0 ny = 0.16 * y elif r < 0.08 nx = 0.2 * x - 0.26 * y ny = 0.23 * x + 0.22 * y + 1.6 elif r < 0.15 nx = -0.15 * x + 0.28 * y ny = 0.26 * x + 0.24 * y + 0.44 else nx = 0.85 * x + 0.04 * y ny = -0.04 * x + 0.85 * y + 1.6 ...
Give a code snippet in #EasyLang 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 y...
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.
#LSL
LSL
integer iLimit_of_Recursion = 0; Find_Limit_of_Recursion(integer x) { llOwnerSay("x="+(string)x); iLimit_of_Recursion = x; Find_Limit_of_Recursion(x+1); } default { state_entry() { Find_Limit_of_Recursion(0); llOwnerSay("iLimit_of_Recursion="+(string)iLimit_of_Recursion); } }  
Give a code snippet in #LSL 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/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* Generate open/close events. *) gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten]   (* Check balance. *) check[lst_] := And @@ (# >= 0 & /@ Accumulate[lst])   (* Do task for string with n opening and n closing brackets. *) doString[n_] := ( lst = gen[n]; str = StringJoin[lst /. {1 -> "[", -1 -> "]"}]; Pri...
Give a code snippet in #Mathematica.2FWolfram_Language Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that or...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#VBA
VBA
Public stateBSD As Variant Public stateMS As Variant Private Function bsd() As Long Dim temp As Variant temp = CDec(1103515245 * stateBSD + 12345) temp2 = temp / 2 ^ 31 temp3 = CDec(WorksheetFunction.Floor_Precise(temp2)) stateBSD = temp - (2 ^ 31) * temp3 bsd = stateBSD End Function Private Fun...
Give a code snippet in #VBA The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   typedef int (^Func)(int); typedef Func (^FuncFunc)(Func); typedef Func (^RecursiveFunc)(id); // hide recursive typing behind dynamic typing   Func Y(FuncFunc f) { RecursiveFunc r = ^(id y) { RecursiveFunc w = y; // cast value back into desired type return f(^(int x) { ...
Give a code snippet in #Objective-C In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state o...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Swift
Swift
struct CUSIP { var value: String   private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")   init?(value: String) { if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) { self.value = value } else if value.count == 8, let checkDigit = CUSIP....
Give a code snippet in #Swift This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Ada
Ada
with Ada.Text_IO;   procedure Main is function Levenshtein_Distance (S, T : String) return Natural is D : array (0 .. S'Length, 0 .. T'Length) of Natural; begin for I in D'Range (1) loop D (I, 0) := I; end loop; for I in D'Range (2) loop D (0, I) := I; end loop; ...
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and compu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PHP
PHP
<?php //Sort strings $x = 'lions, tigers, and'; $y = 'bears, oh my!'; $z = '(from the "Wizard of OZ")'; $items = [$x, $y, $z]; sort($items);   list($x, $y, $z) = $items;   echo <<<EOT Case 1: x = $x y = $y z = $z   EOT;   //Sort numbers $x = 77444; $y = -12; $z = 0; $items = [$x, $y, $z]; sort($items);   list($x,...
Give a code snippet in #PHP Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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. ...
#Wren
Wren
for (i in 1..5) { for (j in 1..i) System.write("*") System.print() }
Give a code snippet in #Wren “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 structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Sidef
Sidef
func randN (n) { n.rand / (n-1) -> int }   func unbiased(n) { var n1 = nil do { n1 = randN(n) } while (n1 == randN(n)) return n1 }   var iterations = 1000   for n in (3..6) { var raw = [] var fixed = [] iterations.times { raw[ randN(n) ] := 0 ++ fixed[ unbiased(n) ] := 0...
Give a code snippet in #Sidef P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York" - , "US Boston", "US Washington" - , "UK Washington", "US Birmingham" - , "UK Birmingham", "UK Boston" - ] sortedList = cocktailSort(String[] Arrays.copy...
Give a code snippet in #NetRexx 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/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#C
C
#include <stdio.h>     int main() { int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};   // There is a bug: "XL\0" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long... // Should be "XL" without \0 etc. // char roman[13][3] = {"M\0", "CM\0", "D\0", "CD\0", "C\0", "X...
Give a code snippet in #C Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value o...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#C.23
C#
using System;   class Program { public static void Main(string[] args) { Func<double, double> f = x => { return x * x * x - 3 * x * x + 2 * x; };   double step = 0.001; // Smaller step values produce more accurate and precise results double start = -1; double stop = 3; do...
Give a code snippet in #C.23 Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Modula-3
Modula-3
GENERIC INTERFACE Matrix(RingElem);   (* "RingElem" must export the following: - a type T; - procedures + "Nonzero(a: T): BOOLEAN", which indicates whether "a" is nonzero; + "Minus(a, b: T): T" and "Times(a, b: T): T", which return the results you'd guess from the procedures' names; and + "Print(a: T)", which...
Give a code snippet in #Modula-3 Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Ada
Ada
with ada.text_io;use ada.text_io;   procedure perfect_shuffle is function count_shuffle (half_size : Positive) return Positive is subtype index is Natural range 0..2 * half_size - 1; subtype index_that_move is index range index'first+1..index'last-1; type deck is array (index) of index; initial, d, ne...
Give a code snippet in #Ada A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#UNIX_Shell
UNIX Shell
# any valid variable name can be used as a queue without initialization   queue_empty foo && echo foo is empty || echo foo is not empty   queue_push foo bar queue_push foo baz queue_push foo "element with spaces"   queue_empty foo && echo foo is empty || echo foo is not empty   print "peek: $(queue_peek foo)"; queue_po...
Give a code snippet in #UNIX_Shell 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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations o...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#R
R
  # provided by neonira   integerToText <- function(value_n_1) { english_words_for_numbers <- list( simples = c( 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ...
Give a code snippet in #R Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of chara...
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...
#Nim
Nim
import intsets, strutils, times   proc mianchowla(n: Positive): seq[int] = result = @[1] var sums = [2].toIntSet() var candidate = 1   while result.len < n: # Test successive candidates. var fit = false result.add 0 # Make room for next value. while not fit: inc candidate fit = tr...
Give a code snippet in #Nim 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/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#C
C
#include <stdio.h>   #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE];   void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } }   void horizontal(size_t c1, size_t c2, size_t r) { ...
Give a code snippet in #C Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represen...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace RosettaVectors { public class Vector { public double[] store; public Vector(IEnumerable<double> init) { store = init.ToArray(); } public Vector(double x, double y) { ...
Give a code snippet in #C.23 Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (le...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Elixir
Elixir
defmodule Gamma do @a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_9509...
Give a code snippet in #Elixir Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#PARI.2FGP
PARI/GP
isNarcissistic(n)=my(v=digits(n)); sum(i=1, #v, v[i]^#v)==n v=List();for(n=1,1e9,if(isNarcissistic(n),listput(v,n);if(#v>24, return(Vec(v)))))
Give a code snippet in #PARI.2FGP A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyl...
christopher/rosetta-code
http://rosettacode.org/wiki/Intersecting_number_wheels
Intersecting number wheels
A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"...
#REXX
REXX
/*REXX program expresses numbers from intersecting number wheels (or wheel sets). */ @.= /*initialize array to hold the wheels. */ parse arg lim @.1 /*obtain optional arguments from the CL*/ if lim='' | lim="," then lim= 20 ...
Give a code snippet in #REXX A number wheel has: A name which is an uppercase letter. A set of ordered values which are either numbers or names. A number is generated/yielded from a named wheel by: 1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Ruby
Ruby
require "test/unit/assertions" include Test::Unit::Assertions   n = 5 begin assert_equal(42, n) rescue Exception => e # Ruby 1.8: e is a Test::Unit::AssertionFailedError # Ruby 1.9: e is a MiniTest::Assertion puts e end
Give a code snippet in #Ruby Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#Lua
Lua
function deconvolve(f, g) local h = setmetatable({}, {__index = function(self, n) if n == 1 then self[1] = g[1] / f[1] else self[n] = g[n] for i = 1, n - 1 do self[n] = self[n] - self[i] * (f[n - i + 1] or 0) end self[n] = self[n] / f[1] end ret...
Give a code snippet in #Lua The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#D
D
import std.stdio, std.algorithm, std.random, std.range;   void main() { foreach (immutable i; 1 .. 9) { immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s); } }
Give a code snippet in #D Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest....
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...
#OxygenBasic
OxygenBasic
    Class MyObject   static int count 'statics are private   int a,b,c bstring s   method constructor(int pa,pb,pc) s="constructed" a=pa : b=pb : c=pc count++ end method   method destructor() del s end method   method sum() as int return a+b+c end method   end class   new MyObject v(2,4,6)   print "Sum: " v.s...
Give a code snippet in #OxygenBasic 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Python
Python
def ack1(M, N): return (N + 1) if M == 0 else ( ack1(M-1, 1) if N == 0 else ack1(M-1, ack1(M, N-1)))
Give a code snippet in #Python The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#x86_Assembly
x86 Assembly
  ; Accumulator factory ; Returns a function that returns the sum of all numbers ever passed in ; Build: ; nasm -felf32 af.asm ; ld -m elf32_i386 af.o -o af   global _start section .text   _start: mov eax, 0x2D ; sys_brk(unsigned long brk) xor ebx, ebx ; Returns current break on an error i...
Give a code snippet in #x86_Assembly A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric val...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Java
Java
    --------------------------------- START of Main.java --------------------------------- //By xykmz. Enjoy!   import java.util.Scanner;   public class Main {   static int intErrorTrap (int x, int y){   int max, min;   if (x < y) { min = x; max = y; } else { ...
Give a code snippet in #Java There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordi...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Haskell
Haskell
import System.IO import System.Directory   main = do renameFile "input.txt" "output.txt" renameDirectory "docs" "mydocs" renameFile "/input.txt" "/output.txt" renameDirectory "/docs" "/mydocs"
Give a code snippet in #Haskell Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#JavaScript
JavaScript
function createRow(i, point, heading) { var tr = document.createElement('tr'), td;   td = document.createElement('td'); td.appendChild(document.createTextNode(i)); tr.appendChild(td);   td = document.createElement('td'); point = point.substr(0, 1).toUpperCase() + point.substr(1); td....
Give a code snippet in #JavaScript There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print a...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Oz
Oz
declare %% Helper function fun {ReadLines Filename} File = {New class $ from Open.file Open.text end init(name:Filename)} in for collect:C break:B do case {File getS($)} of false then {File close} {B} [] Line then {C Line} end end end   %% Groups anagrams by using a mutable dictionary...
Give a code snippet in #Oz When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them...
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)
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() For Each y In {1900, 1994, 1996, Date.Now.Year} Console.WriteLine("{0} is {1}a leap year.", y, If(Date.IsLeapYear(y), String.Empty, "not ")) Next End Sub   End Module
Give a code snippet in #Visual_Basic_.NET 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/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 ...
#VBA
VBA
    'pancake sort 'uses two auxiliary routines "printarray" and "flip" Public Sub printarray(A) For i = LBound(A) To UBound(A) Debug.Print A(i), Next Debug.Print End Sub   Public Sub Flip(ByRef A, p1, p2, trace) 'flip first elements of A (p1 to p2) If trace Then Debug.Print "we'll flip the first "; p2 - p1 ...
Give a code snippet in #VBA Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Delphi
Delphi
- Read(F,V1..Vn) - ReadLn(F,V1..Vn) - Write(F,V1[,V2..Vn]) - WriteLn(f,V1[,V2..Vn]) - BlockRead(F,Buff,BytesToRead[,BytesRead]) - BlockWrite(F,Buff,BytesToRead[,BytesWritten])
Give a code snippet in #Delphi File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
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
#Lua
Lua
require ("math")   shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}   function normalize (vec) len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2) return {vec[1]/len, vec[2]/len, vec[3]/len} end   light = normalize{30, 30, -50}   function dot (vec1, vec2) d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[...
Give a code snippet in #Lua 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 Deat...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#ALGOL_68
ALGOL 68
print( ( 0 ^ 0, newline ) )  
Give a code snippet in #ALGOL_68 Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     ...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#BASIC
BASIC
10 DEFINT P,N,I,S 20 PRINT "First 20 Harshad numbers:" 30 P=0 40 N=0 50 N=N+1 60 S=0 70 I=N 80 S=S+I MOD 10 90 I=I\10 100 IF I THEN 80 110 IF N MOD S THEN 50 120 IF P<20 THEN P=P+1: PRINT N, 130 IF N<=1000 THEN 50 140 PRINT 150 PRINT "First Harshad number > 1000:";N
Give a code snippet in #BASIC The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Julia
Julia
  fs(f, s) = map(f, s) f1(x) = 2x f2(x) = x^2 fsf1(s) = fs(f1, s) fsf2(s) = fs(f2, s)   s1 = [0, 1, 2 ,3] s2 = [2, 4, 6, 8] println("fsf1 of s1 is $(fsf1(s1))") println("fsf2 of s1 is $(fsf2(s1))") println("fsf1 of s2 is $(fsf1(s2))") println("fsf2 of s2 is $(fsf2(s2))")  
Give a code snippet in #Julia Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have...
#Kotlin
Kotlin
// version 1.2.10   class FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {   var coverage = coverage set(value) { if (field != value) { field = value // update any parent's coverage if (parent != null) parent!!.updateCoverage() ...
Give a code snippet in #Kotlin Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Eiffel
Eiffel
class POINT inherit ANY redefine out end create make, make_origin   feature -- Initialization   make (a_x, a_y: INTEGER) -- Create with values `a_x' and `a_y' do set_x (a_x) set_y (a_y) ensure x_set: x = a_x ...
Give a code snippet in #Eiffel Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#SystemVerilog
SystemVerilog
    package math_pkg; // Inspired by the post // https://community.cadence.com/cadence_blogs_8/b/fv/posts/create-a-sine-wave-generator-using-systemverilog // import functions directly from C library //import dpi task C Name = SV function name import "DPI" pure function real cos (input real rTheta); imp...
Give a code snippet in #SystemVerilog Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be t...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#PowerShell
PowerShell
function Get-GCD ($x, $y) { if ($x -eq $y) { return $y } if ($x -gt $y) { $a = $x $b = $y } else { $a = $y $b = $x } while ($a % $b -ne 0) { $tmp = $a % $b $a = $b $b = $tmp } return $b }
Give a code snippet in #PowerShell Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   gre...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Factor
Factor
USING: checksums checksums.ripemd checksums.sha io.binary kernel math sequences ; IN: rosetta-code.bitcoin.point-address   CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"   : btc-checksum ( bytes -- checksum-bytes ) 2 [ sha-256 checksum-bytes ] times 4 head ;   : bigint>base58 ( n --...
Give a code snippet in #Factor Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in o...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#zkl
zkl
fname,count := vm.arglist; // grab cammand line args   // words may have leading or trailing "_", ie "the" and "_the" File(fname).pump(Void,"toLower", // read the file line by line and hash words RegExp("[a-z]+").pump.fp1(Dictionary().incV)) // line-->(word:count,..) .toList().copy().sort(fcn(a,b){ b[1]<a[1] })...
Give a code snippet in #zkl Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Ursala
Ursala
#import nat #import flo   nth_non_square = float; plus^/~& math..trunc+ plus/0.5+ sqrt is_square = sqrt; ^E/~& math..trunc   #show+   examples = %neALP ^(~&,nth_non_square)*t iota23 check = (is_square*~+nth_non_square*t; ~&i&& %eLP)||-[no squares found]-! iota 1000000
Give a code snippet in #Ursala Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A0000...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Run_BASIC
Run BASIC
string$ = "12345" numeric = val(string$) numeric = numeric + 1 string$ = str$(numeric) print string$  
Give a code snippet in #Run_BASIC Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 ...
#Prolog
Prolog
patience_sort(UnSorted,Sorted) :- make_piles(UnSorted,[],Piled), merge_piles(Piled,[],Sorted).   make_piles([],P,P). make_piles([N|T],[],R) :- make_piles(T,[[N]],R). make_piles([N|T],[[P|Pnt]|Tp],R) :- N =< P, make_piles(T,[[N,P|Pnt]|Tp],R). make_piles([N|T],[[P|Pnt]|Tp],R) :- N > P, make_piles(T,[[N],[P|Pnt]|Tp...
Give a code snippet in #Prolog 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/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Quackery
Quackery
[ dup 400 mod 0 = iff [ drop true ] done dup 100 mod 0 = iff [ drop false ] done 4 mod 0 = ] is leap? ( n --> b )
Give a code snippet in #Quackery Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code