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/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Haskell
Haskell
import Data.List (isInfixOf) import Numeric (showHex) import Data.Char (isDigit)   data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) | IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] | IPv4WithPort IPChunk String | IPv4NoPort IPChunk | IPInvalid | IPZeroSection | IPUndefinedWithPort String |...
Give a code snippet in #Haskell The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Shen
Shen
(tc +)   (datatype subtype (subtype B A); X : B; _____________________ X : A;)   (datatype integer if (integer? X) ___________ X: integer;   ________________________ (subtype integer number);)   (datatype bit if (< X 2) _______ X: bit;   _____________________ (subtype bit integer);)   (datatyp...
Give a code snippet in #Shen The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#BASIC
BASIC
DECLARE SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER)   CLS triangle 1, 1, 16, 5   SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER) IF n = 0 THEN LOCATE y, x: PRINT "*"; ELSE triangle x, y + length, length / 2, n - 1 triangle x + len...
Give a code snippet in #BASIC Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
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...
#AWK
AWK
$ awk 'BEGIN{system("mv input.txt output.txt")}' $ awk 'BEGIN{system("mv docs mydocs")}' $ awk 'BEGIN{system("mv /input.txt /output.txt")}' $ awk 'BEGIN{system("mv docs mydocs")}'
Give a code snippet in #AWK 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 righ...
christopher/rosetta-code
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Go
Go
package main   import ( "fmt" "rcu" )   func motzkin(n int) []int { m := make([]int, n+1) m[0] = 1 m[1] = 1 for i := 2; i <= n; i++ { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } return m }   func main() { fmt.Println(" n M[n] Prime?") fmt.Pri...
Give a code snippet in #Go Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers o...
christopher/rosetta-code
http://rosettacode.org/wiki/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#Batch_File
Batch File
@echo off  :main cls echo Drag a .wav file there and press enter set /p file1= sndrec32 /embedding /play /close %file1% cls echo Drag a second .wav file and both will play together set /p file2= sndrec32 /embedding /play /close %file1% | sndrec32 /embedding /play /close %file2% echo Thanks pause>nul exit
Give a code snippet in #Batch_File Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing perfor...
christopher/rosetta-code
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#R
R
  #to install hilbercurve library, biocmanager needs to be installed first install.packages("BiocManager") BiocManager::install("HilbertCurve") #loading library and setting seed for random numbers library(HilbertCurve) library(circlize) set.seed(123)   #4th order peano curve is generated for(i in 1:512) { peano =...
Give a code snippet in #R Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#PL.2FI
PL/I
loops:procedure options (main); declare i fixed binary;   put skip list ('-2 to 2 by 1:'); do i = -2 to 2 by 1; put edit (i) (f(3)); end; put skip list ('-2 to 2 by 0: infinite loop, prints -2');   put skip list ('-2 to 2 by -1: [no values printed]'); do i = -2 to 2 by -1; put edit (i...
Give a code snippet in #PL.2FI Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is t...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
set1 = {"a", "b", "c", "d", "e"}; set2 = {"a", "b", "c", "d", "e", "f", "g"}; MemberQ[set1, "a"] Union[set1 , set2] Intersection[set1 , set2] Complement[set2, set1](*Set Difference*) MemberQ[Subsets[set2], set1](*Subset*) set1 == set2(*Equality*) set1 == set1(*Equality*)
Give a code snippet in #Mathematica.2FWolfram_Language Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of thes...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#D
D
void main() { import std.stdio, std.complex;   for (real y = -1.2; y < 1.2; y += 0.05) { for (real x = -2.05; x < 0.55; x += 0.03) { auto z = 0.complex; foreach (_; 0 .. 100) z = z ^^ 2 + complex(x, y); write(z.abs < 2 ? '#' : '.'); } w...
Give a code snippet in #D Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Go
Go
package main   import ( "regexp" "strings" "testing" )   var lengthByCountryCode = map[string]int{ "AL": 28, "AD": 24, "AT": 20, "AZ": 28, "BE": 16, "BH": 22, "BA": 20, "BR": 29, "BG": 22, "CR": 21, "HR": 21, "CY": 28, "CZ": 24, "DK": 18, "DO": 28, "EE": 20, "FO": 18, "FI": 18, "FR": 27, "GE": 22, "DE": 22, "GI"...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)  ...
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 |...
#Eiffel
Eiffel
class MAIN creation make feature make is local a, b: REAL; do print("a = "); io.read_real; a := io.last_real;   print("b = "); io.read_real; b := io.last_real;   print("a + b = "); io.put_...
Give a code snippet in #Eiffel 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/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#zkl
zkl
fcn norm2{ // Box-Muller const PI2=(0.0).pi*2;; rnd:=(0.0).random.fp(1); // random number in [0,1), using partial application r,a:=(-2.0*rnd().log()).sqrt(), PI2*rnd(); return(r*a.cos(), r*a.sin()); // z0,z1 } const N=100000, BINS=12, SIG=3, SCALE=500; var sum=0.0,sumSq=0.0, h=BINS.pump(List(),0); // (0...
Give a code snippet in #zkl The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random n...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#EchoLisp
EchoLisp
  (lib 'list) ;; in-permutations (lib 'bigint)   ;; generates derangements by filtering out permutations (define (derangement? nums) ;; predicate (for/and ((n nums) (i (length nums))) (!= n i)))   (define (derangements n) (for/list ((p (in-permutations n))) #:when (derangement? p) p))   (define (count-derangeme...
Give a code snippet in #EchoLisp A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial ...
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.   ...
#11l
11l
F is_prime(a) I a == 2 R 1B I a < 2 | a % 2 == 0 R 0B L(i) (3 .. Int(sqrt(a))).step(2) I a % i == 0 R 0B R 1B   F digit_sum(=n) V sum = 0 L n > 0 sum += n % 10 n I/= 10 R sum   V additive_primes = 0 L(i) 2..499 I is_prime(i) & is_prime(digit_sum(i)) a...
Give a code snippet in #11l 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/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...
#Raven
Raven
define gcd use $u, $v $v 0 > if $u $v % $v gcd else $u abs   24140 40902 gcd
Give a code snippet in #Raven 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Fortran
Fortran
program Example implicit none   integer :: num character(32) :: str   str = "0123459" read(str, "(i10)") num ! Decimal write(*,*) num ! Prints 123459   str = "abcf123" read(str, "(z8)") num ! Hexadecimal write(*,*) num ! Prints 180154659   str = "7651" read(str, "(o11)"...
Give a code snippet in #Fortran It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing o...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#11l
11l
print(Float.infinity)
Give a code snippet in #11l Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, r...
christopher/rosetta-code
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[EqualRisesAndFallsQ] EqualRisesAndFallsQ[n_Integer] := Total[Sign[Differences[IntegerDigits[n]]]] == 0 Take[Select[Range[1000], EqualRisesAndFallsQ], 200] valid = 0; Dynamic[{i, valid}] Do[ If[EqualRisesAndFallsQ[i], valid += 1; If[valid == 10^7, Print[i]; Break[]] ] , {i, 50 10^6} ]
Give a code snippet in #Mathematica.2FWolfram_Language When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Python
Python
from math import pi, exp r = exp(pi)-pi print r print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r) print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r) print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r) print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r) print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r) print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)...
Give a code snippet in #Python Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
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...
#Bracmat
Bracmat
( ( odd-word = dothis doother forward backward . ( forward = ch . fil$:?ch & put$!ch & ( low$!ch:~<a:~>z&forward$ | !ch:~"." ) ) & ( backward = ch . fil$:?ch & ( low$!ch:~<a:~>z ...
Give a code snippet in #Bracmat 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 ...
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...
#6502_Assembly
6502 Assembly
JSEPHS: STA $D0  ; n STX $D1  ; k LDA #$FF LDX #$00 SETUP: STA $1000,X  ; populate array with hex FF INX CPX $D0 BEQ KILL JMP SETUP KILL: LDA #$00  ; number killed so far STA $D2 LDX #$00  ; position within arr...
Give a code snippet in #6502_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Nim
Nim
import sugar, sequtils   proc combsReps[T](lst: seq[T], k: int): seq[seq[T]] = if k == 0: @[newSeq[T]()] elif lst.len == 0: @[] else: lst.combsReps(k - 1).map((x: seq[T]) => lst[0] & x) & lst[1 .. ^1].combsReps(k)   echo(@["iced", "jam", "plain"].combsReps(2)) echo toSeq(1..10).combsReps(3).len
Give a code snippet in #Nim The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AppleScript
AppleScript
-- In-place bubble sort. on bubbleSort(theList, l, r) -- Sort items l thru r of theList. set listLen to (count theList) if (listLen < 2) then return -- Convert negative and/or transposed range indices. if (l < 0) then set l to listLen + l + 1 if (r < 0) then set r to listLen + r + 1 if (l > r) t...
Give a code snippet in #AppleScript 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Perl
Perl
use strict; use English; use POSIX; use Test::Simple tests => 7;   ok( validate_isin('US0378331005'), 'Test 1'); ok( ! validate_isin('US0373831005'), 'Test 2'); ok( ! validate_isin('U50378331005'), 'Test 3'); ok( ! validate_isin('US03378331005'), 'Test 4'); ok( validate_isin('AU0000XVGZA3'), 'Test 5'); ok( ...
Give a code snippet in #Perl An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#XPL0
XPL0
include c:\cxpl\codes; real Val;   proc R2CF(N1, N2, Lev); \Output continued fraction for N1/N2 int N1, N2, Lev; int Quot, Rem; [if Lev=0 then Val:= 0.0; Quot:= N1/N2; Rem:= rem(0); IntOut(0, Quot); if Rem then [ChOut(0, if Lev then ^, else ^;); R2CF(N2, Rem, Lev+1)]; Val:= Val + float(Quot); \generat...
Give a code snippet in #XPL0 Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ActionScript
ActionScript
public function bubbleSort(toSort:Array):Array { var changed:Boolean = false;   while (!changed) { changed = true;   for (var i:int = 0; i < toSort.length - 1; i++) { if (toSort[i] > toSort[i + 1]) { var tmp:int = toSort[i]; toSort[i] = toSort[i + 1]; toSort[i + 1] = tmp;   changed = fals...
Give a code snippet in #ActionScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#D
D
import std.bigint; import std.functional; import std.stdio;   alias sterling1 = memoize!sterling1Impl; BigInt sterling1Impl(int n, int k) { if (n == 0 && k == 0) { return BigInt(1); } if (n > 0 && k == 0) { return BigInt(0); } if (k > n) { return BigInt(0); } return s...
Give a code snippet in #D Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#C
C
void cubic_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4, unsigned int y4, color_component r, color_component g, color_component b );
Give a code snippet in #C Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
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 ...
#PostScript
PostScript
3 4 mul
Give a code snippet in #PostScript 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/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Pointless
Pointless
-- Code based on -- https://github.com/allisio/pointless/blob/master/lib/examples/brainfuck.ptls   output = iterate(run, vm) |> takeUntil(isFinished) |> map(vm => vm.outVal) |> filter(notEq(None)) |> map(char) |> printElems   ----------------------------------------------------------   vm = VM { ip = 0 ...
Give a code snippet in #Pointless Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly im...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Oforth
Oforth
: bullsAndCows | numbers guess digits bulls cows |   ListBuffer new ->numbers while(numbers size 4 <>) [ 9 rand dup numbers include ifFalse: [ numbers add ] else: [ drop ] ]   while(true) [ "Enter a number of 4 different digits between 1 and 9 : " print System.Console askln ->digits digits as...
Give a code snippet in #Oforth Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) maxCount := count := 0   every !&input ? case tab(upto('@')) of { "License OUT ": { maxTime := (maxCount <:= (count +:= 1), []) put(maxTime, (maxCount = count, ="@ ", tab(find(" for ")))) } "License IN ": count -:= (count > 0, 1) # E...
Give a code snippet in #Icon_and_Unicon A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully rec...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Forth
Forth
include random.fs   variable stay-wins variable switch-wins   : trial ( -- ) 3 random 3 random ( prize choice ) = if 1 stay-wins +! else 1 switch-wins +! then ; : trials ( n -- ) 0 stay-wins ! 0 switch-wins ! dup 0 do trial loop cr stay-wins @ . [char] / emit dup . ." staying wins" cr switch-wins @ . ...
Give a code snippet in #Forth Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the...
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
#Plan
Plan
#STEER LIST,BINARY #PROGRAM HLWD #LOWER MSG1A 11HHELLO WORLD MSG1B 11/MSG1A #PROGRAM #ENTRY 0 DISTY MSG1B SUSWT 2HHH #END #FINISH #STOP
Give a code snippet in #Plan 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Action.21
Action!
BYTE FUNC CountDivisors(INT a) INT i BYTE prod,count   prod=1 count=0 WHILE a MOD 2=0 DO count==+1 a==/2 OD prod==*(1+count)   i=3 WHILE i*i<=a DO count=0 WHILE a MOD i=0 DO count==+1 a==/i OD prod==*(1+count) i==+2 OD   IF a>2 THEN prod==*2 FI R...
Give a code snippet in #Action.21 The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Display
Pinstripe/Display
Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display, we can switch to a wider 2 pi...
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 FOR W=1 TO 4 20 FOR I=0 TO 63 STEP 2*W 30 FOR J=1 TO W 40 FOR K=43-11*(W-1) TO 33-11*(W-1) STEP -1 50 PLOT I+J,K 60 NEXT K 70 NEXT J 80 NEXT I 90 NEXT W
Give a code snippet in #Sinclair_ZX81_BASIC Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way do...
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.
#SenseTalk
SenseTalk
put recurse(1)   function recurse n put n get the recurse of (n+1) end recurse
Give a code snippet in #SenseTalk 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/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#XSLT
XSLT
sum($values) div count($values)
Give a code snippet in #XSLT Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Java
Java
import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.ListIterator; import java.util.List; import java.util.Set; import java.util.Map;   public class UTM { private List<String> tape; private String blankSymbol; private ListIterator<String> head; private Map<St...
Give a code snippet in #Java One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine ...
christopher/rosetta-code
http://rosettacode.org/wiki/Erd%C3%B6s-Selfridge_categorization_of_primes
Erdös-Selfridge categorization of primes
A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their category, then assign the firs...
#Julia
Julia
using Primes   primefactors(n) = collect(keys(factor(n)))   function ErdösSelfridge(n) highfactors = filter(>(3), primefactors(n + 1)) category = 1 while !isempty(highfactors) highfactors = unique(reduce(vcat, [filter(>(3), primefactors(a + 1)) for a in highfactors])) category += 1 end ...
Give a code snippet in #Julia A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their...
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 ...
#Liberty_BASIC
Liberty BASIC
Print Ackermann(1, 2)   Function Ackermann(m, n) Select Case Case (m < 0) Or (n < 0) Exit Function Case (m = 0) Ackermann = (n + 1) Case (m > 0) And (n = 0) Ackermann = Ackermann((m - 1), 1) Case (m > 0) And (n >...
Give a code snippet in #Liberty_BASIC 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/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#zkl
zkl
// Use Graham Scan to sort points into a convex hull // https://en.wikipedia.org/wiki/Graham_scan, O(n log n) // http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/ // http://geomalgorithms.com/a10-_hull-1.html fcn grahamScan(points){ N:=points.len(); # find the point with the lowest y-coordinate, x is ti...
Give a code snippet in #zkl Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#FreeBASIC
FreeBASIC
'Vampire numbers. 'FreeBASIC version 24. Windows 'Vampire.bas Function WithinString(n As Ulongint,f As Ulongint) As Integer var m=Str(n),p=Str(f) For z As Integer=0 To Len(p)-1 var i=Instr(m,Chr(p[z])) If i Then m=Mid(m,1,i-1)+Mid(m,i+1) Else Return 0 End ...
Give a code snippet in #FreeBASIC A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#REXX
REXX
Axtec_god.3='Quetzalcoatl ("feathered serpent"), god of learning, civilization, regeneration, wind and storms'
Give a code snippet in #REXX Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/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. ...
#MUMPS
MUMPS
FORLOOP NEW I,J FOR I=1:1:5 DO .FOR J=1:1:I DO ..WRITE "*" .WRITE ! QUIT
Give a code snippet in #MUMPS “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/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, ...
#Mercury
Mercury
:- module zero_to_the_zero_power. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module float, int, integer, list, string.   main(!IO) :- io.format(" int.pow(0, 0) = %d\n", [i(pow(0, 0))], !IO), io.format("integer.pow(zero, zero) = %s\n", [s...
Give a code snippet in #Mercury 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     o...
christopher/rosetta-code
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
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 ...
#jq
jq
def splitup: def tidy: if .[0] == "" then .[1:] else . end | if .[length-1] == "" then .[0:length-1] else . end ;   # a and b are assumed to be arrays: def alternate(a;b): reduce range(0; [a,b] | map(length) | max) as $i ([]; . + [a[$i], b[$i]]);   ([splits("[0-9]+")] | tidy) as $a | ([splits("[^0-9]+")] ...
Give a code snippet in #jq 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/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...
#UNIX_Shell
UNIX Shell
gcd() { # Calculate $1 % $2 until $2 becomes zero. until test 0 -eq "$2"; do # Parallel assignment: set -- 1 2 set -- "$2" "`expr "$1" % "$2"`" done   # Echo absolute value of $1. test 0 -gt "$1" && set -- "`expr 0 - "$1"`" echo "$1" }   gcd -47376 87843 # => 987
Give a code snippet in #UNIX_Shell 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/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...
#Modula-2
Modula-2
MODULE CUSIP; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..10] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE cusipCheckDigit(cusip : ARRAY OF CHAR) : INTEGER; VAR i,v,su...
Give a code snippet in #Modula-2 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 alphanume...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);   Catalan2 := n -> Binomial(2*n, n)/(n + 1);   Catalan3 := function(n) local k, c; c := 1; k := 0; while k < n do k := k + 1; c := 2*(2*k - 1)*c/(k + 1); od; return c; end;   Catalan4_memo := [1]; Catalan4 := function(n) ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) !...
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...
#Go
Go
package main   import "fmt"   func isCusip(s string) bool { if len(s) != 9 { return false } sum := 0 for i := 0; i < 8; i++ { c := s[i] var v int switch { case c >= '0' && c <= '9': v = int(c) - 48 case c >= 'A' && c <= 'Z': v =...
Give a code snippet in #Go 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#OCaml
OCaml
let is_palindrome s = let l = String.length s in let rec comp n = n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in comp (l / 2)
Give a code snippet in #OCaml A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#E
E
def isPalindrome(string :String) { def upper := string.toUpperCase() def last := upper.size() - 1 for i => c ? (upper[last - i] != c) in upper(0, upper.size() // 2) { return false } return true }
Give a code snippet in #E A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a w...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Ursala
Ursala
#import std #import nat   carpet = ~&a^?\<<&>>! (-*<7,5,7>; *=DS ~&K7+ ~&B**DS*=rlDS)^|R/~& predecessor   #show+   test = mat0 ~&?(`#!,` !)*** carpet* <0,1,2,3>
Give a code snippet in #Ursala Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Phix
Phix
procedure subleq(sequence code) integer ip := 0 while ip>=0 do integer {a,b,c} = code[ip+1..ip+3] ip += 3 if a=-1 then code[b+1] = iff(platform()=JS?'?':getc(0)) elsif b=-1 then puts(1,code[a+1]) else code[b+1] -= code[a+1] ...
Give a code snippet in #Phix 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 sig...
christopher/rosetta-code
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat...
#Python
Python
from itertools import product, combinations, izip   scoring = [0, 1, 3] histo = [[0] * 10 for _ in xrange(4)]   for results in product(range(3), repeat=6): s = [0] * 4 for r, g in izip(results, combinations(range(4), 2)): s[g[0]] += scoring[r] s[g[1]] += scoring[2 - r]   for h, v in izip(his...
Give a code snippet in #Python It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on the...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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 Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJLINK = STRUCT( REF OBJLINK next, REF OBJLINK prev, OBJVALUE value # ... etc. required # ); PROC obj link new = REF OBJLINK: ~; PROC obj link free = (REF OBJLINK free)VOID: ~ END CO   # actually a pointer to the last LINK, there ITEMs are ADDED/get # MOD...
Give a code snippet in #ALGOL_68 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 Implement a FIFO queue. Elements are added at one side and popped from the other in th...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#CoffeeScript
CoffeeScript
double = [1,2,3].map (x) -> x*2
Give a code snippet in #CoffeeScript Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#C.23
C#
using System; using System.Linq;   class Program { const string Lower = "abcdefghijklmnopqrstuvwxyz"; const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string Digits = "0123456789"; const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; static readonly string[] Full = {Lower, Upper, Digits...
Give a code snippet in #C.23 Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Elixir
Elixir
defmodule Prime do def decomposition(n), do: decomposition(n, 2, [])   defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n]) defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc]) defp decomposition(n, k, acc), do: decomposition(n, k+1, acc) end   prime = ...
Give a code snippet in #Elixir The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Wren
Wren
import "random" for Random import "/dynamic" for Tuple import "/fmt" for Fmt   var Symbols = Tuple.create("Symbols", ["k", "q", "r", "b", "n"])   var A = Symbols.new("K", "Q", "R", "B", "N") var W = Symbols.new("♔", "♕", "♖", "♗", "♘") var B = Symbols.new("♚", "♛", "♜", "♝", "♞")   var krn = [ "nnrkr", "nrnkr", "nr...
Give a code snippet in #Wren Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#VBScript
VBScript
Function pick_random(arr) Set objRandom = CreateObject("System.Random") pick_random = arr(objRandom.Next_2(0,UBound(arr)+1)) End Function   WScript.Echo pick_random(Array("a","b","c","d","e","f"))
Give a code snippet in #VBScript Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#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 = bubbleSort(String[] Arrays.copyOf...
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/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de dtor (Deg) (*/ Deg pi 180.0) )   (de rtod (Rad) (*/ Rad 180.0 pi) )   (prinl (format (sin (/ pi 4)) *Scl) " " (format (sin (dtor 45.0)) *Scl) ) (prinl (format (cos (/ pi 4)) *Scl) " " (format (cos (dtor 45.0)) *Scl) ) (prinl (format (tan (/ pi 4)) *Scl) " " (format (tan (dtor 4...
Give a code snippet in #PicoLisp Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that ev...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_wheel
Color wheel
Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and ...
#zkl
zkl
var w=300,h=300,out=PPM(w,h); colorWheel(out); out.writeJPGFile("colorWheel.zkl.jpg");   fcn colorWheel(ppm){ zero,R:=ppm.w/2, zero; foreach x,y in (w,h){ v,hue:=(x - zero).toFloat().toPolar(y - zero); if(v<=R){ // only render in the circle if((hue = hue.toDeg())<0) hue+=360; // (-pi..pi] to [0...
Give a code snippet in #zkl Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understa...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#EchoLisp
EchoLisp
  (lib 'hash) (lib 'amb)   ;; return #f or house# for thing/category ;; houses := (0 1 2 3 4) (define (house-get H category thing houses) (for/or ((i houses)) #:continue (!equal? (hash-ref (vector-ref H i) category) thing) i))   ;; return house # for thing (eg cat) in category (eq animals) ;; add th...
Give a code snippet in #EchoLisp Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five...
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 ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class PartialFunctionApplication { static Func<T1, TResult> PartiallyApply<T1, T2, TResult>(Func<T1, T2, TResult> function, T2 argument2) { return argument1 => function(argument1, argument2); }   static void Main() { ...
Give a code snippet in #C.23 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...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#TI-89_BASIC
TI-89 BASIC
Prgm InputStr "Enter a string", s Loop Prompt integer If integer ≠ 75000 Then Disp "That wasn't 75000." Else Exit EndIf EndLoop EndPrgm
Give a code snippet in #TI-89_BASIC User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Run_BASIC
Run BASIC
for i = 0 to 50000000 step 10 a$ = str$(i) for c = 1 TO len(a$) d = val(mid$(a$, c, 1)) j(d) = j(d) + 1 k(c-1) = d next c r = 0 for n = 0 to 10 r = r + (j(n) = k(n)) j(n) = 0 k(n) = 0 next n if r = 11 then print i next i print "== End ==" end
Give a code snippet in #Run_BASIC 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, whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Battlestar
Battlestar
  // Fibonacci sequence, recursive version fun fibb loop a = funparam[0] break (a < 2)   a--   // Save "a" while calling fibb a -> stack   // Set the parameter and call fibb funparam[0] = a call fibb   // Handle the return value and restore "a"...
Give a code snippet in #Battlestar The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solution...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#JavaScript
JavaScript
  /* Token: type, value, line, pos */   const TokenType = { Keyword_if: 1, Keyword_else: 2, Keyword_print: 3, Keyword_putc: 4, Keyword_while: 5, Op_add: 6, Op_and: 7, Op_assign: 8, Op_divide: 9, Op_equal: 10, Op_greater: 11, Op_greaterequal: 12, Op_less: 13, Op_Lessequal: 14, Op_mod: 15, Op_multiply: 16...
Give a code snippet in #JavaScript Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer,...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Scheme
Scheme
(use gauche.collection) ;; for fold2   (define (char-val char) (define i (string-scan "IVXLCDM" char)) (* (expt 10 (div i 2)) (expt 5 (mod i 2))))   (define (decode roman) (fold2 (lambda (n sum prev-val) (values ((if (< n prev-val) - +) sum n) (max n prev-val))) 0 0 (map char-val (reverse (strin...
Give a code snippet in #Scheme Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Phix
Phix
-- -- demo\rosetta\Euler_method.exw -- ============================= -- with javascript_semantics function ivp_euler(atom y, integer f, step, end_t) sequence res = {} for t=0 to end_t by step do if remainder(t,10)==0 then res &= y end if y += step * call_func(f,{t, y}) end for return res...
Give a code snippet in #Phix Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#MAXScript
MAXScript
haystack=#("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")   for needle in #("Washington","Bush") do ( index = findItem haystack needle   if index == 0 then ( format "% is not in haystack\n" needle ) else ( format "% %\n" index needle ) )
Give a code snippet in #MAXScript Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needl...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#FreeBASIC
FreeBASIC
function numdiv( n as uinteger ) as uinteger dim as uinteger c = 2 for i as uinteger = 2 to (n+1)\2 if n mod i = 0 then c += 1 next i return c end function   function istau( n as uinteger ) as boolean if n = 1 then return true if n mod numdiv(n) = 0 then return true else return false end...
Give a code snippet in #FreeBASIC A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau func...
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 |...
#BBC_BASIC
BBC BASIC
first$ = "The fox jumps over the dog"   FOR test% = 1 TO 3 READ second$ starts% = FN_first_starts_with_second(first$, second$) IF starts% PRINT """" first$ """ starts with """ second$ """" ends% = FN_first_ends_with_second(first$, second$) IF ends% PRINT """" first$ "...
Give a code snippet in #BBC_BASIC Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Racket
Racket
#lang typed/racket (define-type Point (Pair Real Real)) (define-type Points (Listof Point))   (: ⊗ (Point Point Point -> Real)) (define/match (⊗ o a b) [((cons o.x o.y) (cons a.x a.y) (cons b.x b.y)) (- (* (- a.x o.x) (- b.y o.y)) (* (- a.y o.y) (- b.x o.x)))])   (: Point<? (Point Point -> Boolean)) (define (Point...
Give a code snippet in #Racket Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
GCD[a, b]
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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 fa...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Scala
Scala
def quibble( s:List[String] ) = s match { case m if m.isEmpty => "{}" case m if m.length < 3 => m.mkString("{", " and ", "}") case m => "{" + m.init.mkString(", ") + " and " + m.last + "}" }   // A little test... { println( quibble( List() ) ) println( quibble( List("ABC") ) ) println( quibble( List("ABC","...
Give a code snippet in #Scala Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An in...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Excel
Excel
lastSundayOfEachMonth =LAMBDA(y, LAMBDA(monthEnd, 1 + monthEnd - WEEKDAY(monthEnd) )( EDATE( DATEVALUE(y & "-01-31"), SEQUENCE(12, 1, 0, 1) ) ) )
Give a code snippet in #Excel Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Component_Pascal
Component Pascal
  MODULE Callback; IMPORT StdLog;   TYPE Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER); Callback2 = PROCEDURE (x: INTEGER): INTEGER;   PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER); VAR i: INTEGER; BEGIN FOR i := 0 TO LEN(x) - 1 DO; proc(x[i],x[i]); END END Apply;   PROCEDURE Apply2(...
Give a code snippet in #Component_Pascal Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Rendezvous
Rendezvous
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
#zkl
zkl
class OutOfInk(Exception.IOError){ const TEXT="Out of ink"; text=TEXT; // rename IOError to OutOfInk for this first/mother class fcn init{ IOError.init(TEXT) } // this renames instances } class Printer{ var id, ink; fcn init(_id,_ink){ id,ink=vm.arglist } fcn print(line){ if(not ink) throw(OutO...
Give a code snippet in #zkl Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Python
Python
  from turtle import *   colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]   # Middle of screen is 0,0   screen = getscreen()   left_edge = -screen.window_width()//2   right_edge = screen.window_width()//2   quarter_height = screen.window_height()//4   half_height = quarter_height * 2   s...
Give a code snippet in #Python The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Minkowski_question-mark_function
Minkowski question-mark function
The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o...
#FreeBASIC
FreeBASIC
#define MAXITER 151   function minkowski( x as double ) as double if x>1 or x<0 then return int(x)+minkowski(x-int(x)) dim as ulongint p = int(x) dim as ulongint q = 1, r = p + 1, s = 1, m, n dim as double d = 1, y = p while true d = d / 2.0 if y + d = y then exit while m = ...
Give a code snippet in #FreeBASIC The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. ...
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...
#Crystal
Crystal
class MyClass   def initialize @instance_var = 0 end   def add_1 @instance_var += 1 end   end   my_class = MyClass.new  
Give a code snippet in #Crystal 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#Racket
Racket
#lang racket   (define (pig-the-dice #:print? [print? #t] . players) (define prn (if print? (λ xs (apply printf xs) (flush-output)) void)) (define names (for/list ([p players] [n (in-naturals 1)]) n)) (define points (for/list ([p players]) (box 0))) (with-handlers ([(negate exn?) identity]) (for ([nm (in-cy...
Give a code snippet in #Racket Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play str...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#11l
11l
F maxnum(x) V maxlen = String(max(x)).len R sorted((x.map(v -> String(v))), key' i -> i * (@maxlen * 2 I/ i.len), reverse' 1B).join(‘’)   L(numbers) [[212, 21221], [1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]] print("Numbers: #.\n Largest integer: #15".format(numbers, maxnum(numbers)))
Give a code snippet in #11l Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34,...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Wren
Wren
/* The answer must be an even number and it can't be less than the square root of 269,696. So, if we start from that, keep on adding 2 and squaring it we'll eventually find the answer. */   import "/fmt" for Fmt // this enables us to format numbers with thousand separators   var start = 269696.s...
Give a code snippet in #Wren Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Compu...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Liberty_BASIC
Liberty BASIC
  'adapted from BASIC solution mult(1) = 1: mult(2) = 3: mult(3) = 1 mult(4) = 7: mult(5) = 3: mult(6) = 9   DO INPUT a$ PRINT a$ + STR$(getSedolCheckDigit(a$)) LOOP WHILE a$ <> ""   FUNCTION getSedolCheckDigit (str$) IF LEN(str$) <> 6 THEN PRINT "Six chars only please" EXIT ...
Give a code snippet in #Liberty_BASIC Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#COBOL
COBOL
  program-id. last-fri. data division. working-storage section. 1 wk-date. 2 yr pic 9999. 2 mo pic 99 value 1. 2 da pic 99 value 1. 1 rd-date redefines wk-date pic 9(8). 1 binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 friday pic ...
Give a code snippet in #COBOL Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Tcl
Tcl
proc fibiter n { if {$n < 2} {return $n} set prev 1 set fib 1 for {set i 2} {$i < $n} {incr i} { lassign [list $fib [incr fib $prev]] prev fib } return $fib }
Give a code snippet in #Tcl The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Julia
Julia
s = "hello" println(s * " there!")
Give a code snippet in #Julia String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lit...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ПП 38 П1 ПП 30 П2 ПП 35 П3 2 * ПП 30 ИП2 ИП3 + 2 * + ИП1 + 3 / ИП7 + П7 П8 С/П БП 00 ИП6 ИП5 + П6 <-> ИП7 + П8 ИП8 КвКор ИП6 * ИП5 * В/О
Give a code snippet in #.D0.9C.D0.9A-61.2F52 Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Elena
Elena
import system'dynamic; import extensions;   class TestClass { object theVariables;   constructor() { theVariables := new DynamicStruct() }   function() { auto prop := new MessageName(console.write:"Enter the variable name:".readLine()); (prop.setPropertyMessage())(theVari...
Give a code snippet in #Elena Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
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"
#Neko
Neko
/* command line arguments, neko */ var argc = $asize($loader.args)   /* Display count and arguments, indexed from 0, no script name included */ $print("There are ", argc, " arguments\n")   var arg = 0 while arg < argc $print($loader.args[arg ++= 1], "\n")
Give a code snippet in #Neko 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/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#IS-BASIC
IS-BASIC
100 PROGRAM "NQueens.bas" 110 TEXT 80 120 DO 130 INPUT PROMPT "Size of board (2-12): ":N$ 140 LET N=VAL(N$) 150 LOOP UNTIL N>1 AND N<13 160 NUMERIC A(1 TO N),X(1 TO N),B(2 TO 2*N),C(-N+1 TO N-1) 170 LET SOL=0 180 CALL INIT(A):CALL INIT(B):CALL INIT(C) 190 CALL TRY(1) 200 PRINT SOL;"solutions." 210 END 220 DEF WRITE...
Give a code snippet in #IS-BASIC Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight'...
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...
#Vedit_macro_language
Vedit macro language
// Main program for testing BINARY_SEARCH #3 = Get_Num("Value to search: ") EOF #2 = Cur_Line // hi #1 = 1 // lo Call("BINARY_SEARCH") Message("Value ") Num_Type(#3, NOCR) if (Return_Value < 1) { Message(" not found\n") } else { Message(" found at index ") Num_Type(Ret...
Give a code snippet in #Vedit_macro_language 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#GW-BASIC
GW-BASIC
10 FOR N = 1 TO 100 20 IF N < 3 THEN T=N: GOTO 70 30 T=2 40 FOR A = 2 TO INT( (N+1)/2 ) 50 IF N MOD A = 0 THEN T = T + 1 60 NEXT A 70 PRINT T; 80 IF N MOD 10 = 0 THEN PRINT 90 NEXT N
Give a code snippet in #GW-BASIC Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#C.23
C#
namespace RosettaCode.Arithmetic.Complex { using System; using System.Numerics;   internal static class Program { private static void Main() { var number = Complex.ImaginaryOne; foreach (var result in new[] { number + number, number * number, -number, 1 / number, ...
Give a code snippet in #C.23 A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaysty...
christopher/rosetta-code