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/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Tcl
Tcl
package require Tcl 8.4 proc dl {_name cmd {where error} {value ""}} { upvar 1 $_name N switch -- $cmd { insert { if ![info exists N()] {set N() {"" "" 0}} set id [lindex $N() 2] lset N() 2 [incr id] switch -- $where { head { ...
Give a code snippet in #Tcl Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Ada
Ada
private with Ada.Containers.Doubly_Linked_Lists;   generic type State is (<>); -- State'First is starting state type Symbol is (<>); -- Symbol'First is blank package Turing is   Start: constant State := State'First; Halt: constant State := State'Last; subtype Action_State is State range Start .. Stat...
Give a code snippet in #Ada 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Julia
Julia
const winningpositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]]   function haswon(brd, xoro) marked = findall(x -> x == xoro, brd) for pos in winningpositions if length(pos) <= length(marked) && pos == sort(marked)[1:3] return true ...
Give a code snippet in #Julia Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#MAXScript
MAXScript
  fn drawBarRow _bmp _row _width _number _inverse= ( local dir = if _inverse then 1 else -1 if not _inverse then ( setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (black)) for i = (_width/_number) to _width by (_width/_number) do ( local loopPosition = i/(_width-(_width/_number)) as fl...
Give a code snippet in #MAXScript The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Kite
Kite
#!/usr/bin/kite   import "System.file";   in = System.file.stdin; line = in|readline; while(not (line is null)) [ arry = line|split(" "); result = (arry[0])|int + (arry[1])|int; result|print;   line = in|readline; ];
Give a code snippet in #Kite A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Maple
Maple
#defining an array of a certain length a := Array (1..5); a := [ 0 0 0 0 0 ] #can also define with a list of entries a := Array ([1, 2, 3, 4, 5]); a := [ 1 2 3 4 5 ] a[1] := 9; a a[1] := 9 [ ...
Give a code snippet in #Maple This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retri...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Salmon
Salmon
variable x := 0; do { ++x; x! } while (x % 6 != 0);
Give a code snippet in #Salmon Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Tcl
Tcl
proc fizzbuzz {n {m1 3} {m2 5}} { for {set i 1} {$i <= $n} {incr i} { set ans "" if {$i % $m1 == 0} {append ans Fizz} if {$i % $m2 == 0} {append ans Buzz} puts [expr {$ans eq "" ? $i : $ans}] } } fizzbuzz 100
Give a code snippet in #Tcl Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Forth
Forth
hex 0000ff constant red 00ff00 constant green ff0000 constant blue decimal   1 cells constant pixel : pixels cells ;   : bdim ( bmp -- w h ) 2@ ; : bheight ( bmp -- h ) @ ; : bwidth ( bmp -- w ) bdim drop ; : bdata ( bmp -- addr ) 2 cells + ;   : bitmap ( w h -- bmp ) 2dup * pixels bdata allocate throw dup >r 2! r>...
Give a code snippet in #Forth Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB co...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#C
C
#include <stdio.h>   int main() { int i, j; double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87...
Give a code snippet in #C There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and displa...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:"   #mem execute("CREATE TABLE t_age(age,name)") #mem execute("CREATE TABLE t_name(name,nemesis)")   #mem execute("INSERT INTO t_age VALUES(27,'Jonah')") #mem execute("INSERT INTO t_age VALUES(18,'Alan')") #mem execute("INSERT INTO t_age VALUES(28,'Glory')") #mem execute("INSERT INTO t_age ...
Give a code snippet in #Run_BASIC An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash j...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Groovy
Groovy
content = new File('input.txt').text new File('output.txt').write(content)
Give a code snippet in #Groovy File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Maclisp
Maclisp
(format t "Hello world!~%")
Give a code snippet in #Maclisp 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/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Kotlin
Kotlin
// version 1.1.0   // constant top level property const val N = 5   // read-only top level property val letters = listOf('A', 'B', 'C', 'D', 'E') // 'listOf' creates here a List<Char) which is immutable   class MyClass { // MyClass is effectively immutable because it's only property is read-only /...
Give a code snippet in #Kotlin Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#UNIX_Shell
UNIX Shell
echo "Goodbye, World!" >&2
Give a code snippet in #UNIX_Shell Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#AutoHotkey
AutoHotkey
#NoEnv StringCaseSense On   o := str := "Hello"   Loop { str := perm_next(str) If !str { MsgBox % clipboard := o break } o.= "`n" . str }   perm_Next(str){ p := 0, sLen := StrLen(str) Loop % sLen { If A_Index=1 continue t := SubStr(str, sLen+1-A_Index, 1) n...
Give a code snippet in #AutoHotkey Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#Ruby
Ruby
ary = (1..9).to_a ary.shuffle! while ary == ary.sort score = 0 until ary == ary.sort print "#{ary.inspect} -- How many digits to reverse? " num = gets.to_i # should validate input ary[0, num] = ary[0, num].reverse score += 1 end p ary puts "Your score: #{score}"
Give a code snippet in #Ruby Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sco...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#REXX
REXX
/*REXX program simulates a number of trials of a random digit and show it's skew %. */ parse arg func times delta seed . /*obtain arguments (options) from C.L. */ if func=='' | func=="," then func= 'RANDOM' /*function not specified? Use default.*/ if times=='' | times=="," then times= 1000000...
Give a code snippet in #REXX This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random i...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#C.2B.2B
C++
#include <iostream>   int main() { std::cout << ( (727 == 0x2d7) && (727 == 01327) ? "true" : "false") << std::endl;   return 0; }
Give a code snippet in #C.2B.2B Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should ...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#C.23
C#
using System.Collections.Generic; using System.Linq; using static System.Console; using static System.Linq.Enumerable;   namespace RunLengthEncoding { static class Program { public static string Encode(string input) => input.Length ==0 ? "" : input.Skip(1) .Aggregate((t:input[0].ToString()...
Give a code snippet in #C.23 Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Icon_and_Unicon
Icon and Unicon
  # Play TicTacToe   $define E " " # empty square $define X "X" # X piece $define O "O" # O piece   # -- define a board record Board(a, b, c, d, e, f, g, h, i)   procedure display_board (board, player) write ("\n===============") write (board.a || " | " || board.b || " | " || board.c) write ("---------") write...
Give a code snippet in #Icon_and_Unicon Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#Java
Java
import java.util.function.BiFunction;   public class TriangleOverlap { private static class Pair { double first; double second;   Pair(double first, double second) { this.first = first; this.second = second; }   @Override public String toString...
Give a code snippet in #Java Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#FreeBASIC
FreeBASIC
#define EPS 1.0e-20   type polyterm degree as uinteger coeff as double end type   sub poly_print( P() as double ) dim as string outstr = "", sri for i as integer = ubound(P) to 0 step -1 if outstr<>"" then if P(i)>0 then outstr = outstr + " + " if P(i)<0 then outstr = out...
Give a code snippet in #FreeBASIC This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Java
Java
  import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;   public class PalindromicGapfulNumbers {   public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20...
Give a code snippet in #Java Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful num...
christopher/rosetta-code
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula
Thiele's interpolation formula
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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) Thiele's interpolation formula is an interpolation ...
#Julia
Julia
const N = 256 const N2 = N * div(N - 1, 2) const step = 0.01 const xval_table = zeros(Float64, N) const tsin_table = zeros(Float64, N) const tcos_table = zeros(Float64, N) const ttan_table = zeros(Float64, N) const rsin_cache = Dict{Float64, Float64}() const rcos_cache = Dict{Float64, Float64}() const rtan_cache = Dict...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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) Thiele's interpolati...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#TI-83_BASIC
TI-83 BASIC
100->T 2->N {17,78,19,23,29,77,95,77, 1,11,13,15,15,55}->LA {91,85,51,38,33,29,23,19,17,13,11,14, 2, 1}->LB Dim(LA)->U T->Dim(LC) For(I,1,T) 1->J: 1->F While J<=U and F=1 If remainder(N,LB(J))=0 Then Disp N N->LC(I) iPart(N/LB(J))*LA(J)->N 0->F End J+1->J End End
Give a code snippet in #TI-83_BASIC FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#AWK
AWK
  # syntax: GAWK -f ABBREVIATIONS_AUTOMATIC.AWK ABBREVIATIONS_AUTOMATIC.TXT { dow_arr[NR] = $0 } END { for (i=1; i<=NR; i++) { if (split(dow_arr[i],arr1,FS) != 7) { printf("NG %s\n",dow_arr[i]) continue } col_width = 0 for (j=1; j<=7; j++) { col_width = max(col_width,...
Give a code snippet in #AWK The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or delet...
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...
#Raku
Raku
my $s = 'hello'; say $s ~ ' literal'; my $s1 = $s ~ ' literal'; say $s1;   # or, using mutating concatenation:   $s ~= ' literal'; say $s;
Give a code snippet in #Raku 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 lite...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
While[(Print[#];#!=10)&[RandomIntger[{0,19}]], Print[RandomInteger[{0,19}] ]
Give a code snippet in #Mathematica.2FWolfram_Language Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number befo...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Stata
Stata
. clear all . input x 12 127 28 ... 31 116 146 end   . stem x   Stem-and-leaf plot for x   0* | 77 1* | 2388 2* | 357777778899 3* | 011112345677789 4* | 001222233344456788 5* | 23788 6* | 138 7* | 1 8* | 9* | 69 10* | 4555567999 11* | 13333444555666677778899 12* | 001122344455567777...
Give a code snippet in #Stata Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#R
R
z <- 0 repeat { print(z) z <- z + 1 }
Give a code snippet in #R Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#MelonBasic
MelonBasic
Wait:0.25 Delete:1 Say:/ Wait:0.25 Delete:1 Say:- Wait:0.25 Delete:1 Say:\ Wait:0.25 Delete:1 Goto:1
Give a code snippet in #MelonBasic Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Action.21
Action!
INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit   PROC Main() DEFINE len="121" BYTE ARRAY a(len)=[ 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 ...
Give a code snippet in #Action.21 Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Julia
Julia
function pascal(a::Integer, b::Integer, mid::Integer, top::Integer) yd = round((top - 4 * (a + b)) / 7)  !isinteger(yd) && return 0, 0, 0 y = Int(yd) x = mid - 2a - y return x, y, y - x end   x, y, z = pascal(11, 4, 40, 151) if !iszero(x) println("Solution: x = $x, y = $y, z = $z.") else pr...
Give a code snippet in #Julia This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Liberty_BASIC
Liberty BASIC
nomainwin WindowWidth=800 WindowHeight=600 open "Barnsley Fern" for graphics_nf_nsb as #1 #1 "trapclose [q];down;fill black;flush;color green"   for n = 1 To WindowHeight * 50 r = int(rnd(1)*100) Select Case Case (r>=0) and (r<=84) xn=0.85*x+0.04*y yn=-0.04*x+0.85*y+1.6 Case (r>84) a...
Give a code snippet in #Liberty_BASIC A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 GO TO 9950 5000 REM We reserve line numbers 5000 to 8999 for merged code 9000 STOP: REM In case our line numbers are wrong 9950 REM Merge in our module 9955 MERGE "MODULE" 9960 REM Jump to the merged code. Pray it has the right line numbers! 9965 GO TO 5000
Give a code snippet in #ZX_Spectrum_Basic Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Latitude
Latitude
while { $stdin eof? not. } do { $stdout putln: $stdin readln. }.
Give a code snippet in #Latitude Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Wren
Wren
import "web" for Routes, App   Routes.GET("/") { return "Goodbye, World!" }   App.run(8080)
Give a code snippet in #Wren The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note ...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Objective-C
Objective-C
NSString *str = @"I am a string"; NSString *regex = @".*string$";   // Note: the MATCHES operator matches the entire string, necessitating the ".*" NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];   if ([pred evaluateWithObject:str]) { NSLog(@"ends with 'string'"); }
Give a code snippet in #Objective-C Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If th...
#Julia
Julia
using Combinatorics, BenchmarkTools   asint(dig) = foldl((i, j) -> 10i + Int128(j), dig)   """ Algorithm 1(A) Generate all the permutations of the digits and sort into numeric order. Find the number in the list. Return the next highest number from the list. """ function nexthighest_1A(N) n = Int128(abs(N)) dig ...
Give a code snippet in #Julia Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Q
Q
({-1 string x; x+1}\) 1
Give a code snippet in #Q Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Pascal
Pascal
Program QuadraticRoots;   var a, b, c, q, f: double;   begin a := 1; b := -10e9; c := 1; q := sqrt(a * c) / b; f := (1 + sqrt(1 - 4 * q * q)) / 2;   writeln ('Version 1:'); writeln ('x1: ', (-b * f / a):16, ', x2: ', (-c / (b * f)):16);   writeln ('Version 2:'); q := sqrt(b * b - 4 * a * c); if b ...
Give a code snippet in #Pascal This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#ABAP
ABAP
REPORT z99bottles.   DATA lv_no_bottles(2) TYPE n VALUE 99.   DO lv_no_bottles TIMES. WRITE lv_no_bottles NO-ZERO. WRITE ' bottles of beer on the wall'. NEW-LINE. WRITE lv_no_bottles NO-ZERO. WRITE ' bottles of beer'. NEW-LINE. WRITE 'Take one down, pass it around'. NEW-LINE. SUBTRACT 1 FROM lv_no_bot...
Give a code snippet in #ABAP Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Dylan
Dylan
Module: bottles define method bottles (n :: <integer>) for (n from 99 to 1 by -1) format-out("%d bottles of beer on the wall,\n" "%d bottles of beer\n" "Take one down, pass it around\n" "%d bottles of beer on the wall\n", n, n, n - 1); end end method
Give a code snippet in #Dylan Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Ada
Ada
with Prime_Numbers, Ada.Text_IO;   procedure Test_Semiprime is   package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2); use Integer_Numbers;   begin for N in 1 .. 100 loop if Decompose(N)'Length = 2 then -- N is a semiprime; Ada.Text_IO.Put(Integer'Image(Integer(N))); end if; ...
Give a code snippet in #Ada Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chose...
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...
#JavaScript
JavaScript
var Roman = { Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4], ['IX', 9], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['M', 1000], ['I', 1], ['D', 500]], UnmappedStr : 'Q', parse: function(str) { var result = 0 for (var i=0; i<Roman.Values.leng...
Give a code snippet in #JavaScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Python
Python
>>> def maprange( a, b, s): (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))   >>> for s in range(11): print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))     0 maps to -1 1 maps to -0.9 2 maps to -0.8 3 maps to -0.7 4 maps to -0.6 5 maps to -0.5 6 maps to -0.4 7 maps to -0...
Give a code snippet in #Python Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#Python
Python
import fileinput   # This returns True if the second string has a value on the # same index as the last index of the first string. It runs # faster than trimming the strings because it runs len once # and is a single index lookup versus slicing both strings # one character at a time. def longer(a, b): try: ...
Give a code snippet in #Python Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challe...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Perl
Perl
use utf8; # so we can use literal characters like ☺ in source use Encode qw(encode);   print length encode 'UTF-8', "Hello, world! ☺"; # 17. The last character takes 3 bytes, the others 1 byte each.   print length encode 'UTF-16', "Hello, world! ☺"; # 32. 2 bytes for the BOM, then 15 byte pairs for each character.
Give a code snippet in #Perl Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme conta...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#PL.2FI
PL/I
*process source xref; apd: Proc Options(main); p9a=time(); Dcl (p9a,p9b) Pic'(9)9'; Dcl cnt(3) Bin Fixed(31) Init((3)0); Dcl x Bin Fixed(31); Dcl pd(300) Bin Fixed(31); Dcl sumpd Bin Fixed(31); Dcl npd Bin Fixed(31); Do x=1 To 20000; Call proper_divisors(x,pd,npd); sumpd=sum(pd,npd); Select; ...
Give a code snippet in #PL.2FI These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficien...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#TXR
TXR
@(next :args) @(do (defun count-occurrences (haystack needle) (for* ((occurrences 0) (old-pos 0) (new-pos (search-str haystack needle old-pos nil))) (new-pos occurrences) ((inc occurrences) (set old-pos (+ new-pos (length needle))) ...
Give a code snippet in #TXR Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It...
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  ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Window 16, 14000,12000; Module Pinstripe { Smooth off ' use of GDI32 Dim colors(0 to 7) Colors(0)=#000000,#FF0000, #00FF00, #0000FF, #FF00FF, #00FFFF, #FFFF00, #FFFFFF pixelsX=scale.x/twipsX pixelsY=scale.y/twipsY zo...
Give a code snippet in #M2000_Interpreter 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,  ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { val filePath = "input.txt" // or whatever val file = File(filePath) with (file) { println("%tc".format(lastModified())) // update to current time, say setLastModified(System.currentTimeMillis()) println(...
Give a code snippet in #Kotlin Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Red
Red
>> size? %input.txt == 39244 >> size? %/c/input.txt == 39244
Give a code snippet in #Red Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#LiveCode
LiveCode
function agm aa,g put abs(aa-g) into absdiff put (aa+g)/2 into aan put sqrt(aa*g) into gn repeat while abs(aan - gn) < absdiff put abs(aa-g) into absdiff put (aa+g)/2 into aan put sqrt(aa*g) into gn put aan into aa put gn into g end repeat return aa end ...
Give a code snippet in #LiveCode This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a functio...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#OCaml
OCaml
#require "gen" #require "zarith" open Z let range ?(step=one) i j = if i = j then Gen.empty else Gen.unfold (fun k -> if compare i j = compare k j then Some (k, (add step k)) else None) i   (* kth coefficient of (x - 1)^n *) let coeff n k = let numer = Gen.fold mul one (range n (sub n k) ~step:minus_one) in ...
Give a code snippet in #OCaml The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Euphoria
Euphoria
type fourty_two(integer i) return i = 42 end type   fourty_two i   i = 41 -- type-check failure
Give a code snippet in #Euphoria Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Pascal
Pascal
Program PriceFraction(output);   const limit: array [1..20] of real = (0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01); price: array [1..20] of real = (0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0....
Give a code snippet in #Pascal A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and...
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 ...
#PL.2FI
PL/I
/* A primitive bubble sort */ bubble_sort: procedure (A); declare A(*) fixed binary; declare temp fixed binary; declare i fixed binary, no_more_swaps bit (1) aligned;   do until (no_more_swaps); no_more_swaps = true; do i = lbound(A,1) to hbound(A,1)-1; if A(i) > A(i+1) then ...
Give a code snippet in #PL.2FI Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#Perl
Perl
use List::Util qw(none);   sub grep_unique { my($by, @list) = @_; my @seen; for (@list) { my $x = &$by(@$_); $seen[$x]= defined $seen[$x] ? 0 : join ' ', @$_; } grep { $_ } @seen; }   sub sums { my($n) = @_; my @sums; push @sums, [$_, $n - $_] for 2 .. int $n/2; @sums...
Give a code snippet in #Perl Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P ...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#newLISP
newLISP
(define pi 3.141592654) (define (radians degrees) (mul degrees (div pi 180))) (define (degrees radians) (mul radians (div 180 pi)))   (print "Enter latitude => ") (set 'lat (float (read-line)))   (print "Enter longitude => ") (set 'lng (float (read-line)))   (print "Enter legal meridian => ") (set 'rf (float...
Give a code snippet in #newLISP Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Isla...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Delphi
Delphi
  program Gamma_function;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   function lanczos7(z: double): Double; begin var t := z + 6.5; var x := 0.99999999999980993 + 676.5203681218851 / z - 1259.1392167224028 / (z + 1) + 771.32342877765313 / (z + 2) - 176.61502916214059 / (z + 3) + 12.50734...
Give a code snippet in #Delphi Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#AutoHotkey
AutoHotkey
Vet1 := "1,3,-5" Vet2 := "4 , -2 , -1" MsgBox % DotProduct( Vet1 , Vet2 )   ;---------------------------   DotProduct( VectorA , VectorB ) { Sum := 0 StringSplit, ArrayA, VectorA, `,, %A_Space% StringSplit, ArrayB, VectorB, `,, %A_Space% If ( ArrayA0 <> ArrayB0 ) Return ERROR While ( A_Index <= ArrayA0 ) ...
Give a code snippet in #AutoHotkey Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Crystal
Crystal
File.write "output.txt", "" Dir.mkdir "docs"   File.write "/output.txt", "" Dir.mkdir "/docs"
Give a code snippet in #Crystal In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#PowerShell
PowerShell
  function Get-RandomInteger { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateScript({$_ -ge 4})] [int[]] $InputObject = 64 )   Begin ...
Give a code snippet in #PowerShell Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Huginn
Huginn
import Algorithms as algo; import Mathematics as math; import Terminal as term;   class Maze { _rows = none; _cols = none; _data = none; constructor( rows_, cols_ ) { _rows = ( rows_ / 2 ) * 2 - 1; _cols = ( cols_ / 2 ) * 2 - 1; _data = [].resize( _rows + 2, [].resize( _cols + 2, false ) ); x = 0; y = 0; ...
Give a code snippet in #Huginn This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#D
D
import std.stdio, std.bigint, std.range, std.algorithm;   struct BalancedTernary { // Represented as a list of 0, 1 or -1s, // with least significant digit first. enum Dig : byte { N=-1, Z=0, P=+1 } // Digit. const Dig[] digits;   // This could also be a BalancedTernary template argument. static...
Give a code snippet in #D Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus ...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#AWK
AWK
BEGIN { site="en.wikipedia.org" path="/wiki/" name="Rosetta_Code"   server = "/inet/tcp/0/" site "/80" print "GET " path name " HTTP/1.0" |& server print "Host: " site |& server print "\r\n\r\n" |& server   while ( (server |& getline fish) > 0 ) { if ( ++scale == 1 ) ship = fish else ...
Give a code snippet in #AWK Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
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
#APL
APL
'Hello world!'
Give a code snippet in #APL 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/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Python
Python
def _menu(items): for indexitem in enumerate(items): print ("  %2i) %s" % indexitem)   def _ok(reply, itemcount): try: n = int(reply) return 0 <= n < itemcount except: return False   def selector(items, prompt): 'Prompt to select an item from the items' if not items: ...
Give a code snippet in #Python Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the str...
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...
#ALGOL_W
ALGOL W
begin % show some (unsigned) Stirling numbers of the first kind  % integer MAX_STIRLING; MAX_STIRLING := 12; begin  % construct a matrix of Stirling numbers up to max n, max n  % integer array s1 ( 0 :: MAX_STIRLING, 0 :: MAX_STIRLING ); for n := 0 until MAX_STIRL...
Give a code snippet in #ALGOL_W 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Rascal
Rascal
import IO;   public void logic(bool a, bool b){ println("a and b, is <a && b>"); println("a or b, is <a || b>"); println("a equivalent to b, is <a <==> b>"); println("a implies b, is <a ==> b>"); println("not a", <!a>"); }
Give a code snippet in #Rascal 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/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are pai...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data=Import["https://rosettacode.org/mw/title.png","Byte"]; parts=Hash[ByteArray[#],"SHA256","ByteArray"]&/@Partition[data,UpTo[1024]]; parts=NestWhile[If[Length[#]==2,Hash[Join@@#,"SHA256","ByteArray"],First[#]]&/@Partition[#,UpTo[2]]&,parts,Length[#]>1&]; StringJoin[IntegerString[Normal[First[parts]],16]]
Give a code snippet in #Mathematica.2FWolfram_Language As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning o...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#AppleScript
AppleScript
-- All input values must be integers and multiples of the same monetary unit. on countCoins(amount, denominations) -- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros. script o property counters : {1} end script repeat amount times set end of...
Give a code snippet in #AppleScript There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#JavaScript
JavaScript
  class Nim { constructor(tokens, printFun) { this.startTokens = tokens; this.tokens = tokens; this.printFun = printFun; }   playerTurn(take) { take = Math.round(take);   if (take < 1 || take > 3) { this.printFun("take must be between 1 and 3.\n") return false; } this.tokens -= take; this.print...
Give a code snippet in #JavaScript Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player t...
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.
#R
R
#Get the limit options("expressions")   #Set it options(expressions = 10000)   #Test it recurse <- function(x) { print(x) recurse(x+1)   } recurse(0)
Give a code snippet in #R 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/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Haskell
Haskell
main = print ψ where δΔ = 1 ψ = δΔ + 1
Give a code snippet in #Haskell Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Gnuplot
Gnuplot
load "filename.gnuplot"
Give a code snippet in #Gnuplot Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#VBScript
VBScript
Function ArrayConcat(arr1, arr2) ReDim ret(UBound(arr1) + UBound(arr2) + 1) For i = 0 To UBound(arr1) ret(i) = arr1(i) Next offset = Ubound(arr1) + 1 For i = 0 To UBound(arr2) ret(i + offset) = arr2(i) Next ArrayConcat = ret End Function   arr1 = array(10,20,30) arr2 = array(...
Give a code snippet in #VBScript Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Modula-2
Modula-2
MODULE NQueens; FROM InOut IMPORT Write, WriteCard, WriteString, WriteLn;   CONST N = 8; VAR hist: ARRAY [0..N-1] OF CARDINAL; count: CARDINAL;   PROCEDURE Solve(n, col: CARDINAL); VAR i, j: CARDINAL;   PROCEDURE Attack(i, j: CARDINAL): BOOLEAN; VAR diff: CARDINAL; BEGIN IF hist[j] = i T...
Give a code snippet in #Modula-2 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/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#ALGOL_68
ALGOL 68
# calculate various pernicious numbers #   # returns the population (number of bits on) of the non-negative integer n # PROC population = ( INT n )INT: BEGIN INT number := n; INT result := 0; WHILE number > 0 DO IF ODD number THEN result +:= 1 F...
Give a code snippet in #ALGOL_68 A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is pr...
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified...
#F.23
F#
open Microsoft.FSharp.Data.TypeProviders   type Wsdl = WsdlService<"http://example.com/soap/wsdl"> let result = Wsdl.soapFunc("hello") let result2 = Wsdl.anotherSoapFunc(34234)
Give a code snippet in #F.23 In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect onc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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
function countingSort(array:Array, min:int, max:int) { var count:Array = new Array(array.length); for(var i:int = 0; i < count.length;i++)count[i]=0; for(i = 0; i < array.length; i++) { count[array[i]-min] ++; } var j:uint = 0; for(i = min; i <= max; i++) { for(; count[i-min] > 0; count[i-min]--) array[j...
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/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Lingo
Lingo
keys = ["a","b","c"] values = [1,2,3]   props = [:] cnt = keys.count repeat with i = 1 to cnt props[keys[i]] = values[i] end repeat   put props -- ["a": 1, "b": 2, "c": 3]
Give a code snippet in #Lingo Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_power_tree
Knuth's power tree
(Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values of (at least) the integer po...
#Racket
Racket
#lang racket   (define pow-path-cache (make-hash '((0 . (0)) (1 . (0 1)))))   (define pow-path-level '(1))   (define (pow-path-extend!) (define next-level (for*/fold ([next-level '()]) ([x (in-list pow-path-level)] [y (in-list (pow-path x))] [s (in-value (+ x y))] ...
Give a code snippet in #Racket (Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact val...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Lingo
Lingo
put var -- <Void> put var=VOID -- 1 put voidP(var) -- 1 var = 23 put voidP(var) -- 0
Give a code snippet in #Lingo
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Haskell
Haskell
import Data.List import Control.Monad import Control.Arrow   leaptext x b | b = show x ++ " is a leap year" | otherwise = show x ++ " is not a leap year"   isleapsf j | 0==j`mod`100 = 0 == j`mod`400 | otherwise = 0 == j`mod`4
Give a code snippet in #Haskell Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Perl
Perl
#!/usr/bin/perl do "include.pl"; # Utilize source from another file sayhello();
Give a code snippet in #Perl Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#D
D
import std.stdio, std.algorithm, std.range, arithmetic_rational;   auto farey(in int n) pure nothrow @safe { return rational(0, 1).only.chain( iota(1, n + 1) .map!(k => iota(1, k + 1).map!(m => rational(m, k))) .join.sort().uniq); }   void main() @safe { writefln("Farey seque...
Give a code snippet in #D The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Far...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Perl
Perl
sub prompt { my $prompt = shift; while (1) { print "\n", $prompt, ": "; # type ^D, q, quit, quagmire, etc to quit defined($_ = <STDIN>) and !/^\s*q/ or exit;   return $_ if /^\s*\d+\s*$/s; $prompt = "Please give a non-negative integer"; } }   my $tgt = int(rand prompt("Hola! Please tell me the upper bound"...
Give a code snippet in #Perl Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hig...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Delphi
Delphi
program Floats;   {$APPTYPE CONSOLE}   uses SysUtils;   var PlusInf, MinusInf, NegZero, NotANum: Double;   begin PlusInf:= 1.0/0.0; MinusInf:= -1.0/0.0; NegZero:= -1.0/PlusInf; NotANum:= 0.0/0.0;   Writeln('Positive Infinity: ', PlusInf); // +Inf Writeln('Negative Infinity: ', MinusInf); // -In...
Give a code snippet in #Delphi The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language...
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...
#Scheme
Scheme
(define (catalan m) (let loop ((c 1)(n 0)) (if (not (eqv? n m)) (begin (display n)(display ": ")(display c)(newline) (loop (* (/ (* 2 (- (* 2 (+ n 1)) 1)) (+ (+ n 1) 1)) c) (+ n 1) )))))   (catalan 15)
Give a code snippet in #Scheme 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 ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#MAXScript
MAXScript
fn plot img coord steep col = ( if steep then ( swap coord[1] coord[2] ) setPixels img coord col )   fn drawLine img start end col = ( local steep = (abs (end.y - start.y)) > (abs (end.x - start.x))   if steep then ( swap start.x start.y swap end.x end.y )   i...
Give a code snippet in #MAXScript Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#PHP
PHP
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; }   foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n";   ?>
Give a code snippet in #PHP Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops a...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#CLU
CLU
nth = proc (n: int) returns (string) num: string := int$unparse(n) sfx: array[string] := array[string]$[0: "th", "st", "nd", "rd"]   if n / 10 // 10 = 1 cor n // 10 > 3 then return(num || sfx[0]) else return(num || sfx[n // 10]) end end nth   do_range = proc (from, to: int) po: s...
Give a code snippet in #CLU Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show h...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#MUMPS
MUMPS
MULTTABLE(SIZE)  ;Print out a multiplication table  ;SIZE is the size of the multiplication table to make  ;MW is the maximum width of the numbers  ;D is the down axis  ;A is the across axis  ;BAR is the horizontal bar under the operands NEW MW,D,A,BAR IF $DATA(SIZE)<1 SET SIZE=12 SET MW=$LENGTH(SIZE*SIZE) SET BAR=...
Give a code snippet in #MUMPS Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#ALGOL_68
ALGOL 68
  COMMENT First cut. Doesn't yet do blocking and deblocking. Also, as encryption and decryption are identical operations but for the reciprocal exponents used, only one has been implemented below.   A later release will address these issues. COMMENT   BEGIN PR precision=1000 PR MODE LLI = LONG LONG ...
Give a code snippet in #ALGOL_68 Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encrypt...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Vedit_macro_language
Vedit macro language
#1 = Get_Num("Sleep time in 1/10 seconds: ") Message("Sleeping...\n") Sleep(#1) Message("Awake!\n")
Give a code snippet in #Vedit_macro_language Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep ...
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.
#Julia
Julia
using Printf test = [7.125, [rand()*10^rand(0:4) for i in 1:9]]   println("Formatting some numbers with the @sprintf macro (using \"%09.3f\"):") for i in test println(@sprintf "  %09.3f" i) end   using Formatting println() println("The same thing using the Formatting package:") fe = FormatExpr(" {1:09.3f}") fo...
Give a code snippet in #Julia 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/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Phix
Phix
with javascript_semantics for i=1 to 3 do integer c = (i==2), -- fine d = (c==1), -- oops e = (c==true), -- fine f = equal(c,1) -- fine, ditto equal(c,true) printf(1,"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n", {i, c, c, d,...
Give a code snippet in #Phix Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code