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/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#REXX
REXX
/*REXX program expresses a lighted sphere with simple characters used for shading. */ call drawSphere 19, 4, 2/10, '30 30 -50' /*draw a sphere with a radius of 19. */ call drawSphere 10, 2, 4/10, '30 30 -50' /* " " " " " " " ten. */ exit ...
Give a code snippet in #REXX Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Dea...
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 ≤...
#Emojicode
Emojicode
🏁🍇 🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string 🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space 🍺🔢 🐽 nums 0❗ 10❗ ➡️ A 💭 Retrieve first number 🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number 😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum 🍉️
Give a code snippet in #Emojicode 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, sepa...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#uBasic.2F4tH
uBasic/4tH
C=0   For I = 1 Step 1 Until C = 20 ' First 20 Harshad numbers If FUNC(_FNHarshad(I)) Then Print I;" "; : C = C + 1 Next   For I = 1001 Step 1 ' First Harshad greater than 1000 If FUNC(_FNHarshad(I)) Then Print I;" " : Break Next   End   _FNHarshad Param(1) Local(2)   c@ = a@ b@ = ...
Give a code snippet in #uBasic.2F4tH The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Joy
Joy
DEFINE hanoi == [[rolldown] infra] dip [ [ [null] [pop pop] ] [ [dup2 [[rotate] infra] dip pred] [ [dup rest put] dip [[swap] infra] dip pred ] [] ] ] condnestrec.
Give a code snippet in #Joy Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a 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. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Scala
Scala
/* Query.scala */ object Query { def call(data: Array[Byte], length: Array[Int]): Boolean = { val message = "Here am I" val mb = message.getBytes("utf-8") if (length(0) >= mb.length) { length(0) = mb.length System.arraycopy(mb, 0, data, 0, mb.length) true } else false } }
Give a code snippet in #Scala This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Phix
Phix
without js -- (file i/o) include pSQLite.e constant sqlcode = """ CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL)""" sqlite3 db = sqlite3_open("address.sqlite") integer res = sqlite3_exec(...
Give a code snippet in #Phix Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state cod...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#COBOL
COBOL
>>SOURCE FORMAT IS FIXED IDENTIFICATION DIVISION. PROGRAM-ID. EULER. DATA DIVISION. WORKING-STORAGE SECTION. 01 EPSILON USAGE COMPUTATIONAL-2 VALUE 1.0E-15. 01 FACT USAGE BINARY-DOUBLE UNSIGNED VALUE 1. 01 N USAGE BINARY-INT UNSIGNED. 01 E U...
Give a code snippet in #COBOL Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#NS-HUBASIC
NS-HUBASIC
10 I=1024 20 IF I=0 THEN END 30 PRINT I 40 I=I/2 50 GOTO 20
Give a code snippet in #NS-HUBASIC Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#PHP
PHP
<?PHP ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT JANUARY FEBRUARY MARCH APRIL MAY JUNE MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA S...
Give a code snippet in #PHP Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code...
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...
#Ruby
Ruby
class Maze DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]   def initialize(width, height) @width = width @height = height @start_x = rand(width) @start_y = 0 @end_x = rand(width) @end_y = height - 1   # Which walls do exist? Default to "true". Both arrays are # one element ...
Give a code snippet in #Ruby 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#zkl
zkl
fcn alignment(a,b){ a,b = a.toLower(), b.toLower(); costs := (a.len()+1).pump(List(),'wrap(a){ [1..b.len()].pump(List(a)) }); foreach i,j in (a.len()+1, [1..b.len()]){ costs[i][j] = ( 1 + costs[i-1][j].min(costs[i][j-1]) ) .min(if(a[i-1] == b[j-1]) costs[i-1][j-1] else costs[i-1][j-1] + 1); ...
Give a code snippet in #zkl The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to d...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Lua
Lua
local N = 2 local base = 10 local c1 = 0 local c2 = 0   for k = 1, math.pow(base, N) - 1 do c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 io.write(k .. ' ') end end   print() print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 10...
Give a code snippet in #Lua Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Dyalect
Dyalect
var t = (x: 1, y: 2, z: 3) print(t.Keys().ToArray())
Give a code snippet in #Dyalect Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Selectively_replace_multiple_instances_of_a_character_within_a_string
Selectively replace multiple instances of a character within a string
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' the fifth 'a' with 'D' the first 'b...
#Lambdatalk
Lambdatalk
the first 'a' with 'A' -> aA1 ...and so on
Give a code snippet in #Lambdatalk Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: the first 'a' with 'A' the second 'a' with 'B' the fourth 'a' with 'C' ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Bracmat
Bracmat
  double=.!arg+!arg;   (=.!arg+!arg):(=?double); { inverted assignment syntax, same result as above. }  
Give a code snippet in #Bracmat Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Wren
Wren
import "/ioutil" for FileUtil, Input import "/pattern" for Pattern import "/str" for Str import "os" for Process   var invIndex = {} var fileNames = [] var splitter = Pattern.new("+1/W")   class Location { construct new(fileName, wordNum) { _fileName = fileName _wordNum = wordNum }   toStrin...
Give a code snippet in #Wren An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ter...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#C.23
C#
  using System; using System.Linq;   namespace PopulationCount { class Program { private static int PopulationCount(long n) { string binaryn = Convert.ToString(n, 2); return binaryn.ToCharArray().Where(t => t == '1').Count(); }   static void Main(string[] ...
Give a code snippet in #C.23 Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Oz
Oz
proc {SwapCells A B} Tmp = @A in A := @B B := Tmp end
Give a code snippet in #Oz 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/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...
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON@   BEGIN DECLARE VAL INTEGER; LOOP: WHILE (TRUE = TRUE) DO SET VAL = INTEGER(RAND() * 20); CALL DBMS_OUTPUT.PUT_LINE(VAL); IF (VAL = 10) THEN LEAVE LOOP; END IF; SET VAL = INTEGER(RAND() * 20); CALL DBMS_OUTPUT.PUT_LINE(VAL); END WHILE LOOP; END @  
Give a code snippet in #SQL_PL 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#Smalltalk
Smalltalk
#( (54 546 548 60) (1 34 3 98 9 76 45 4) ) do:[:ints | |resultString|   "sort ints by padded strings (sort a copy - literals are immudatble), then collect their strings, then concatenate" resultString := ((ints copy sort:[:a :b | |pad| pad := (...
Give a code snippet in #Smalltalk Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Objeck
Objeck
class CastingNines { function : Main(args : String[]) ~ Nil { base := 10; N := 2; c1 := 0; c2 := 0;   for (k:=1; k<base->As(Float)->Power(N->As(Float)); k+=1;){ c1+=1; if (k%(base-1) = (k*k)%(base-1)){ c2+=1; IO.Console->Print(k)->Print(" "); }; };   IO.Co...
Give a code snippet in #Objeck Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Beads
Beads
beads 1 program 'Identity matrix'   var id : array^2 of num n = 5   calc main_init loop from:1 to:n index:i loop from:1 to:n index:j id[i,j] = 1 if i == j else 0
Give a code snippet in #Beads Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Vedit_macro_language
Vedit macro language
Repeat(10) { BOL Reg_Empty(20) While (!At_EOL) { Match("(.)\1*", REGEXP+ADVANCE) Num_Str(Chars_Matched, 20, LEFT+APPEND) Reg_Copy_Block(20, CP-1, CP, APPEND) } Ins_Newline Reg_Ins(20) }
Give a code snippet in #Vedit_macro_language The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number ...
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...
#Kabap
Kabap
  // Loop that spits lyrics to "99 Bottles of Beer"   $n = 99; $out = "";   :loop; $out = $out << $n << " bottles of beer on the wall, " << $n << " bottles of beer. Take one down, pass it around, " << $n - 1 << " bottles of beer on the wall… "; $n = $n - 1; if $n > 0; goto loop;   return = $out;  
Give a code snippet in #Kabap 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/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AutoHotkey
AutoHotkey
Gui, Add, Edit, va, 5 Gui, Add, Edit, vb, -3 Gui, Add, Button, Default, Compute Gui, Show Return   ButtonCompute: Gui, Submit MsgBox,% (Join`s"`n" a "+" b " = " a+b a "-" b " = " a-b a "*" b " = " a*b a "//" b " = " a//b " remainder " Mod(a,b) a "**" b " = " a**b ) ; fallthrough GuiClose: ExitA...
Give a code snippet in #AutoHotkey 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/Pointers_and_references
Pointers and references
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 |...
#C.2B.2B
C++
int* pointer2(&var);
Give a code snippet in #C.2B.2B 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program appendstr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#Lambdatalk
Lambdatalk
  {def str World} -> str   Hello, {str} -> Hello, World  
Give a code snippet in #Lambdatalk 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/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Quackery
Quackery
[ 0 swap behead swap witheach [ 2dup > iff [ nip nip i^ 1+ swap ] else drop ] drop ] is least ( [ --> n )   [ [] swap dup size times [ dup least pluck swap dip join ] drop ] is ssort ( [ --> [ )   [] 20 times [ 10...
Give a code snippet in #Quackery Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Crystal
Crystal
struct Int def evil? self >= 0 && popcount.even? end end   puts "Powers of 3:", (0...30).map{|n| (3u64 ** n).popcount}.join(' ') # can also use &** (to prevent arithmetic overflow) puts "Evil:" , 0.step.select(&.evil?).first(30).join(' ') puts "Odious:", 0.step.reject(&.evil?).first(30).join(' ')
Give a code snippet in #Crystal Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop cou...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Ada
Ada
with Ada.Float_Text_IO; with Ada.Text_IO; with Ada.Numerics.Discrete_Random; procedure Game_24 is subtype Digit is Character range '1' .. '9'; package Random_Digit is new Ada.Numerics.Discrete_Random (Digit); Exp_Error : exception; Digit_Generator : Random_Digit.Generator; Given_Digits : array (1 .. 4) o...
Give a code snippet in #Ada The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digi...
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.
#Tcl
Tcl
proc addsub {x y} { list [expr {$x+$y}] [expr {$x-$y}] }
Give a code snippet in #Tcl Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
firstyear = 2000; lastyear = 2099; years = Range[firstyear, lastyear]; firstday = Table[DayName[{years[[n]], 01, 01}], {n, Length[years]}]; lastday = Table[DayName[{years[[n]], 12, 31}], {n, Length[years]}]; Table[If[years[[n]] >= 1582, If[firstday[[n]] == Thursday || lastday[[n]] == Thursday, Style[years[[n]] "...
Give a code snippet in #Mathematica.2FWolfram_Language Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Java
Java
public class Levenshtein {   public static int distance(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); // i == 0 int [] costs = new int [b.length() + 1]; for (int j = 0; j < costs.length; j++) costs[j] = j; for (int i = 1; i <= a.length();...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Erlang
Erlang
let sl : string list = [null; "abc"]   let f s = match s with | null -> "It is null!" | _ -> "It's non-null: " + s   for s in sl do printfn "%s" (f s)
Give a code snippet in #Erlang Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#BBC_BASIC
BBC BASIC
@% = &60B RPN$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +"   DIM Stack(1000) SP% = 0   FOR i% = 1 TO LEN(RPN$) Token$ = MID$(RPN$,i%,1) IF Token$ <> " " THEN PRINT Token$ " :"; CASE Token$ OF WHEN "+": PROCpush(FNpop + FNpop) WHEN "-": PROCpush...
Give a code snippet in #BBC_BASIC Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Nanoquery
Nanoquery
n = 0   while not (n ^ 2 % 1000000) = 269696 n += 1 end   println n
Give a code snippet in #Nanoquery Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic ...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. 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, Euler's identity is the equality: ...
#Groovy
Groovy
import static Complex.*   Number.metaClass.mixin ComplexCategory   def π = Math.PI def e = Math.E   println "e ** (π * i) + 1 = " + (e ** (π * i) + 1)   println "| e ** (π * i) + 1 | = " + (e ** (π * i) + 1).ρ
Give a code snippet in #Groovy This page uses content from Wikipedia. The original article was at Euler's_identity. 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, Euler's identity...
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...
#K
K
f:{[a1;a2;b1;b2;s] b1+(s-a1)*(b2-b1)%(a2-a1)}   +(a; f[0;10;-1;0]'a:!11) ((0;-1.0) (1;-0.9) (2;-0.8) (3;-0.7) (4;-0.6) (5;-0.5) (6;-0.4) (7;-0.3) (8;-0.2) (9;-0.1) (10;0.0))
Give a code snippet in #K 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 mappe...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Perl
Perl
use strict; use warnings; use GD;   my $file = '/tmp/one-pixel-screen-capture.png';   system "screencapture -R 123,456,1,1 $file";   my $image = GD::Image->newFromPng($file); my $index = $image->getPixel(0,0); my($red,$green,$blue) = $image->rgb($index); print "RGB: $red, $green, $blue\n";   unlink $file;
Give a code snippet in #Perl Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_turtle_graphics
Simple turtle graphics
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. See imag...
#Python
Python
from turtle import *   def rectangle(width, height): for _ in range(2): forward(height) left(90) forward(width) left(90)   def square(size): rectangle(size, size)   def triangle(size): for _ in range(3): forward(size) right(120)   def house(size): right(18...
Give a code snippet in #Python The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might b...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Rascal
Rascal
  public int gcd_iterative(int a, b){ if(a == 0) return b; while(b != 0){ if(a > b) a -= b; else b -= a;} return a; }  
Give a code snippet in #Rascal Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#Cowgol
Cowgol
# Truth table generator in Cowgol # - # This program will generate a truth table for the Boolean expression # given on the command line. # # The expression is in infix notation, and operator precedence is impemented, # i.e., the following expression: # A & B | C & D => E # is parsed as: # ((A & B) | (C & D...
Give a code snippet in #Cowgol A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Stata
Stata
. scalar a="ha" . scalar b=a*5 . display b hahahahaha
Give a code snippet in #Stata Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Java
Java
import java.lang.reflect.*;   class Example { private String _name; public Example(String name) { _name = name; } public String toString() { return "Hello, I am " + _name; } }   public class BreakPrivacy { public static final void main(String[] args) throws Exception { Example foo = new Example("Eric");   for (...
Give a code snippet in #Java Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool mi...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Applesoft_BASIC
Applesoft BASIC
1 DATA248,169,153,24,105,1,48 2 DATA6,24,251,144,2,251,56 3 DATA216,105,0,133,251,96 4 FOR I = 768 TO 787 5 READ B: POKE I,B: NEXT 6 CALL 768:M = PEEK (251) 7 PRINT " WORD SIZE: "; 8 IF NOT M THEN PRINT 8 9 M$ = "HYBRID 8/16" 10 IF M THEN PRINT M$ 11 PRINT "ENDIANNESS: "; 12 PRINT "LITTLE-ENDIAN"
Give a code snippet in #Applesoft_BASIC Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#Swift
Swift
let a = [1,2,1,3,2] let b = [1,2,0,4,4,0,0,0] println(lexicographicalCompare(a, b)) // this is "less than"
Give a code snippet in #Swift sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   + (NSArray *)powerSetForArray:(NSArray *)array { UInt32 subsetCount = 1 << array.count; NSMutableArray *subsets = [NSMutableArray arrayWithCapacity:subsetCount]; for(int subsetIndex = 0; subsetIndex < subsetCount; subsetIndex++) { NSMutableArray *subset = [[NSMutableArray alloc]...
Give a code snippet in #Objective-C A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. ...
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.
#AutoIt
AutoIt
  Func _AddSub($iX, $iY) Local $aReturn[2] $aReturn[0] = $iX + $iY $aReturn[1] = $iX - $iY Return $aReturn EndFunc  
Give a code snippet in #AutoIt Task Show how to return more than one value from a function.
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.
#Swift
Swift
let a = 1 a = 1 // error: a is immutable var b = 1 b = 1
Give a code snippet in #Swift 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/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Astro
Astro
fun caesar(s, k, decode: false): if decode: k = 26 - k result = '' for i in s.uppercase() where 65 <= ord(i) <= 90: result.push! char(ord(i) - 65 + k) mod 26 + 65 return result   let message = "The quick brown fox jumped over the lazy dogs" let encrypted = caesar(msg, 11) let decrypted =...
Give a code snippet in #Astro Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Perl
Perl
use IO::Socket; my $use_fork = 1;   my $sock = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => '12321', Proto => 'tcp', Listen => 1, # maximum queued connections ...
Give a code snippet in #Perl Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#OCaml
OCaml
val argv : string array (** The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. *)   val executable_name : string (** The name of the file containing the executable current...
Give a code snippet in #OCaml Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/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
#AppleScript
AppleScript
try set num to 1 / 0 --do something that might throw an error end try
Give a code snippet in #AppleScript 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   Exce...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Ruby
Ruby
class Integer   def popcount digits(2).count(1) #pre Ruby 2.4: self.to_s(2).count("1") end   def evil? self >= 0 && popcount.even? end   end   puts "Powers of 3:", (0...30).map{|n| (3**n).popcount}.join(' ') puts "Evil:" , 0.step.lazy.select(&:evil?).first(30).join(' ') puts "Odious:", 0.step.lazy...
Give a code snippet in #Ruby Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Int-Compare.   DATA DIVISION. WORKING-STORAGE SECTION. 01 A PIC 9(10). 01 B PIC 9(10).   PROCEDURE DIVISION. DISPLAY "First number: " WITH NO ADVANCING ACCEPT A DISPLAY "Second number: " WITH NO ADVA...
Give a code snippet in #COBOL 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/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Java
Java
import java.math.BigInteger; public class Mersenne {   public static boolean isPrime(int p) { if (p == 2) return true; else if (p <= 1 || p % 2 == 0) return false; else { int to = (int)Math.sqrt(p); for (int i = 3; i <= to; i += 2) ...
Give a code snippet in #Java Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly L_ALPHABET As String = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" ReadOnly R_ALPHABET As String = "PTLNBQDEOYSFAVZKGJRIHWXUMC"   Enum Mode ENCRYPT DECRYPT End Enum   Function Exec(text As String, mode As Mode, Optional showSteps As Boolean = False) As String Dim l...
Give a code snippet in #Visual_Basic_.NET Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 20...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#TSE_SAL
TSE SAL
    // library: math: create: array: spiral: inwards <description></description> <version control></version control> <version>1.0.0.0.15</version> (filenamemacro=creamasi.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 01:15:43] PROC PROCMathCreateArraySpiralInwards( INTEGER nI ) // e.g. PROC Main() // e.g. STRIN...
Give a code snippet in #TSE_SAL Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 ...
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 |...
#Quackery
Quackery
[ 1 [ 2dup < not while 2 << again ] 0 [ over 1 > while dip [ 2 >> 2dup - ] dup 1 >> unrot - dup 0 < iff drop else [ 2swap nip rot over + ] again ] nip swap ] is isqrt ( n --> n n )   [ [] swap dup isqrt 0 = dip [ times [ d...
Give a code snippet in #Quackery Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Delphi
Delphi
program SortCompositeStructures;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections, Generics.Defaults;   type TStructurePair = record name: string; value: string; constructor Create(const aName, aValue: string); end;   constructor TStructurePair.Create(const aName, aValue: string); begin name...
Give a code snippet in #Delphi 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/Hunt_the_Wumpus
Hunt the Wumpus
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. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Nim
Nim
import random, strformat, strutils   type Adjacent = array[3, int]   const Cave: array[1..20, Adjacent] = [ 1: [2, 3, 4], 2: [1, 5, 6], 3: [1, 7, 8], 4: [1, 9, 10], 5: [2, 9, 11], 6: [2, 7, 12], 7: [3, 6, 13], 8: [3, 10, 14], 9: [4, 5, 15], 10: [4, 8, 16], 11: [5, 12, 17], 12: ...
Give a code snippet in #Nim 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. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Pascal
Pascal
PROGRAM EVOLUTION (OUTPUT);   CONST TARGET = 'METHINKS IT IS LIKE A WEASEL'; COPIES = 100; (* 100 children in each generation. *) RATE = 1000; (* About one character in 1000 will be a mutation. *)   TYPE STRLIST = ARRAY [1..COPIES] OF STRING;   FUNCTION RANDCHAR : CHAR; (* Generate a random letter or space. *) ...
Give a code snippet in #Pascal Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of it...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 print "Mode 1 (4 colors):" 30 for y=0 to 3 40 for x=0 to 3 50 pen x:paper y:print "Test"; 60 next 70 print 80 next 90 pen 1:paper 0 100 locate 1,25:print "<Press any key>";:call &bb06 110 ink 1,8,26 120 ink 2,21,17 130 locate 1,25:print "Flashing inks --- <Press any key>";:call &bb06 140 speed i...
Give a code snippet in #Locomotive_Basic Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colo...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Mercury
Mercury
:- module symdiff. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module list, set, string.   main(!IO) :- A = set(["John", "Bob", "Mary", "Serena"]), B = set(["Jim", "Mary", "John", "Bob"]), print_set("A\\B", DiffAB @ (A `difference` B), !IO), p...
Give a code snippet in #Mercury Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#BBC_BASIC
BBC BASIC
REM Store some values with their keys: PROCputdict(mydict$, "FF0000", "red") PROCputdict(mydict$, "00FF00", "green") PROCputdict(mydict$, "0000FF", "blue")   REM Iterate through the dictionary: i% = 1 REPEAT i% = FNdict(mydict$, i%, v$, k$) PRINT v$, k$ UN...
Give a code snippet in #BBC_BASIC Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections ...
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...
#PARI.2FGP
PARI/GP
while(1, t=random(20); print(t); if(t==10, break); print(random(20)) )
Give a code snippet in #PARI.2FGP 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 loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ol
Ol
; short version based on 'apply' (define (matrix-multiply matrix1 matrix2) (map (lambda (row) (apply map (lambda column (apply + (map * row column))) matrix2)) matrix1))  
Give a code snippet in #Ol Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Elixir
Elixir
defmodule Knuth do def shuffle( inputs ) do n = length( inputs ) {[], acc} = Enum.reduce( n..1, {inputs, []}, &random_move/2 ) acc end   defp random_move( n, {inputs, acc} ) do item = Enum.at( inputs, :rand.uniform(n)-1 ) {List.delete( inputs, item ), [item | acc]} end end   seq = Enum.to_li...
Give a code snippet in #Elixir The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#ooRexx
ooRexx
/* Rexx */ say say 'Loops/Foreach' out = ''   days = .array~of('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')   loop daysi over days out ||= daysi' ' end daysi say out~strip()   exit
Give a code snippet in #ooRexx Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loop...
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.)
#Swift
Swift
// this is a single line comment /* This a block comment /* containing nested comment */ */   ///This is a documentation comment   /** This is a documentation block comment */
Give a code snippet in #Swift 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/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Lua
Lua
-- Return entire contents of named file function readFile (filename) local file = assert(io.open(filename, "r")) local contents = file:read("*all") file:close() return contents end   -- Return a closure to keep track of letter counts function tally () local t = {}   -- Add x to tally if supplied, return tal...
Give a code snippet in #Lua Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assig...
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
#Erlang
Erlang
-module(format_date). -export([iso_date/0, iso_date/1, iso_date/3, long_date/0, long_date/1, long_date/3]). -import(calendar,[day_of_the_week/1]). -import(io,[format/2]). -import(lists,[append/1]).   iso_date() -> iso_date(date()). iso_date(Year, Month, Day) -> iso_date({Year, Month, Day}). iso_date(Date) -> format("...
Give a code snippet in #Erlang 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/Undefined_values
Undefined values
#D
D
void main() { // Initialized: int a = 5; double b = 5.0; char c = 'f'; int[] d = [1, 2, 3];   // Default initialized: int aa; // set to 0 double bb; // set to double.init, that is a NaN char cc; // set to 0xFF int[] dd; // set to null int[3] ee; // set to [0, 0, 0]   // U...
Give a code snippet in #D
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Lua
Lua
function f (x) return math.abs(x)^0.5 + 5*x^3 end   function reverse (t) local rev = {} for i, v in ipairs(t) do rev[#t - (i-1)] = v end return rev end   local sequence, result = {} print("Enter 11 numbers...") for n = 1, 11 do io.write(n .. ": ") sequence[n] = io.read() end for _, x in ipairs(rever...
Give a code snippet in #Lua The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, g...
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...
#Raku
Raku
my @cities = { name => 'Lagos', population => 21.0 }, { name => 'Cairo', population => 15.2 }, { name => 'Kinshasa-Brazzaville', population => 11.3 }, { name => 'Greater Johannesburg', population => 7.55 }, { name => 'Mogadishu', population => 5.85 }, { name => ...
Give a code snippet in #Raku 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[ed...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Groovy
Groovy
import groovy.transform.TupleConstructor   enum Pip { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } enum Suit { DIAMONDS, SPADES, HEARTS, CLUBS }   @TupleConstructor class Card { final Pip pip final Suit suit   String toString() { "$pip of $suit" } }   class Deck { ...
Give a code snippet in #Groovy Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#R
R
  options(digits=22) cat("e =",sum(rep(1,20)/factorial(0:19)))  
Give a code snippet in #R Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Run_BASIC
Run BASIC
suite$ = "C,D,H,S" ' Club, Diamond, Heart, Spade card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King   dim n(55) ' make ordered deck for i = 1 to 52 ' of 52 cards n(i) = i next i   for i = 1 to 52 * 3 ' shuffle de...
Give a code snippet in #Run_BASIC Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curre...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Lasso
Lasso
  local( myfile = file('//path/to/file.txt'), textresult = array )   #myfile -> foreachline => { #textresult -> insert(#1) }   #textresult -> join('<br />')
Give a code snippet in #Lasso Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
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.)
#Chef
Chef
Comment Stew.   This is a comment. The other comment is a loop, but you can name it anything (single word only). You can also name ingredients as comments This is pseudocode.   Ingredients. Ingredient list   Method. Methods. SingleWordCommentOne the Ingredient. Methods. SingleWordCommentTwo until SingleWordCommentOned....
Give a code snippet in #Chef 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/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#REXX
REXX
/*REXX program tests the MD5 procedure (below) as per a test suite the IETF RFC (1321).*/ msg.1 = /*─────MD5 test suite [from above doc].*/ msg.2 = 'a' msg.3 = 'abc' msg.4 = 'message digest' msg.5 = 'abcdefghijklmnopqrstuvwxyz' msg.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno...
Give a code snippet in #REXX Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the W...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Quackery
Quackery
[ over 3 < if [ 1 - ] dup 4 / over + over 100 / - swap 400 / + swap 1 - [ table 0 3 2 5 0 3 5 1 4 6 2 4 ] + + 7 mod ] is dayofweek ( day month year --> weekday )   [ dup 400 mod 0 = iff [ drop true ] done dup 100 mod 0 = iff [ drop false ] ...
Give a code snippet in #Quackery Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#M2000_Interpreter
M2000 Interpreter
  \\ old style Basic, including a Binary.Or() function Module OldStyle { 10 LET A$="" 20 FOR I=ASC("A") TO ASC("Z") 30 LET A$=A$+CHR$(BINARY.OR(I, 32)) 40 NEXT I 50 PRINT A$ } CALL OldStyle  
Give a code snippet in #M2000_Interpreter Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#ERRE
ERRE
SHELL("DIR/W")
Give a code snippet in #ERRE Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#QB64
QB64
  'Task 'Simulate/translate the above PL/I program snippet as best as possible ' in your language, with particular emphasis on the do loop ' construct. 'The do index must be incremented/decremented in the same order shown. 'If feasible, add commas to the two output numbers (being displayed). 'Show all output ...
Give a code snippet in #QB64 Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED a...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#XPL0
XPL0
IntOut(0, ^a); \(Integer Out) displays "97" on the console (device 0) ChOut(0, 97); \(Character Out) displays "a" on the console (device 0)
Give a code snippet in #XPL0 Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Phix
Phix
-- -- demo\rosetta\Cursor_movement.exw -- ================================ -- -- These may vary by platform/hardware... (this program is ideal for sorting such things out) -- constant HOME = 327, END = 335, UP = 328, DOWN = 336, LEFT = 331, RIGHT = 333, PGUP...
Give a code snippet in #Phix Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (witho...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#BASIC256
BASIC256
subroutine Evaluation() lo = 1 : hi = 100 : temp = 0 for i = lo to hi temp += (1/i) ##r(i) next i print temp end subroutine   call Evaluation() end
Give a code snippet in #BASIC256 Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying 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.
#PL.2FI
PL/I
  /* PL/I does not have an assert function as such, */ /* but it is something that can be implemented in */ /* any of several ways. A straight-forward way */ /* raises a user-defined interrupt. */   on condition (assert_failure) snap put skip list ('Assert failure'); .... if a ^= b then signal condition(assert_fa...
Give a code snippet in #PL.2FI 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/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#APL
APL
∇ {res}←Trabb;f;S;i;a;y ⍝ define a function Trabb f←{(0.5*⍨|⍵)+5×⍵*3} ⍝ define a function f S←,⍎{⍞←⍵ ⋄ (≢⍵)↓⍞}'Please, enter 11 numbers: '  :For i a :InEach (⌽⍳≢S)(⌽S) ⍝ loop through N..1 and reversed S  :If 400<y←f(a) ⎕←'Too large: ',⍕i  :Else ⎕←i,y...
Give a code snippet in #APL The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, g...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Prolog
Prolog
:-use_module(library(lambda)).     closure :- numlist(1,10, Lnum), maplist(make_func, Lnum, Lfunc), maplist(call_func, Lnum, Lfunc).     make_func(I, \X^(X is I*I)).   call_func(N, F) :- call(F, R), format('Func ~w : ~w~n', [N, R]).  
Give a code snippet in #Prolog Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Quackery
Quackery
[ char [ over of swap char ] swap of join shuffle ] is bracket$ ( n --> $ )   [ 0 swap witheach [ char [ = iff 1 else -1 + dup 0 < if conclude ] 0 = ] is balanced ( $ --> b )     10 times [ 20 i 2 * - times sp i bracket$ dup echo$ ...
Give a code snippet in #Quackery Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mi...
christopher/rosetta-code
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#REXX
REXX
/*REXX program demonstrates various ways to express a string of characters or numbers.*/ a= 'This is one method of including a '' (an apostrophe) within a string.' b= "This is one method of including a ' (an apostrophe) within a string."   /*sometimes, an apostrophe i...
Give a code snippet in #REXX Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Icon_and_Unicon
Icon and Unicon
link strings # for permutes   procedure main() givens := set![ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]   every insert(full := set(), permutes("ABCD")) # ge...
Give a code snippet in #Icon_and_Unicon ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Kotlin
Kotlin
fun main(a: Array<String>) { val map = mapOf("hello" to 1, "world" to 2, "!" to 3)   with(map) { entries.forEach { println("key = ${it.key}, value = ${it.value}") } keys.forEach { println("key = $it") } values.forEach { println("value = $it") } } }
Give a code snippet in #Kotlin Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#FBSL
FBSL
#APPTYPE CONSOLE   DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left...
Give a code snippet in #FBSL Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#BASIC
BASIC
REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM) A$ = "STRING" : REM CREATION A$ = "" : REM DESTRUCTION PRINT FRE(0) : REM GARBAGE COLLECTION   REM STRING ASSIGNMENT A$ = "STRING" : R$ = "DEUX"   REM STRING COMPARISON PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > B$; ...
Give a code snippet in #BASIC Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accor...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Prolog
Prolog
    %! directory_prefix(PATHs,STOP0,PREFIX)   directory_prefix([],_STOP0_,'') :- ! .   directory_prefix(PATHs0,STOP0,PREFIX) :- prolog:once(longest_prefix(PATHs0,STOP0,LONGEST_PREFIX)) -> prolog:atom_concat(PREFIX,STOP0,LONGEST_PREFIX) ; PREFIX='' .   %! longest_prefix(PATHs,STOP0,PREFIX)   longest_prefix(PATHs0,STOP0...
Give a code snippet in #Prolog Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Forth
Forth
  \ Triangle representation; words created by this defining word return the address of element \ specified by its row number and position within that row, both indexed from 0. : TRIANGLE ( "name" -- |DOES: row pos -- addr ) CREATE DOES> ROT DUP 1+ * 2/ CELLS + SWAP CELLS + ;   18 CONSTANT #ROWS \ total number of ...
Give a code snippet in #Forth Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such ...
christopher/rosetta-code