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/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Raven
Raven
VERSION 0 prefer 20071104 < if 'version >= 20071104 required' print bye   'bloop' GLOBAL keys in && 'abs' CORE keys in if bloop abs print
Give a code snippet in #Raven Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Tcl
Tcl
package require Tcl 8.5   namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] }   proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [...
Give a code snippet in #Tcl Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would b...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Mercury
Mercury
:- func name = string. name = Name :- Name = Title ++ " " ++ Given, Title = "Dr.", Given = "Bob".
Give a code snippet in #Mercury Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Euphoria
Euphoria
-- This is a comment
Give a code snippet in #Euphoria Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program rpg.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBTIRAGES, 4 .equ ...
Give a code snippet in #ARM_Assembly RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll fou...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Action.21
Action!
Proc Main() Byte KEY,k=764 KEY=K Return
Give a code snippet in #Action.21 Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Objective-C
Objective-C
NSLog(@"%@", [NSDate date]); NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]); NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d, %Y" timeZone:nil locale:nil]);
Give a code snippet in #Objective-C This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
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 ...
#Smalltalk
Smalltalk
FloatE nan FloatD nan FloatE infinity FloatD infinity FloatE negativeInfinity FloatD negativeInfinity   Float zero -> 0.0 Float negativeZero -> -0.0 0.0 negated -> -0.0 0.0 negated = 0.0 -> true. "they have the same value" 0.0 negated < 0.0 -> false 0.0 negated > 0.0 -> false   1.0 isFinite -> true FloatE infinity isFi...
Give a code snippet in #Smalltalk 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 langu...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Julia
Julia
sorttable(T; ordering=<, column=1, reverse=false) = sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering) sorttable(T, ordering=<, column=1, reverse=false) = sorttable(T, ordering=ordering, column=column, reverse=reverse)
Give a code snippet in #Julia Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lex...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" )   func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect)   // Use green background, say. green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)   /...
Give a code snippet in #Go Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#JavaScript
JavaScript
var now = new Date(), weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' ...
Give a code snippet in #JavaScript This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Red
Red
Red ["Create two-dimensional array at runtime"]   width: to-integer ask "What is the width of the array? " height: to-integer ask "What is the height of the array? "   ; 2D arrays are just nested blocks in Red. matrix: copy [] ; Make an empty block to hold our...
Give a code snippet in #Red Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those number...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#J
J
  NB. use: k lah n lah=: ! :(!&<: * %&!~)&x: NB. `%~' is shorter than `*inv'   NB. wory_lah translates lah to algebraic English. Monad =: :[: NB. permit only a y argument Dyad =: [: : NB. require x and y arguments but_1st =: & decrement =: <: Monad   NB. ! means either factorial or combinations (just as - means n...
Give a code snippet in #J Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly orde...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Cowgol
Cowgol
include "cowgol.coh";   sub count_jewels(stones: [uint8], jewels: [uint8]): (count: uint16) is var jewel_mark: uint8[256]; MemZero(&jewel_mark as [uint8], 256);   while [jewels] != 0 loop jewel_mark[[jewels]] := 1; jewels := @next jewels; end loop;   count := 0; while [stones] !=...
Give a code snippet in #Cowgol Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower cas...
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...
#Io
Io
bottles := method(i, if(i==0, return "no more bottles of beer") if(i==1, return "1 bottle of beer") "" .. i .. " bottles of beer" ) for(i, 99, 1, -1, write( bottles(i), " on the wall, ", bottles(i), ",\n", "take one down, pass it around,\n", bottles(i - 1), " on the wall...
Give a code snippet in #Io 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 bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#Tcl
Tcl
for {set c 0;set printed 0;set special {}} {$c <= 0xffff} {incr c} { set ch [format "%c" $c] set v "_${ch}_" #puts "testing variable named $v" if {[catch {set $v $c; set $v} msg] || $msg ne $c} { puts [format "\\u%04x illegal in names" $c] incr printed } elseif {[catch {subst $$v} msg] == 0 && $ms...
Give a code snippet in #Tcl Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#F.23
F#
open System   let LoremIpsum = " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cu...
Give a code snippet in #F.23 Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provi...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#AWK
AWK
$ awk 'func psqr(x){print x,x*x}BEGIN{split("1 2 3 4 5",a);for(i in a)psqr(a[i])}' 4 16 5 25 1 1 2 4 3 9
Give a code snippet in #AWK Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
TYPE UByte = BITS 8 FOR [0..255];
Give a code snippet in #Mathematica.2FWolfram_Language Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#J
J
(-[smoutput bind 'SPAM')^:_(1)
Give a code snippet in #J Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#PARI.2FGP
PARI/GP
Hupto(n)={ my(v=vector(n),x2=2,x3=3,x5=5,i=1,j=1,k=1,t); v[1]=1; for(m=2,n, v[m]=t=min(x2,min(x3,x5)); if(x2 == t, x2 = v[i++] << 1); if(x3 == t, x3 = 3 * v[j++]); if(x5 == t, x5 = 5 * v[k++]); ); v }; H(n)=Hupto(n)[n];   Hupto(20) H(1691) H(10^6)
Give a code snippet in #PARI.2FGP Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming ...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Lua
Lua
function binomial(n,k) if n<0 or k<0 or n<k then return -1 end if n==0 or k==0 then return 1 end   local num = 1 for i=k+1,n do num = num * i end   local denom = 1 for i=2,n-k do denom = denom * i end   return num / denom end   function gcd(a,b) while b ~= 0 do ...
Give a code snippet in #Lua Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#VBA
VBA
  Option Explicit   Public Sub Main_Anagram() Dim varReturn Dim temp Dim strContent As String Dim strFile As String Dim Num As Long Dim i As Long Dim countTime As Single   'Open & read txt file Num = FreeFile strFile = "C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt" Open strFile For Input As...
Give a code snippet in #VBA When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in the...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#ML.2FI
ML/I
MCSKIP MT,<> MCINS %. MCDEF F WITHS (,,) AS <%WA1.%WA3.%WA2.%WA2.>
Give a code snippet in #ML.2FI Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell....
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#SenseTalk
SenseTalk
  set numbers to [0,1,7,22,186,pi,-48.6,-3451,925734, 12570902378]   repeat with each number in numbers put number into output put numberWords of number into character 15 of output put output end repeat  
Give a code snippet in #SenseTalk Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ada
Ada
with Ada.Text_IO; procedure Radix_Sort is type Integer_Array is array (Positive range <>) of Integer;   procedure Least_Significant_Radix_Sort (Data : in out Integer_Array; Base : Positive := 10) is type Bucket is record Count  : Natural := 0; Content : Integer_Array (Data'Range); e...
Give a code snippet in #Ada 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/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Delphi
Delphi
import extensions;   MakeList(separator) { var counter := 1;   var makeItem := (item){ var retVal := counter.toPrintable() + separator + item + (forward newLine); counter += 1; ^ retVal };   ^ makeItem("first") + makeItem("second") + makeItem("third") }   public program() { console.printLine(MakeList("....
Give a code snippet in #Delphi In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of tw...
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...
#HicEst
HicEst
LEN("1 character == 1 byte") ! 21
Give a code snippet in #HicEst 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 con...
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...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DATA "North","North by east","North-northeast" 20 DATA "Northeast by north","Northeast","Northeast by east","East-northeast" 30 DATA "East by north","East","East by south","East-southeast" 40 DATA "Southeast by east","Southeast","Southeast by south","South-southeast" 50 DATA "South by east","South","South by west","...
Give a code snippet in #ZX_Spectrum_Basic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Rust
Rust
// [dependencies] // primal = "0.2" // circular-queue = "0.2.5"   use circular_queue::CircularQueue;   fn main() { let max = 1000035; let max_group_size = 5; let diff = 6; let max_groups = 5; let max_unsexy = 10;   let sieve = primal::Sieve::new(max + diff); let mut group_count = vec![0; max...
Give a code snippet in #Rust This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime nu...
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
#ACL2
ACL2
PROC Test(BYTE v) PrintF("Variable v has value %B%E",v) IF v THEN PrintE("Condition IF v is satisfied.") ELSE PrintE("Condition IF v is not satisfied.") FI IF v=0 THEN PrintE("Condition IF v=0 is satisfied.") ELSE PrintE("Condition IF v=0 is not satisfied.") FI IF v<>0 THEN PrintE("C...
Give a code snippet in #ACL2 Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Node.js
Node.js
  'use strict'; /* * Imported from http://rosettacode.org/wiki/Maze_generation#JavaScript * Added asynchronous behaviour to the maze generation. * * Port by sigmasoldier */   /** * Generates the maze asynchronously. * @param {Number} x Width of the maze. * @param {Number} y Height of the maze. * @returns {Pro...
Give a code snippet in #Node.js 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 sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Perl
Perl
use strict; $x = 1; # Compilation error. our $y = 2; print "$y\n"; # Legal; refers to $main::y.   package Foo; our $z = 3; package Bar; print "$z\n"; # Refers to $Foo::z.
Give a code snippet in #Perl Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static sco...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#OCaml
OCaml
#directory "+cairo" #load "bigarray.cma" #load "cairo.cma"   let img_name = "/tmp/fractree.png" let width = 480 let height = 640   let level = 9 let line_width = 4.0   let color = (1.0, 0.5, 0.0)   let pi = 4.0 *. atan 1.0   let angle_split = pi *. 0.12 let angle_rand = pi *. 0.12   let () = Random.self_init(); l...
Give a code snippet in #OCaml Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Clojure
Clojure
(try (if (> (rand) 0.5) (throw (RuntimeException. "oops!")) (println "see this half the time") (catch RuntimeException e (println e) (finally (println "always see this"))
Give a code snippet in #Clojure Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptio...
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:...
#Icon_and_Unicon
Icon and Unicon
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
Give a code snippet in #Icon_and_Unicon 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 prope...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Smalltalk
Smalltalk
" Class " MyClass selector: someArgument . " or equivalently " foo := MyClass . foo selector: someArgument.   " Instance " myInstance selector: someArgument.   " Message with multiple arguments " myInstance fooWithRed:arg1 green:arg2 blue:arg3 .   " Message with no arguments " myInstance selector.   " Binary (operator)...
Give a code snippet in #Smalltalk In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#UNIX_Shell
UNIX Shell
#!/bin/sh n=5; k=3; calculate_factorial(){ partial_factorial=1; for (( i=1; i<="$1"; i++ )) do factorial=$(expr $i \* $partial_factorial) partial_factorial=$factorial   do...
Give a code snippet in #UNIX_Shell This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) (...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Lingo
Lingo
str = EMPTY -- same as: str = "" put str=EMPTY -- 1 put str<>EMPTY -- 0
Give a code snippet in #Lingo Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Haskell
Haskell
exp 1 -- Euler number pi -- pi sqrt x -- square root log x -- natural logarithm exp x -- exponential abs x -- absolute value floor x -- floor ceiling x -- ceiling x ** y -- power (e.g. floating-point exponentiation) x ^ y -- power (e.g. integer exponentiation, nonnegative y only) x ^^...
Give a code snippet in #Haskell Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Phixmonti
Phixmonti
"apple" "orange" stklen tolist len print
Give a code snippet in #Phixmonti Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter f...
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) ...
#Common_Lisp
Common Lisp
(defun fizzbuzz () (loop for x from 1 to 100 do (princ (cond ((zerop (mod x 15)) "FizzBuzz") ((zerop (mod x 3)) "Fizz") ((zerop (mod x 5)) "Buzz") (t x))) (terpri)))
Give a code snippet in #Common_Lisp 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   Fi...
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...
#Julia
Julia
  julia> julia> Inf32 == Inf64 == Inf16 == Inf true  
Give a code snippet in #Julia 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Common_Lisp
Common Lisp
(defun horner (coeffs x) (reduce #'(lambda (coef acc) (+ (* acc x) coef)) coeffs :from-end t :initial-value 0))
Give a code snippet in #Common_Lisp A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 )...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Perl
Perl
sub next_num { my @a; $a[$_]++ for split '', shift; join('', map(exists $a[$_] ? $a[$_].$_ : "", reverse 0 .. 9)); }   my %cache; sub seq { my $a = shift; my (%seen, @s); until ($seen{$a}) { $seen{$a} = 1; push(@s, $a); last if !wantarray && $cache{$a}; $a = next_num($a); } return (@s) if wantarray;   ...
Give a code snippet in #Perl There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
package main   import ( "fmt" "strings" )   func main() { // Go language string comparison operators: c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { ...
Give a code snippet in #Go 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 Con...
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)
#Action.21
Action!
BYTE FUNC IsLeapYear(CARD year) IF year MOD 100=0 THEN IF year MOD 400=0 THEN RETURN (1) ELSE RETURN (0) FI FI   IF year MOD 4=0 THEN RETURN (1) FI RETURN (0)   PROC Main() CARD ARRAY t=[1900 1901 2000 2001 2004 2020 2021] BYTE i,leap CARD year   FOR i=0 TO 6 DO year=t...
Give a code snippet in #Action.21 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/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...
#VBScript
VBScript
' Queue Definition - VBScript Option Explicit Dim queue, i, x Set queue = CreateObject("System.Collections.ArrayList") If Not empty_(queue) Then Wscript.Echo queue.Count push queue, "Banana" push queue, "Apple" push queue, "Pear" push queue, "Strawberry" Wscript.Echo "Count=" & queue.Count Wscript.Echo pull(queue) & " ...
Give a code snippet in #VBScript 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/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Fermat
Fermat
Function IsLeap(y) = if y|4>0 then 0 else if y|100=0 and y|400>0 then 0 else 1 fi fi.
Give a code snippet in #Fermat 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/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Crystal
Crystal
File.open("input.txt") do |file| file.each_char { |c| p c } end
Give a code snippet in #Crystal Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should sup...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Tcl
Tcl
# This is how to declare functions - the mathematical entities - as opposed to procedures proc function {name arguments body} { uplevel 1 [list proc tcl::mathfunc::$name $arguments [list expr $body]] }   function double n {$n * 2} function halve n {$n / 2} function even n {($n & 1) == 0} function mult {a b} { $...
Give a code snippet in #Tcl Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Racket
Racket
#lang racket   (define (first-non-matching-index l =) (and (not (null? l)) (index-where l (curry (negate =) (car l)))))   (define (report-string-sameness s) (printf "~s (length: ~a): ~a~%" s (string-length s) (cond [(first-non-matching-index (string->list s) char=?) =>...
Give a code snippet in #Racket Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each...
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...
#OpenEdge.2FProgress
OpenEdge/Progress
MESSAGE 1.0 / 0.0 SKIP -1.0 / 0.0 SKIP(1) ( 1.0 / 0.0 ) = ( -1.0 / 0.0 ) VIEW-AS ALERT-BOX.
Give a code snippet in #OpenEdge.2FProgress 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...
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
#OCaml
OCaml
print_string "Enter a string: "; let str = read_line () in print_string "Enter an integer: "; let num = read_int () in Printf.printf "%s%d\n" str num
Give a code snippet in #OCaml 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/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...
#MANOOL
MANOOL
  { {extern "manool.org.18/std/0.3/all"} in : let { N = 40; M = 80 } in : let { G = 99 } in : let { Display = { proc { B } as  : for { I = Range[N]$ } do  : do Out.WriteLine[] after  : for { J = Range[M]$ } do Out.Write[{if B[I; J] <> 0 then "*" else " "}] } } in : var { B = {array N of: ar...
Give a code snippet in #MANOOL 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/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Maple
Maple
rec := [table(["name"="Lagos","population"=21.0]), table(["name"="Cairo","population"=15.2]), table(["name"="Kinshasa-Brazzaville","population"=11.3]), table(["name"="Greater Johannesburg","population"=7.55]), table(["name"="Mogadishu","population"=5.85]), table(["name"="Khartoum-Omdurman"...
Give a code snippet in #Maple Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[e...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Comal
Comal
0010 FUNC can'make'word#(word$) CLOSED 0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" 0030 FOR i#:=1 TO LEN(word$) DO 0040 pos#:=UPPER$(word$(i#)) IN blocks$ 0050 IF NOT pos# THEN RETURN FALSE 0060 blocks$(pos#):="";blocks$(pos# BITXOR 1):="" 0070 ENDFOR i# 0080 RETURN TRUE 0090 ENDFUNC 0...
Give a code snippet in #Comal ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#AutoHotkey
AutoHotkey
nums := [6, 7, 8, 9, 2, 5, 3, 4, 1] while circlesort(nums, 1, nums.Count(), 0) ; 1-based continue for i, v in nums output .= v ", " MsgBox % "[" Trim(output, ", ") "]" return   circlesort(Arr, lo, hi, swaps){ if (lo = hi) return swaps high:= hi low := lo mid := Floor((hi - lo) / 2) ...
Give a code snippet in #AutoHotkey 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 | Qui...
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,...
#Pony
Pony
use "assert" // due to the use of Fact   - - -   var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed try let x = numbers(0) // fetch the first element of array. index ...
Give a code snippet in #Pony 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 retrie...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#D
D
import std.algorithm; import std.stdio;   int[] getDivisors(int n) { auto divs = [1, n]; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { divs ~= i;   int j = n / i; if (i != j) { divs ~= j; } } } return divs; }   bool i...
Give a code snippet in #D Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors ...
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...
#Fortran
Fortran
program Guess_a_number implicit none   integer, parameter :: limit = 100 integer :: guess, number real :: rnum   write(*, "(a, i0, a)") "I have chosen a number between 1 and ", limit, & " and you have to try to guess it." write(*, "(a/)") "I will score your guess by indicating whe...
Give a code snippet in #Fortran 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: ...
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...
#REBOL
REBOL
;; r2 length? "møøse"   ;; r3 length? to-binary "møøse"
Give a code snippet in #REBOL 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 cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Tern
Tern
module Singleton { speak() { println("I am a singleton"); } }   Singleton.speak();
Give a code snippet in #Tern A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
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...
#Perl
Perl
use warnings; use strict; use Math::BigRat; use ntheory qw/euler_phi vecsum/;   sub farey { my $N = shift; my @f; my($m0,$n0, $m1,$n1) = (0, 1, 1, $N); push @f, Math::BigRat->new("$m0/$n0"); push @f, Math::BigRat->new("$m1/$n1"); while ($f[-1] < 1) { my $m = int( ($n0 + $N) / $n1) * $m1 - $m0; my $n...
Give a code snippet in #Perl 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Pascal
Pascal
Program OneOfNLines (Output);   {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   function one_of_n(n: longint): longint; var i: longint; begin one_of_n := 1; for i := 2 to n do if random < 1.0 / i then one_of_n := i; end;   function sum(a: array of longint): longint; var i: integer; begin R...
Give a code snippet in #Pascal A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second li...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Clojure
Clojure
(defmulti matrix-transpose "Switch rows with columns." class)   (defmethod matrix-transpose clojure.lang.PersistentList [mtx] (apply map list mtx))   (defmethod matrix-transpose clojure.lang.PersistentVector [mtx] (apply mapv vector mtx))  
Give a code snippet in #Clojure Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Euphoria
Euphoria
function strip_first(sequence s) return s[2..$] end function   function strip_last(sequence s) return s[1..$-1] end function   function strip_both(sequence s) return s[2..$-1] end function   puts(1, strip_first("knight")) -- strip first character puts(1, strip_last("write")) -- strip last character puts...
Give a code snippet in #Euphoria The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#MiniScript
MiniScript
factors = function(n) result = [1] for i in range(2, n) if n % i == 0 then result.push i end for return result end function   while true n = val(input("Number to factor (0 to quit)? ")) if n <= 0 then break print factors(n) end while
Give a code snippet in #MiniScript Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#ALGOL_68
ALGOL 68
main:(   [,]REAL m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625));   OP ZIP = ([,]REAL in)[,]REAL:( [2 LWB in:2 UPB in,1 LWB in:1UPB in]REAL out; FOR i FROM LWB in TO UPB in DO out[,i]:=in[i,] OD; ...
Give a code snippet in #ALGOL_68 Transpose an arbitrarily sized rectangular Matrix.
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...
#ALGOL_68
ALGOL 68
# returns TRUE if n is semi-prime, FALSE otherwise # # n is semi prime if it has exactly two prime factors # PROC is semiprime = ( INT n )BOOL: BEGIN # We only need to consider factors between 2 and # # sqrt( n ) inclusive. If there is only one of these # # then it...
Give a code snippet in #ALGOL_68 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#VBA
VBA
Sub Main() Dim i As Integer, c As Integer, j As Integer, strReturn() As String Dim s, n s = Split(SING_, "$") n = Split(NUMBERS_, " ") ReDim strReturn(UBound(s)) For i = LBound(s) To UBound(s) strReturn(i) = Replace(BASE_, "(X)", n(i)) For j = c To 0 Step -1 strReturn(i) = strReturn(i) ...
Give a code snippet in #VBA Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations:...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Cowgol
Cowgol
include "cowgol.coh"; const LIMIT := 100;   var flags: uint8[LIMIT+1]; MemZero(&flags[0], @bytesof flags);   var a: @indexof flags; var b: @indexof flags; var c: @indexof flags;   a := 0; while a <= LIMIT loop b := a; while b <= LIMIT loop c := b; while c <= LIMIT loop flags[c] := 1;...
Give a code snippet in #Cowgol Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McN...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#D
D
import std.stdio, core.runtime;   void inner() { defaultTraceHandler.writeln; } void middle() { inner; } void outer() { middle; }   void main() { outer; "After the stack trace.".writeln; }
Give a code snippet in #D Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platfo...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Ruby
Ruby
def makeList(separator) counter = 1   makeItem = lambda {|item| result = "#{counter}#{separator}#{item}\n" counter += 1 result }   makeItem["first"] + makeItem["second"] + makeItem["third"] end   print makeList(". ")
Give a code snippet in #Ruby In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#J
J
coinsert'jsocket' [ require 'socket' NB. Sockets library socket =. >{.sdcheck sdsocket'' NB. Open a socket host =. sdcheck sdgethostbyname 'localhost' NB. Resolve host sdcheck sdconnect socket ; host ,< 256 NB. Create connection to port 256 sdcheck 'hello s...
Give a code snippet in #J For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Raku
Raku
unit sub MAIN (:$prisoners = 100, :$simulations = 10000); my @prisoners = ^$prisoners; my $half = floor +@prisoners / 2;   sub random ($n) { ^$n .race.map( { my @drawers = @prisoners.pick: *; @prisoners.map( -> $prisoner { my $found = 0; for @drawers.pick($half) -> $card { ...
Give a code snippet in #Raku The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start ou...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Factor
Factor
QUALIFIED: io  ! there already is print in io   GENERIC: print ( shape -- )   TUPLE: point x y ; C: <point> point  ! shorthand constructor definition   M: point print drop "Point" io:print ;   TUPLE: circle radius x y ; C: <circle> circle   M: circle print drop "Circle" io:print ;
Give a code snippet in #Factor Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Genie
Genie
[indent=4] /* Here documents, as template and verbatim strings in Genie valac heredoc.gs */ init test:string = "Genie string"   var multilineString = """ this is a $test """   var templateString = @" this is a $test template with math for six times seven = $(6 * 7) "   stdout.printf("%s", multilineS...
Give a code snippet in #Genie A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#Phix
Phix
with javascript_semantics sequence test = {{"UK","London"}, {"US","New York"}, {"US","Birmingham"}, {"UK","Birmingham"}} --------------------- -- probably stable -- --------------------- function cmp(object a, object b) return compare(a[2],b[2]) end function pp(c...
Give a code snippet in #Phix Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Lingo
Lingo
_player.alert("Goodbye, World!")
Give a code snippet in #Lingo Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
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...
#KQL
KQL
  let dataset = datatable(values:real)[ 1, 1.5, 3, 5, 6.5];   dataset|summarize avg(values)  
Give a code snippet in #KQL Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an establ...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Vedit_macro_language
Vedit macro language
// Daw a line using Bresenham's line algorithm. // #1=x1, #2=y1; #3=x2, #4=y2   :DRAW_LINE: Num_Push(31,35) #31 = abs(#3-#1) // x distance #32 = abs(#4-#2) // y distance if (#4-#2 < -#31 || #3-#1 <= -#32) { #99=#1; #1=#3; #3=#99 // swap start and end points #99=#2; #2=#4; #4=#99 } if (#1 < #3) { #34=1 }...
Give a code snippet in #Vedit_macro_language 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/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopinc64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM6...
Give a code snippet in #AArch64_Assembly Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#IDL
IDL
test: ..some code here goto, test
Give a code snippet in #IDL Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. ...
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...
#Falcon
Falcon
for i in [99:1] > i, " bottles of beer on the wall" > i, " bottles of beer" > "Take one down, pass it around" > i-1, " bottles of beer on the wall\n" end
Give a code snippet in #Falcon 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 9...
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) ...
#Groovy
Groovy
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Group import javafx.scene.Scene import javafx.scene.image.ImageView import javafx.scene.image.WritableImage import javafx.scene.paint.Color import javafx.stage.Stage   class BarnsleyFern extends Application {   @Overrid...
Give a code snippet in #Groovy A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Standard_ML
Standard ML
signature QUEUE = sig type 'a queue val empty : 'a queue val enqueue : 'a -> 'a queue -> 'a queue val dequeue : 'a queue -> ('a * 'a queue) option end
Give a code snippet in #Standard_ML Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some op...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Lambdatalk
Lambdatalk
  {def sumsq {lambda {:s} {+ {S.map {lambda {:i} {* :i :i}} :s}}}} -> sumsq   {sumsq 1 2 3 4 5} -> 55 {sumsq 0} -> 0  
Give a code snippet in #Lambdatalk Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
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.   ...
#PL.2FI
PL/I
/* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */ additive_primes_100H: procedure options (main);   /* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */ /* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */ /* PL...
Give a code snippet in #PL.2FI 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/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Ring
Ring
  a = 1 b = 2 temp = a a = b b = temp see "a = " + a + nl see "b = " + b + nl  
Give a code snippet in #Ring Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Common_Lisp
Common Lisp
(defun print-name (&key first (last "?")) (princ last) (when first (princ ", ") (princ first)) (values))
Give a code snippet in #Common_Lisp Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relie...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#J
J
wdinfo 'Goodbye, World!'
Give a code snippet in #J Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#11l
11l
L(=line) File(‘data.csv’).read_lines() I L.index == 0 line ‘’= ‘,SUM’ E line ‘’= ‘,’sum(line.split(‘,’).map(Int)) print(line)
Give a code snippet in #11l CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RReturnMultipleVals public properties constant L = 'L' R = 'R' K_lipsum = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do ...
Give a code snippet in #NetRexx Task Show how to return more than one value from a function.
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,...
#J
J
1 NB. a stand-alone scalar value is an array without any axis 1 NB. invoking any array produces that array as the result {. array=: 1 3, 6#0 NB. create, name, then get head item of the array: 1 3 0 0 0 0 0 0 1 0 { array NB. another way to get the head item 1 ...
Give a code snippet in #J 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#ACL2
ACL2
(defun rc-step-r (cells) (if (endp (rest cells)) nil (cons (if (second cells) (xor (first cells) (third cells)) (and (first cells) (third cells))) (rc-step-r (rest cells)))))   (defun rc-step (cells) (cons (and (first cells) (second cells)) (rc...
Give a code snippet in #ACL2 Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Scala
Scala
import java.awt._ import java.awt.event.{MouseAdapter, MouseEvent}   import javax.swing._   import scala.math.{Pi, cos, sin}   object Cuboid extends App { SwingUtilities.invokeLater(() => {   class Cuboid extends JPanel { private val nodes: Array[Array[Double]] = Array(Array(-1, -1, -1), Array(-1, -...
Give a code snippet in #Scala Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Tcl
Tcl
  proc humble? x { foreach f {2 3 5 7} { while {$x % $f == 0} {set x [expr {$x / $f}]} } return [expr {$x == 1}] } set t1 {} for {set i 1} {[llength $t1] < 50} {incr i} { if [humble? $i] {lappend t1 $i} } puts $t1  
Give a code snippet in #Tcl Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above i...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#Elisa
Elisa
component FormalPowerSeries(Number); type PowerSeries; PowerSeries(Size = integer) -> PowerSeries;   + PowerSeries -> PowerSeries; - PowerSeries -> PowerSeries;   PowerSeries + PowerSeries -> PowerSeries; PowerSeries - PowerSeries -> PowerSeries; PowerSeries * PowerSeries ...
Give a code snippet in #Elisa A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc.,...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Smalltalk
Smalltalk
|forward reverse composer compounds| "commodities" Number extend [ cube [ ^self raisedTo: 3 ] ]. Number extend [ cubeRoot [ ^self raisedTo: (1 / 3) ] ].   forward := #( #cos #sin #cube ). reverse := #( #arcCos #arcSin #cubeRoot ).   composer := [ :f :g | [ :x | f value: (g value: x) ] ].   "let us create composed...
Give a code snippet in #Smalltalk A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to oth...
christopher/rosetta-code