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/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Rust
Rust
fn main() { for i in 0..std::usize::MAX { println!("{:o}", i); } }
Give a code snippet in #Rust Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#11l
11l
T Puzzle position = 0 [Int = String] items   F main_frame() V& d = .items print(‘+-----+-----+-----+-----+’) print(‘|#.|#.|#.|#.|’.format(d[1], d[2], d[3], d[4])) print(‘+-----+-----+-----+-----+’) print(‘|#.|#.|#.|#.|’.format(d[5], d[6], d[7], d[8])) print(‘+-----+-----+---...
Give a code snippet in #11l Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Ksh
Ksh
  #!/bin/ksh   # Search a list of records   # # Variables: # json='{ "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogad...
Give a code snippet in #Ksh 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[edi...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#Axe
Axe
LINK(L₁,1)→A LINK(L₁+10,2)→B LINK(L₁+50,3)→C   INSERT(A,B) INSERT(A,C)   A→I While I≠0 Disp VALUE(I)▶Dec,i NEXT(I)→I End   Disp "-----",i   B→I While I≠0 Disp VALUE(I)▶Dec,i PREV(I)→I End
Give a code snippet in #Axe Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Rust
Rust
This version uses number->string then string->number conversions to create palindromes.
Give a code snippet in #Rust Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful num...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#REXX
REXX
/*REXX program applies a callback to an array (using factorials for a demonstration).*/ numeric digits 100 /*be able to display some huge numbers.*/ parse arg # . /*obtain an optional value from the CL.*/ a.= ...
Give a code snippet in #REXX Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Erlang
Erlang
  -module(acc_factory). -export([loop/1,new/1]).   loop(N)-> receive {P,I}-> S =N+I, P!S, loop(S) end.   new(N)-> P=spawn(acc_factory,loop,[N]), fun(I)-> P!{self(),I}, receive V-> V end end.  
Give a code snippet in #Erlang A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa...
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...
#Forth
Forth
: STRING, ( caddr len -- ) \ Allocate space & compile string into memory HERE OVER CHAR+ ALLOT PLACE ;   : " ( -- ) [CHAR] " PARSE STRING, ; \ Parse input to " and compile to memory   \ Array delimiter words : { ALIGN 0 C, ; \ Compile 0 byte start/end of array : } ALIGN 0 C,  ;   \...
Give a code snippet in #Forth 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 frequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <vector>   std::vector<int> findProperDivisors ( int n ) { std::vector<int> divisors ; for ( int i = 1 ; i < n / 2 + 1 ; i++ ) { if ( n % i == 0 ) divisors.push_back( i ) ; } return divisors ; }   int main( ) { std::vector<int> deficients , perf...
Give a code snippet in #C.2B.2B These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficie...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Lua
Lua
print("\33[?3h") -- 132-column text print("\33[?3l") -- 80-column text
Give a code snippet in #Lua The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Pascal
Pascal
var f : file ; // Untyped file begin   // as current directory AssignFile(f,'input.doc'); Rename(f,'output.doc');   // as root directory AssignFile(f,'\input.doc'); Rename(f,'\output.doc');   // rename a directory AssignFile(f,'docs'); Rename(f,'mydocs');   //rename a directory off the roo...
Give a code snippet in #Pascal Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Java
Java
import java.util.HashMap; public static void main(String[] args){ String[] keys= {"a", "b", "c"}; int[] vals= {1, 2, 3}; HashMap<String, Integer> hash= new HashMap<String, Integer>();   for(int i= 0; i < keys.length; i++){ hash.put(keys[i], vals[i]); } }
Give a code snippet in #Java Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Maxima
Maxima
if obj == undefined then print "Obj is undefined"
Give a code snippet in #Maxima 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/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinformatics/base count Count occurren...
#Rust
Rust
extern crate rand;   use rand::prelude::*; use std::io;   fn main() { let answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs p...
Give a code snippet in #Rust Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinformat...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#REXX
REXX
/*REXX program prompts the user for a template substitutions within a story (MAD LIBS).*/ parse arg iFID . /*allow user to specify the input file.*/ if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/ @.= ...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game wh...
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...
#zkl
zkl
"ha" * 5 # --> "hahahahaha"
Give a code snippet in #zkl 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/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#MATLAB_.2F_Octave
MATLAB / Octave
fid = fopen('/dev/lp0'); fprintf(fid,'Hello World!\n'); fclose(fid);
Give a code snippet in #MATLAB_.2F_Octave Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Action.21
Action!
DEFINE MAXSIZE="12"   INT ARRAY dxStack(MAXSIZE),dyStack(MAXSIZE) BYTE ARRAY depthStack(MAXSIZE),stageStack(MAXSIZE) BYTE stacksize=[0]   BYTE FUNC IsEmpty() IF stacksize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stacksize=MAXSIZE THEN RETURN (1) FI RETURN (0)   PROC Push(INT dx,dy BYTE depth,stag...
Give a code snippet in #Action.21 Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Free_Pascal
Free Pascal
program MACVendorLookup;   uses fphttpclient;   var res: String; begin if paramCount > 0 then begin   With TFPHttpClient.Create(Nil) do try allowRedirect := true; try res := Get('http://api.macvendors.com/' + ParamStr(1)); writeLn(res); except writeLn('N/A'); ...
Give a code snippet in #Free_Pascal Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public static class OrderedPartitions { public static void Main() { var input = new [] { new[] { 0, 0, 0, 0, 0 }, new[] { 2, 0, 2 }, new[] { 1, 1, 1 } }; foreach (int[] sizes in input) { foreach (var partition in Partit...
Give a code snippet in #C.23 In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Bracmat
Bracmat
( ( convert = . ("0.06"."0.10") ("0.11"."0.18") ("0.16"."0.26") ("0.21"."0.32") ("0.26"."0.38") ("0.31"."0.44") ("0.36"."0.50") ("0.41"."0.54") ("0.46"."0.58") ("0.51"."0.62") ...
Give a code snippet in #Bracmat A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   an...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Action.21
Action!
BYTE FUNC Max(BYTE ARRAY tab BYTE size) BYTE i,res   res=tab(0) FOR i=1 TO size-1 DO IF res<tab(i) THEN res=tab(i) FI OD RETURN (res)   PROC Main() BYTE i,m,size=[20] BYTE ARRAY tab(size)   FOR i=0 TO size-1 DO tab(i)=Rand(0) OD   Print("Array:") FOR i=0 TO size-1 DO Pr...
Give a code snippet in #Action.21 Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Relation
Relation
  function half(x) set result = floor(x/2) end function   function double(x) set result = 2*x end function   function even(x) set result = (x/2 > floor(x/2)) end function   program ethiopian_mul(a,b) relation first, second while a >= 1 insert a, b set a = half(a) set b = double(b) end while extend third = even(first) *...
Give a code snippet in #Relation 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, an...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Elm
Elm
import Element exposing (show, toHtml) -- elm-package install evancz/elm-graphics import Html.App exposing (beginnerProgram) import Array exposing (Array, append, initialize)     xs : Array Int xs = initialize 3 identity -- [0, 1, 2]   ys : Array Int ys = initialize 3 <| (+) 3 -- [3, 4, 5]   main = beginnerProgr...
Give a code snippet in #Elm Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified...
#Visual_Objects
Visual Objects
LOCAL oSoapClient AS OBJECT //OLEAUTOOBJECT LOCAL cUrl AS STRING LOCAL uResult AS USUAL oSoapClient := OLEAutoObject{"MSSOAP.SoapClient30"} cUrl  := "http://example.com/soap/wsdl" IF oSoapClient:fInit oSoapClient:mssoapinit(cUrl,"", "", "" ) uResult := oSoapClient:soapFunc("hello") uResult := o...
Give a code snippet in #Visual_Objects In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged inc...
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...
#Hoon
Hoon
|= arr=(list *) (lent arr)
Give a code snippet in #Hoon 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 freque...
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...
#11l
11l
F analyze(s) print(‘Examining [’s‘] which has a length of ’s.len‘:’) I s.len > 1 V b = s[0] L(c) s V i = L.index I c != b print(‘ Not all characters in the string are the same.’) print(‘ '’c‘' (0x’hex(c.code)‘) is different at position ’i) R ...
Give a code snippet in #11l 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 st...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Ada
Ada
loop Value := Value + 1; Put (Value); exit when Value mod 6 = 0; end loop;
Give a code snippet in #Ada Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Dow...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { x = "She was a soul stripper. She took my heart!"; print x; gsub(/[aei]/,"",x); print x; }
Give a code snippet in #AWK Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the...
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 ...
#Nemerle
Nemerle
using System.Console;   namespace RosettaCode { abstract class Fruit { abstract public Eat() : void; abstract public Peel() : void;   virtual public Cut() : void // an abstract class con contain a mixture of abstract and implemented methods { /...
Give a code snippet in #Nemerle 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 operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Ursala
Ursala
#import nat   insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD
Give a code snippet in #Ursala 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/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Wren
Wren
var s = "abc123" var t = "abc\t123\%" var u = "\U0001F64A\U0001F680" var v = "%("abc" * 3)" var w = """a"bc""def\n%(v)"""   System.print([s, t, u, v, w])
Give a code snippet in #Wren Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   ...
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...
#BBC_BASIC
BBC BASIC
@%=&1010   PRINT "Binomial (5,3) = "; FNbinomial(5, 3) PRINT "Binomial (100,2) = "; FNbinomial(100, 2) PRINT "Binomial (33,17) = "; FNbinomial(33, 17) END   DEF FNbinomial(N%, K%) LOCAL R%, D% R% = 1 : D% = N% - K% IF D% > K% THEN K% = D% : D% = N% - K% WHILE ...
Give a code snippet in #BBC_BASIC 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/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#J
J
suf=: (;:'th st nd rd th') {::~ 4 <. 10 10 (* 1&~:)~/@#: ] nth=: [: ;:inv (": , suf)each
Give a code snippet in #J Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show her...
christopher/rosetta-code
http://rosettacode.org/wiki/List_rooted_trees
List rooted trees
You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub bagchain { my($x, $n, $bb, $start) = @_; return [@$x] unless $n;   my @sets; $start //= 0; for my $i ($start .. @$bb-1) { my($c, $s) = @{$$bb[$i]}; push @sets, bagchain([$$x[0] + $c, $$x[1] . $s], $n-$c, $bb, $i) if $c <= $n } ...
Give a code snippet in #Perl You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Haskell
Haskell
import Data.List import Control.Arrow import Control.Monad   insertAt e k = uncurry(++).second ((e:).drop 1). splitAt k   swapElems :: [a] -> Int -> Int -> [a] swapElems xs i j = insertAt (xs!!j) i $ insertAt (xs!!i) j xs   stoogeSort [] = [] stoogeSort [x] = [x] stoogeSort xs = doss 0 (length xs - 1) xs doss :: (Ord ...
Give a code snippet in #Haskell 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/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#M2000_Interpreter
M2000 Interpreter
  Module Sets { setA=("apple", "cherry", "grape") setB=("banana","cherry", "date")   Print Len(setA)=3 'true Print setA#pos("apple")>=0=true ' exist Print setA#pos("banana")>=0=False ' not exist   intersection=lambda SetB (x$)-> SetB#pos(x$)>=0 SetC=SetA#filter(intersection,(,)) Print SetC   Difference= la...
Give a code snippet in #M2000_Interpreter Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#Haskell
Haskell
import Control.Concurrent (threadDelay) import Control.Exception (bracket_) import Control.Monad (forM_) import System.Console.Terminfo import System.IO (hFlush, stdout)   -- Use the terminfo database to write the terminal-specific characters -- for the given capability. runCapability :: Terminal -> String -> IO () run...
Give a code snippet in #Haskell Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Elixir
Elixir
defmodule Sort do def permutation_sort([]), do: [] def permutation_sort(list) do Enum.find(permutation(list), fn [h|t] -> in_order?(t, h) end) end   defp permutation([]), do: [[]] defp permutation(list) do for x <- list, y <- permutation(list -- [x]), do: [x|y] end   defp in_order?([], _), do: tru...
Give a code snippet in #Elixir 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/Order_disjoint_list_items
Order disjoint list items
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 ...
#Go
Go
package main   import ( "fmt" "sort" "strings" )   type indexSort struct { val sort.Interface ind []int }   func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i...
Give a code snippet in #Go 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/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#FBSL
FBSL
FUNCTION StrRev1(BYVAL $p1) DIM $b = "" REPEAT LEN(p1) b = b & RIGHT(p1,1) p1 = LEFT(p1,LEN(p1)-1) END REPEAT RETURN b END FUNCTION  
Give a code snippet in #FBSL Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];"; Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]];
Give a code snippet in #Mathematica.2FWolfram_Language Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbo...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ]) write() showTree("", " -", [1, [2,[3,[4]]], [5,[6],[7,[8],[9]],[10]] ]) end   procedure showTree(prefix, lastc, A) write(prefix, lastc, "--", A[1]) if *A > 1 then { prefix ||:= if prefix[-1] == "|" then " ...
Give a code snippet in #Icon_and_Unicon A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML table...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#jq
jq
def count(s): reduce s as $x (0; .+1);   # To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # Output: a possibly empty array of pairs def factor_pairs: . as $n | ($n / (10 | power($n|tostring|length / 2) - 1)) as $first | [range...
Give a code snippet in #jq A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   tog...
christopher/rosetta-code
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cyli...
#Nim
Nim
import algorithm, random, sequtils, strformat, strutils, tables   type Revolver = array[6, bool] Action {.pure.} = enum Load, Spin, Fire, Error   const Actions = {'L': Load, 'S': Spin, 'F': Fire}.toTable   func spin(revolver: var Revolver; count: Positive) = revolver.rotateLeft(-count)   func load(revolver: var R...
Give a code snippet in #Nim The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
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 ...
#Scala
Scala
def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] = if (input.isEmpty || used.size >= using.size) input else if (using diff used contains input.head) using(used.size) +: order(input.tail, using, used :+ input.head) else input.head +: order(input.tail, using, used)
Give a code snippet in #Scala 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#Maple
Maple
with(NumberTheory): for n to 30 do lprint(Phi(n,x)) od:   x-1 x+1 x^2+x+1 x^2+1 x^4+x^3+x^2+x+1 x^2-x+1 x^6+x^5+x^4+x^3+x^2+x+1 x^4+1 x^6+x^3+1 x^4-x^3+x^2-x+1 x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1 x^4-x^2+1 x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1 x^6-x^5+x^4-x^3+x^2-x+1 x^8-x^7+x^5-x^4+x^3-x+1 x^8+1 x^16...
Give a code snippet in #Maple The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode.BogoSort { public static class BogoSorter { public static void Sort<T>(List<T> list) where T:IComparable { while (!list.isSorted()) { list.Shuffle(); } }   ...
Give a code snippet in #C.23 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/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Julia
Julia
# v0.6 using IterTools   str = "gHHH5YY++///\\" sep = map(join, groupby(identity, str)) println("string: $str\nseparated: ", join(sep, ", "))
Give a code snippet in #Julia Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#TXR
TXR
(set-sig-handler sig-int (lambda (signum async-p) (throwf 'error "caught signal ~s" signum)))   (let ((start-time (time))) (catch (each ((num (range 1))) (format t "~s\n" num) (usleep 500000)) (error (msg) (let ((end-time (time))) (...
Give a code snippet in #TXR Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Julia
Julia
using Primes   ispernicious(n::Integer) = isprime(count_ones(n)) nextpernicious(n::Integer) = begin n += 1; while !ispernicious(n) n += 1 end; return n end function perniciouses(n::Int) rst = Vector{Int}(n) rst[1] = 3 for i in 2:n rst[i] = nextpernicious(rst[i-1]) end return rst end pernicio...
Give a code snippet in #Julia A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Haskell
Haskell
import Data.List (genericLength) import Control.Monad (zipWithM_)   mean :: Double -> [Double] -> Double mean 0 xs = product xs ** (1 / genericLength xs) mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p)   main = do let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1] mapM_ (\(t,m) -> putS...
Give a code snippet in #Haskell Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\l...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Locomotive_Basic
Locomotive Basic
10 CLS 20 INPUT "Number of rows? ", rows:GOSUB 40 30 END 40 FOR i=0 TO rows-1 50 c=1 60 FOR k=0 TO i 70 PRINT USING "####";c; 80 c=c*(i-k)/(k+1) 90 NEXT 100 PRINT 110 NEXT 120 RETURN
Give a code snippet in #Locomotive_Basic Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each ro...
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...
#F.23
F#
for i in [1 .. 10] do printfn "%d" i   List.iter (fun i -> printfn "%d" i) [1 .. 10]
Give a code snippet in #F.23 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/...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Wren
Wren
import "io" for Stdin, Stdout   Stdin.isRaw = true // input is neither echoed nor buffered in this mode   System.print("Press Y or N") Stdout.flush()   var byte while ((byte = Stdin.readByte()) && !"YNyn".bytes.contains(byte)) {} var yn = String.fromByte(byte) System.print(yn)   Stdin.isRaw = false
Give a code snippet in #Wren Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed,...
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...
#UNIX_Shell
UNIX Shell
tput cub1 # one position to the left tput cuf1 # one position to the right tput cuu1 # up one line tput cud1 # down one line tput cr # beginning of line tput home # top left corner   # For line ends and bottom, we ne...
Give a code snippet in #UNIX_Shell 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Rust
Rust
fn main() { for i in 0..5 { for _ in 0..=i { print!("*"); }   println!(); } }
Give a code snippet in #Rust “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[AllSameCharacters] AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf}, If[Length[c] > 1, tf = AllTrue[Rest[c], (i++; # == First[c]) &]; If[tf, Print["input = \"", s, "\", Length = ", StringLength[s], ", All the same!"] , Print["input = \"", s, "\", Length = ", ...
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological 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 ...
#Icon_and_Unicon
Icon and Unicon
record graph(nodes,arcs) global ex_name, in_name   procedure main() show(tsort(getgraph())) end   procedure tsort(g) t := "" while (n := g.nodes -- pnodes(g)) ~== "" do { t ||:= "("||n||")" g := delete(g,n) } if g.nodes == '' then return t write("graph contains the cycle:") write("\t...
Give a code snippet in #Icon_and_Unicon 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/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Run_BASIC
Run BASIC
msg$ = "There have been no clicks yet" [loop] cls ' clear screen print msg$ button #c, "Click Me", [clickMe] 'create a button with handle and goto [tag] wait   [clickMe] clicks = clicks + 1 msg$ = "Button has been clicked ";clicks;" times" goto [loop]
Give a code snippet in #Run_BASIC Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_algorithm_S
Knuth's algorithm S
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam...
#zkl
zkl
fcn s_of_n_creator(n){ fcn(item,ri,N,samples){ i:=ri.inc(); // 1,2,3,4,... if(i<=N) samples.append(item); else if ((0).random(i) < N) samples[(0).random(N)] = item; samples }.fp1(Ref(1),n,L()) }
Give a code snippet in #zkl This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although ...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#MAD
MAD
NORMAL MODE IS INTEGER   R INTEGER SQUARE ROOT OF X   INTERNAL FUNCTION(X) ENTRY TO ISQRT. Q = 1 FNDPW4 WHENEVER Q.LE.X Q = Q * 4 TRANSFER TO FNDPW4 END OF CONDITIONAL Z = X R = 0 FNDRT ...
Give a code snippet in #MAD Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer p...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Vedit_macro_language
Vedit macro language
Translate_Load("ROT13.TBL") Translate_Block(0, File_Size)
Give a code snippet in #Vedit_macro_language Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line...
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#Ruby
Ruby
Point = Struct.new(:x,:y) do def to_s; "(#{x}, #{y})" end end   def sutherland_hodgman(subjectPolygon, clipPolygon) # These inner functions reduce the argument passing to # "inside" and "intersection". cp1, cp2, s, e = nil inside = proc do |p| (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) end ...
Give a code snippet in #Ruby The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Phix
Phix
with javascript_semantics for base=9 to 12 do printf(1,"The factorions for base %d are: ", base) for i=1 to 1499999 do atom total = 0, j = i, d while j>0 and total<=i do d = remainder(j,base) total += factorial(d) j = floor(j/base) end while if...
Give a code snippet in #Phix Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,4...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Vedit_macro_language
Vedit macro language
#1 = 41 // number of prisoners #2 = 3 // step size #3 = 1 // number of survivors   Buf_Switch(Buf_Free) for (#5=0; #5<#1; #5++) { Ins_Text("prisoner ") Num_Ins(#5, LEFT) }   BOF #4=1 while (#1 > #3) { if (#4++ % #2 == 0) { Del_Line(1) #1-- } else { Line(1) } if (At_EOF) { BOF } }
Give a code snippet in #Vedit_macro_language Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from pris...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Raku
Raku
sub incomplete-γ-series($s, $z) { my \numers = $z X** 1..*; my \denoms = [\*] $s X+ 1..*; my $M = 1 + [+] (numers Z/ denoms) ... * < 1e-6; $z**$s / $s * exp(-$z) * $M; }   sub postfix:<!>(Int $n) { [*] 2..$n }   sub Γ-of-half(Int $n where * > 0) { ($n %% 2) ?? (($_-1)! giv...
Give a code snippet in #Raku Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#DWScript
DWScript
Print('Goodbye, World!');
Give a code snippet in #DWScript Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/St...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#VTL-2
VTL-2
1000 N=4 1010 F=1 1020 T=2 1030 V=3 1040 S=0 1050 #=2000 1060 #=9999 2000 R=! 2010 #=N<1*2210 2020 #=4000 2030 N=N-1 2040 A=T 2050 T=V 2060 V=A 2070 #=2000 2080 #=5000 2090 ?="Move disk from peg: "; 2100 ?=F 2110 ?=" to peg: "; 2120 ?=T 2130 ?="" 2140 #=4000 2150 N=N-1 2160 A=F 2170 F=V 2180 V=A 2190 #=2000 2200 #=5000...
Give a code snippet in #VTL-2 Task Solve the   Towers of Hanoi   problem with recursion.
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 ...
#CoffeeScript
CoffeeScript
http = require 'http'   show_large_anagram_sets = (word_lst) -> anagrams = {} max_size = 0   for word in word_lst key = word.split('').sort().join('') anagrams[key] ?= [] anagrams[key].push word size = anagrams[key].length max_size = size if size > max_size   for key, variations of anagrams ...
Give a code snippet in #CoffeeScript 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 wor...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Scala
Scala
object PolynomialRegression extends App { private def xy = Seq(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321).zipWithIndex.map(_.swap)   private def polyRegression(xy: Seq[(Int, Int)]): Unit = { val r = xy.indices   def average[U](ts: Iterable[U])(implicit num: Numeric[U]) = num.toDouble(ts.sum) / ts.size  ...
Give a code snippet in #Scala Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients...
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)
#zkl
zkl
Time.Date.isLeapYear(1988) //-->True T(1988,1989,1900,2000).apply(Time.Date.isLeapYear) //-->L(True,False,False,True)
Give a code snippet in #zkl 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/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#Ada
Ada
generic type Argument_1 (<>) is limited private; type Argument_2 (<>) is limited private; type Argument_3 (<>) is limited private; type Return_Value (<>) is limited private;   with function Func (A : in Argument_1; B : in Argument_2; C : in Argument_3) retu...
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#PowerShell
PowerShell
  $Infinity = 1 $NewNumbers = $null $Numbers = $null $Result = $null $Number = $null $Power = $args[0]   Write-Host $Power   For( $i=0; $i -lt $Infinity; $i++ ) { $Numbers = New-Object Object[] 1 $Numbers[0] = $Power For( $k=0; $k -lt $NewNumbers.Length; $k++ ) { ...
Give a code snippet in #PowerShell Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is e...
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...
#VBScript
VBScript
  filepath = "SPECIFY FILE PATH HERE"   Set objfso = CreateObject("Scripting.FileSystemObject") Set objdict = CreateObject("Scripting.Dictionary") Set objfile = objfso.OpenTextFile(filepath,1)   txt = objfile.ReadAll   For i = 1 To Len(txt) char = Mid(txt,i,1) If objdict.Exists(char) Then objdict.Item(char) = objdi...
Give a code snippet in #VBScript 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  (...
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#OCaml
OCaml
open Printf   let create_logger () = def log(text) & logs(l) = printf "Logged: %s\n%!" text; logs((text, Unix.gettimeofday ())::l) & reply to log   or search(text) & logs(l) = logs(l) & reply List.filter (fun (line, _) -> line = text) l to search in spawn logs([]); (log, search)   def w...
Give a code snippet in #OCaml Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed j...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Yabasic
Yabasic
n = 100 // doors ppa = 1 // next open door p2 = 1   for i = 1 to n print "Door ", i, " is "; if i < p2 then print "closed." else ppa = ppa + 1 p2 = ppa^2 print "OPEN." end if next
Give a code snippet in #Yabasic There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Maple
Maple
with(StringTools): Hash("Ars longa, vita brevis",method="SHA1");   # "e640d285242886eb96ab80cbf858389b3df52f43"
Give a code snippet in #Maple SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ide...
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. 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 Implement the Drossel and Schwabl definition of the fores...
#Sidef
Sidef
define w = `tput cols`.to_i-1 define h = `tput lines`.to_i-1 define r = "\033[H"   define red = "\033[31m" define green = "\033[32m" define yellow = "\033[33m"   define chars = [' ', green+'*', yellow+'&', red+'&']   define tree_prob = 0.05 define burn_prob = 0.0002   enum |Empty, Tree, Heating, Burning|   define dirs ...
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Forest-fire model. 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 Implement the Drossel and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Lucid
Lucid
multiply(x,y) = x * y
Give a code snippet in #Lucid A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract ...
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 |...
#PowerShell
PowerShell
$a = [int] (Read-Host a) $b = [int] (Read-Host b)   if ($a -lt $b) { Write-Host $a is less than $b`. } elseif ($a -eq $b) { Write-Host $a is equal to $b`. } elseif ($a -gt $b) { Write-Host $a is greater than $b`. }
Give a code snippet in #PowerShell 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/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   :_main   for /l %%i in (1,1,20000) do (   echo Processing %%i   call:_P %%i set Pn=!errorlevel! if !Pn! lss %%i set /a deficient+=1 if !Pn!==%%i set /a perfect+=1 if !Pn! gtr %%i set /a abundant+=1 cls )   echo Deficient - %deficient% ^| Perfect - %perfect% ^|...
Give a code snippet in #Batch_File These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#NewLISP
NewLISP
(context 'if2)   (define-macro (if2:if2 cond1 cond2 both-true first-true second-true neither) (cond ((eval cond1) (if (eval cond2) (eval both-true) (eval first-true))) ((eval cond2) (eval second-true)) (true (eval neither))))   (context MAIN)   > (if2 true true...
Give a code snippet in #NewLISP Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e....
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Ada
Ada
echo 'with Ada.text_IO; use Ada.text_IO; procedure X is begin Put("Hello!"); end X;' > x.adb; gnatmake x; ./x; rm x.adb x.ali x.o x
Give a code snippet in #Ada Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementation...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Amazing_Hopper
Amazing Hopper
  #include <flow.h> #include <flow-term.h>   DEF-MAIN(argv,argc)   SET( Pen, 0 ) LET( Pen := STR-TO-UTF8(CHAR(219)) )   CLR-SCR HIDE-CURSOR   GOSUB( Animate a Pendulum )   SHOW-CURSOR END   RUTINES   DEF-FUN( Animate a Pendulum ) MSET( accel, speed, bx, by ) SET( theta, M_PI_2 ) // pi/2 constant ...
Give a code snippet in #Amazing_Hopper One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendu...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#EchoLisp
EchoLisp
  (lib 'math) (define (make-circle x0 y0 r) (vector x0 y0 r ))   (define-syntax-id _.radius (_ 2)) (define-syntax-id _.x0 (_ 0)) (define-syntax-id _.y0 (_ 1))   ;; to sort circles (define (cmp-circles a b) (> a.radius b.radius))   (define (included? circle: a circles) (for/or ((b circles)) #:conti...
Give a code snippet in #EchoLisp Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#SPL
SPL
fact(n)=  ? n!>1, <=1 <= n*fact(n-1) .
Give a code snippet in #SPL Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Python
Python
import sys, math, collections   Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z")   def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len)   def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d ...
Give a code snippet in #Python Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language n...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Ezhil
Ezhil
  ## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்   நிரல்பாகம் மீபொம(எண்1, எண்2)   @(எண்1 == எண்2) ஆனால்   ## இரு எண்களும் சமம் என்பதால், மீபொம அந்த எண்ணேதான்   பின்கொடு எண்1   @(எண்1 > எண்2) இல்லைஆனால்   சிறியது = எண்2 பெரியது = எண்1   இல்ல...
Give a code snippet in #Ezhil Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has...
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 ...
#F.23
F#
  open System   let getInput (name : string) = Console.Write ("String {0}: ", name) Console.ReadLine ()   let levDist (strOne : string) (strTwo : string) = let strOne = strOne.ToCharArray () let strTwo = strTwo.ToCharArray ()   let (distArray : int[,]) = Array2D.zeroCreate (strOne.Length + 1) (strTw...
Give a code snippet in #F.23 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/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Toka
Toka
#! Include the regex library needs regex   #! The two test strings " This is a string" is-data test.1 " Another string" is-data test.2   #! Create a new regex named 'expression' which tries #! to match strings beginning with 'This'. " ^This" regex: expression   #! An array to store the results of the match #! (Element...
Give a code snippet in #Toka Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#C
C
#include <stdio.h>//printf #include <stdlib.h>//qsort #include <math.h>//fabs #include <stdbool.h>//bool data type #include <strings.h>//strcasecmp #include <assert.h>//assert, necessary for random integer selection   unsigned int * seq_len(const unsigned int START, const unsigned int END) { //named after R function of...
Give a code snippet in #C Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-val...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Solution_with_recursion
Solution with recursion
  <html> <body> <pre> <?php   /************************************************************************* * * This algorithm solves the 8 queens problem using backtracking. * Please try with N<=25 * * * *************************************************************************/ class Queens { var $size; var $a...
Give a code snippet in #Solution_with_recursion Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight'...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Write $ZConvert("http%3A%2F%2Ffoo%20bar%2F", "I", "URL") http://foo bar/
Give a code snippet in #Cach.C3.A9_ObjectScript This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given a list of strings in HL, and a pointer in DE, write ;; the resulting string starting at DE. quibble: mvi a,'{' ; Write the first {, stax d inx d ; And increment the pointer push h ; Keep start of list call s...
Give a code snippet in #8080_Assembly Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}"...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Swift
Swift
public extension String { func splitOnChanges() -> [String] { guard !isEmpty else { return [] }   var res = [String]() var workingChar = first! var workingStr = "\(workingChar)"   for char in dropFirst() { if char != workingChar { res.append(workingStr) workingStr =...
Give a code snippet in #Swift Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#J
J
merge=: ({:"1 (+/@:({."1),{:@{:)/. ])@; count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@] init=: (1 ,. ,.)^:(0=#@$) nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@,
Give a code snippet in #J There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pen...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#Racket
Racket
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements)))   (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (c...
Give a code snippet in #Racket Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element ...
christopher/rosetta-code
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Picat
Picat
go => S = "TOBEORNOTTOBEORTOBEORNOT", println(s=S), println(len=S.length),   Compressed = compress(S), println(compressed=Compressed), println(len=Compressed.length),   Uncompressed = uncompress(Compressed), println(uncompressed=Uncompressed),   printf("compressed to %3.3f%%\n", 100*(Compressed.length...
Give a code snippet in #Picat The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Vlang
Vlang
fn main() { arrays := [['a','b','c'],['A','B','C'],['1','2','3']] for i in 0..arrays[0].len { println('${arrays[0][i]}${arrays[1][i]}${arrays[2][i]}') } }
Give a code snippet in #Vlang Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exam...
christopher/rosetta-code