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/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Lambdatalk
Lambdatalk
  {def prime {def prime.rec {lambda {:m :n} {if {> {* :m :m} :n} then :n else {if {= {% :n :m} 0} then else {prime.rec {+ :m 1} :n} }}}} {lambda {:n} {prime.rec 2 :n} }}   {map prime {serie 3 100 2}} -> 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97   {map pri...
Give a code snippet in #Lambdatalk Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bei...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#EchoLisp
EchoLisp
  ;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results (define (rpn->string rpn) (if (vector? rpn) (infix->string (rpn->infix rpn)) "😥 Not found"))     (string-delimiter "") (define OPS #(* + - // )) ;; use float division (define-syntax-rule (commutative? op) (or (= op *) (= op +)))...
Give a code snippet in #EchoLisp task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#CoffeeScript
CoffeeScript
  nth_root = (A, n, precision=0.0000000000001) -> x = 1 while true x_new = (1 / n) * ((n - 1) * x + A / Math.pow(x, n - 1)) return x_new if Math.abs(x_new - x) < precision x = x_new   # tests do -> tests = [ [8, 3] [16, 4] [32, 5] [343, 3] [1024, 10] [1000000000, 3] [10000...
Give a code snippet in #CoffeeScript Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const proc: doDivide (in integer: numer, in integer: denom) is func begin block writeln(numer <& " div " <& denom <& " = " <& numer div denom); exception catch NUMERIC_ERROR: writeln("Division by zero detected."); end block; end func...
Give a code snippet in #Seed7 Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Oberon-2
Oberon-2
MODULE M;   TYPE T = POINTER TO TDesc; TDesc = RECORD x: INTEGER END;   PROCEDURE New*(): T; VAR t: T; BEGIN NEW(t); t.x := 0; RETURN t END New;     PROCEDURE (t: T) Increment*; BEGIN INC(t.x) END Increment;   END M.
Give a code snippet in #Oberon-2 In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#F.23
F#
  // Find Antı-Primes. Nigel Galloway: Secember 10th., 2018 let N=200000000000000000000000000I let fI,_=Seq.scan(fun (_,g) e->(e,e*g)) (2I,4I) (primes|>Seq.skip 1|>Seq.map bigint)|>Seq.takeWhile(fun(_,n)->n<N)|>List.ofSeq|>List.unzip let fG g=Seq.unfold(fun ((n,i,e) as z)->Some(z,(n+1,i+1,(e*g)))) (1,2,g)|>Seq.takeWhi...
Give a code snippet in #F.23 The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#UNIX_Shell
UNIX Shell
#!/bin/bash   is_palindrome() { local s1=$1 local s2=$(echo $1 | tr -d "[ ,!:;.'\"]" | tr '[A-Z]' '[a-z]')   if [[ $s2 = $(echo $s2 | rev) ]] then echo "[$s1] is a palindrome" else echo "[$s1] is NOT a palindrome" fi }  
Give a code snippet in #UNIX_Shell Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   namespace RosettaCode { class Program { static void Main(string[] args) { string test = "string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄"; ...
Give a code snippet in #C.23 Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Apex
Apex
  // If not initialized at class/member level, it will be set to null Integer x = 0; Integer y; // y is null here Integer p,q,r; // declare multiple variables Integer i=1,j=2,k=3; // declare and initialize   /* * Similar to Integer, below variables can be initialized together separated by ','. */ String s = 'a string'...
Give a code snippet in #Apex Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#CMake
CMake
# bubble_sort(var [value1 value2...]) sorts a list of integers. function(bubble_sort var) math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last]. set(again YES) while(again) set(again NO) math(EXPR last "${last} - 1") # Decrement last index. foreach(index RANGE 1 ${last}) ...
Give a code snippet in #CMake 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/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#ALGOL_68
ALGOL 68
BEGIN # display the period and group number of an element, # # given its atomic number # INT max atomic number = 118; # highest known element # # the positions are stored as: # # ( group number * group multiplier ) + period # INT group m...
Give a code snippet in #ALGOL_68 Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Scheme
Scheme
(number->string (+ 1 (string->number "1234")))
Give a code snippet in #Scheme Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Liberty_BASIC
Liberty BASIC
mainwin 140 32   CRLF$ =chr$( 13) maxlen =0   read y   Dim txt$( y)   For i =1 To y Read i$ print i$ if right$( i$, 1) <>"$" then i$ =i$ +"$" txt$( i) =i$ x =max( CountDollars( txt$( i)), x) Next i   print x   Dim matrix$( x, y)   Print CRLF$...
Give a code snippet in #Liberty_BASIC Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be ei...
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...
#Q
Q
f:(*/)1+til@
Give a code snippet in #Q 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 numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Stata
Stata
display "`:env PATH'" display "`:env USERNAME'" display "`:env USERPROFILE'"
Give a code snippet in #Stata Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#EchoLisp
EchoLisp
  ;; put info string in permanent storage for later use (info 'make-Q "usage: (define q (make-Q)) ; (q '[top | empty? | pop | push value | to-list | from-list list])")   ;; make-Q (define (make-Q) (let ((q (make-vector 0))) (lambda (message . args) (case message ((empty?) (vector-empty? q)) ...
Give a code snippet in #EchoLisp Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in th...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT "The border colour is "; PEEK (23624): REM bordcr 20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop 30 POKE 23609,50: REM set keyboard pip to 50
Give a code snippet in #ZX_Spectrum_Basic Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#CoffeeScript
CoffeeScript
hash = a: 'one' b: 'two'   for key, value of hash console.log key, value   for key of hash console.log key  
Give a code snippet in #CoffeeScript Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collectio...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#SuperCollider
SuperCollider
  var pyth = { |n| all {: [x,y,z], x <- (1..n), y <- (x..n), z <- (y..n), (x**2) + (y**2) == (z**2) } };   pyth.(20) // example call
Give a code snippet in #SuperCollider A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#11l
11l
print(Array(‘a’..‘z’))
Give a code snippet in #11l Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a re...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Objective-C
Objective-C
@interface U0 : NSObject { } @end @interface U1 : NSObject { } @end @implementation U0 @end @implementation U1 @end   void foo(); void bar(int i); void baz(int i);   void foo() { for (int i = 0; i <= 1; i++) { @try { bar(i); } @catch (U0 *e) { NSLog(@"Function foo caught exception U0"); } } ...
Give a code snippet in #Objective-C Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Asymptote
Asymptote
string src, dst; src = "Hello"; dst = src; src = " world..."; write(dst, src);
Give a code snippet in #Asymptote This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Julia
Julia
  isdefined(:Date) || using Dates   const wday = Dates.Sun const lo = 1 const hi = 12   print("\nThis script will print the last ", Dates.dayname(wday)) println("s of each month of the year given.") println("(Leave input empty to quit.)")   while true print("\nYear> ") y = chomp(readline()) 0 < length(y) ||...
Give a code snippet in #Julia Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Kabap
Kabap
return = "Hello world!";
Give a code snippet in #Kabap Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Arturo
Arturo
eqIndex: function [row][ suml: 0 delayed: 0 sumr: sum row result: new [] loop.with:'i row 'r [ suml: suml + delayed sumr: sumr - r delayed: r if suml = sumr -> 'result ++ i ] return result ]   data: @[ @[neg 7, 1, 5, 2, neg 4, 3, 0] @[2 4 6] @[2 9 ...
Give a code snippet in #Arturo An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#J
J
T=: 0:`1:`(($:&<:+ - $: ])`0:@.(0=]))@.(1+*@-) M. "0
Give a code snippet in #J This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   public class SequenceNthNumberWithExactlyNDivisors {   public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) =...
Give a code snippet in #Java Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number ...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Smalltalk
Smalltalk
DateTime now displayNl.
Give a code snippet in #Smalltalk Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Lua
Lua
T0 = 100 TR = 20 k = 0.07 delta_t = { 2, 5, 10 } n = 100   NewtonCooling = function( t ) return -k * ( t - TR ) end     function Euler( f, y0, n, h ) local y = y0 for x = 0, n, h do print( "", x, y ) y = y + h * f( y ) end end     for i = 1, #delta_t do print( "delta_t = ", delta_t[i] ) Euler( Ne...
Give a code snippet in #Lua Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Ada
Ada
with Ada.Text_IO; with Ada.Containers.Vectors;   procedure Convex_Hull is   type Point is record X, Y : Integer; end record;   package Point_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Point); use Point_Vectors;   function...
Give a code snippet in #Ada Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a = "5^3^2"; Print[a <> " = " <> ToString[ToExpression[a]]] b = "(5^3)^2"; Print[b <> " = " <> ToString[ToExpression[b]]] c = "5^(3^2)"; Print[c <> " = " <> ToString[ToExpression[c]]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.)...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#C.23
C#
using System;   class Program { private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText) { while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1) ...
Give a code snippet in #C.23 A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Hoon
Hoon
  :-  %say |= [* * [bottles=_99 ~]] :-  %noun ^- wall =/ output `(list tape)`~ |- ?: =(1 bottles)  %- flop  :- "1 bottle of beer on the wall"  :- "Take one down, pass it around"  :- "1 bottle of beer"  :- "1 bottle of beer on the wall" output %= $ bottles (dec bottles) output  :- "{<bottles...
Give a code snippet in #Hoon Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#ALGOL_W
ALGOL W
begin % draw sierpinski arrowhead curves using ascii art % integer CANVAS_WIDTH; CANVAS_WIDTH := 200; begin  % the ascii art canvas and related items % string(1) array canvas ( 1 :: CANVAS_WIDTH, 1 :: CANVAS_WIDTH ); integer heading, asciiX, asciiY, width, maxX, maxY, minX, mi...
Give a code snippet in #ALGOL_W Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
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...
#UNIX_Shell
UNIX Shell
#! /bin/bash pascal() { local -i n=${1:-1} if (( n <= 1 )); then echo 1 else local output=$( $FUNCNAME $((n - 1)) ) set -- $( tail -n 1 <<<"$output" ) # previous row echo "$output" printf "1 " while [[ -n $1 ]]; do printf "%d " $(( $1 + ${2:-0} )...
Give a code snippet in #UNIX_Shell 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/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Pascal
Pascal
program StringPrepend; {$mode objfpc}{$H+}   uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes { you can add units after this };   var s: String = ' World !'; begin s := 'Hello' + s; WriteLn(S); ReadLn; end.
Give a code snippet in #Pascal Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Factor
Factor
USING: assocs kernel math mirrors prettyprint strings ;   TUPLE: foo { bar string } { baz string initial: "hi" } { baxx integer initial: 50 read-only } ; C: <foo> foo   "apple" "banana" 200 <foo> <mirror> [ >alist ] [ object-slots ] bi [ . ] bi@
Give a code snippet in #Factor Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Ursala
Ursala
#import std   #executable ('parameterized','')   showenv = <.file$[contents: --<''>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs
Give a code snippet in #Ursala Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#D
D
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By...
Give a code snippet in #D 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PowerShell
PowerShell
function Get-Factor ($a) { 1..$a | Where-Object { $a % $_ -eq 0 } }
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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Vala
Vala
  int fibRec(int n){ if (n < 2) return n; else return fibRec(n - 1) + fibRec(n - 2); }  
Give a code snippet in #Vala The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Julia
Julia
abstract type Mammal end habitat(::Mammal) = "planet Earth"   struct Whale <: Mammal mass::Float64 habitat::String end Base.show(io::IO, ::Whale) = print(io, "a whale") habitat(w::Whale) = w.habitat   struct Wolf <: Mammal mass::Float64 end Base.show(io::IO, ::Wolf) = print(io, "a wolf")   arr = [Whale(1000...
Give a code snippet in #Julia In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cla...
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#Clojure
Clojure
(defn mkdirp [path] (let [dir (java.io.File. path)] (if (.exists dir) true (.mkdirs dir))))
Give a code snippet in #Clojure Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the direc...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Haskell
Haskell
  main = putStrLn ("Hello" ++ "World")  
Give a code snippet in #Haskell Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#J
J
  NB. Naive method NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.   echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)     NB. inclusion/exclusion   triangular =: -:@:(*: + 1&*) sumdiv =: dyad define (triangular <. x % y) * y )   ech...
Give a code snippet in #J Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Ruby
Ruby
def humble?(i) while i % 2 == 0; i /= 2 end while i % 3 == 0; i /= 3 end while i % 5 == 0; i /= 5 end while i % 7 == 0; i /= 7 end i == 1 end   count, num = 0, 0 digits = 10 # max digits for humble numbers limit = 10 ** digits # max numbers to search through humble = Array...
Give a code snippet in #Ruby Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above ...
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...
#Vala
Vala
List<string> things = new List<string> (); things.append("Apple"); things.append("Banana"); things.append("Coconut");   foreach (string thing in things) { stdout.printf("%s\n", thing); }
Give a code snippet in #Vala 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/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Q
Q
> Y: {{x x} {({y {(x x) y} x} y) x} x} > fac: {{$[y<2; 1; y*x y-1]} x} > (Y fac) 6 720j > fib: {{$[y<2; 1; (x y-1) + (x y-2)]} x} > (Y fib) each til 20 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765  
Give a code snippet in #Q In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variab...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Huginn
Huginn
import Algorithms as algo; import Text as text;   main() { print( "{}\n".format( text.character_class( text.CHARACTER_CLASS.LOWER_CASE_LETTER ) ) ); print( "{}\n".format( algo.materialize( algo.map( algo.range( integer( 'a' ), integer( 'z' ) + 1 ), character ...
Give a code snippet in #Huginn Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#J
J
  sieve=: 3 :0 NB. sieve y returns a vector of y boxes. NB. In each box is an array of 2 columns. NB. The first column is the factor tally NB. and the second column is a number with NB. that many factors. NB. Rather than factoring, the algorithm NB. counts prime seive cell hits. NB. The boxes are not ordered b...
Give a code snippet in #J Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random;   procedure Test_Updates is   type Bucket_Index is range 1..13; package Random_Index is new Ada.Numerics.Discrete_Random (Bucket_Index); use Random_Index; type Buckets is array (Bucket_Index) of Natural;   protected type Safe_Buckets ...
Give a code snippet in #Ada Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all buck...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PowerShell
PowerShell
  function euler (${f}, ${y}, $y0, $t0, $tEnd) { function f-euler ($tn, $yn, $h) { $yn + $h*(f $tn $yn) } function time ($t0, $h, $tEnd) { $end = [MATH]::Floor(($tEnd - $t0)/$h) foreach ($_ in 0..$end) { $_*$h + $t0 } } $time = time $t0 10 $tEnd $time5 = time $t0 5 $tE...
Give a code snippet in #PowerShell Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following f...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Phix
Phix
include builtins/ldap.e constant servers = { "ldap.somewhere.com", } --... string name="name", password="passwd" --... for i=1 to length(servers) do atom ld = ldap_init(servers[i]) integer res = ldap_simple_bind_s(ld, name, password) printf(1,"%s: %d [%s]\n",{servers[i],res,ldap_err_desc(res)}) --... ...
Give a code snippet in #Phix The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
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: ...
#Oforth
Oforth
[ "a", "b", "c" ] [ "A", "B", "C" ] [ 1, 2, 3 ] zipAll(3) apply(#[ apply(#print) printcr ])
Give a code snippet in #Oforth 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 exa...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Stata
Stata
* Read rows 20 to 30 from somedata.dta . use somedata in 20/30, clear   * Read rows for which the variable x is positive . use somedata if x>0, clear
Give a code snippet in #Stata Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it i...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Arturo
Arturo
phr: "rosetta code phrase reversal"   print ["(0)" phr] print ["(1)" reverse phr] print ["(2)" join.with:" " map split.words phr => reverse] print ["(3)" join.with:" " reverse split.words phr]
Give a code snippet in #Arturo Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of ea...
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 ...
#Logo
Logo
to double :x output ashift :x 1 end to halve :x output ashift :x -1 end to even? :x output equal? 0 bitand 1 :x end to eproduct :x :y if :x = 0 [output 0] ifelse even? :x ~ [output eproduct halve :x double :y] ~ [output :y + eproduct halve :x double :y] end
Give a code snippet in #Logo 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 wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#SmileBASIC
SmileBASIC
CLS
Give a code snippet in #SmileBASIC Task Clear the terminal window.
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...
#C
C
  #include<stdarg.h> #include<stdio.h>   long int factorial(int n){ if(n>1) return n*factorial(n-1); return 1; }   long int sumOfFactorials(int num,...){ va_list vaList; long int sum = 0;   va_start(vaList,num);   while(num--) sum += factorial(va_arg(vaList,int));   va_end(vaList);   return sum; }   int mai...
Give a code snippet in #C 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Scala
Scala
import math._   // functions as values val cube = (x: Double) => x * x * x val cuberoot = (x: Double) => pow(x, 1 / 3d)   // higher order function, as a method def compose[A,B,C](f: B => C, g: A => B) = (x: A) => f(g(x))   // partially applied functions in Lists val fun = List(sin _, cos _, cube) val inv = List(asin _,...
Give a code snippet in #Scala A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other f...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Oz
Oz
declare fun {BinarySearch Arr Val} fun {Search Low High} if Low > High then nil else Mid = (Low+High) div 2 in if Val < Arr.Mid then {Search Low Mid-1} elseif Val > Arr.Mid then {Search Mid+1 High} else [Mid] end end end ...
Give a code snippet in #Oz A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Maple
Maple
  Ackermann := proc( m :: nonnegint, n :: nonnegint ) option remember; # optional automatic memoization if m = 0 then n + 1 elif n = 0 then thisproc( m - 1, 1 ) else thisproc( m - 1, thisproc( m, n - 1 ) ) end if end proc:  
Give a code snippet in #Maple The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#OCaml
OCaml
let generate_brackets n = let rec aux i acc = if i <= 0 then acc else aux (pred i) ('['::']'::acc) in let brk = aux n [] in List.sort (fun _ _ -> (Random.int 3) - 1) brk   let is_balanced brk = let rec aux = function | [], 0 -> true | '['::brk, level -> aux (brk, succ level) | ']'::brk,...
Give a code snippet in #OCaml Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-n...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#REXX
REXX
/*REXX program that implements various List Manager functions. */ /*┌────────────────────────────────────────────────────────────────────┐ ┌─┘ Functions of the List Manager └─┐ │ │ │ @init ─── initi...
Give a code snippet in #REXX Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, El...
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#FreeBASIC
FreeBASIC
#define MAXX 319 #define MAXY 199   enum state E=0, C=8, H=9, T=4 'doubles as colours: black, grey, bright blue, red end enum   dim as uinteger world(0 to 1, 0 to MAXX, 0 to MAXY), active = 0, buffer = 1 dim as double rate = 1./3. 'seconds per frame dim as double tick dim as uinteger x, y   function turn_on( wor...
Give a code snippet in #FreeBASIC Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All c...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Dart
Dart
  main() { int n=5,d=3; int z= fact(n,d); print('$n factorial of degree $d is $z'); for(var j=1;j<=5;j++) { print('first 10 numbers of degree $j :'); for(var i=1;i<=10;i++) { int z=fact(i,j); print('$z'); } print('\n'); } }   int fact(int a,int b) {   if(a<=b||a==0) return a; if(a>1) retu...
Give a code snippet in #Dart The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#HicEst
HicEst
WRITE(Row=1) " x 1 2 3 4 5 6 7 8 9 10 11 12" DO line = 1, 12 WRITE(Row=line+2, Format='i2') line DO col = line, 12 WRITE(Row=line+2, Column=4*col, Format='i3') line*col ENDDO ENDDO
Give a code snippet in #HicEst Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public class Interval { public Interval(double leftEndpoint, double size) { LeftEndpoint = leftEndpoint; RightEndpoint = leftEndpoint + size; }   public double LeftEndpoint { get; set; }   pu...
Give a code snippet in #C.23 Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to mak...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#F.23
F#
open System   Console.Clear()
Give a code snippet in #F.23 Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Nanoquery
Nanoquery
s = ""   def uniqueDigits(i) global s   // returns true, if unique digits, false otherwise for k in range(0, len(s) - 2) for l in range(k + 1, len(s) - 1) if (s[l] = "0") || (s[l] = "5") //0 or 5 digit ...
Give a code snippet in #Nanoquery Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#x86_Assembly
x86 Assembly
FORMAT=-f elf RUN=./ BIN=scriptname OBJ=scriptname.o   all: test   test: $(BIN) $(RUN)$(BIN)   $(BIN): $(OBJ) ld -o $(BIN) $(OBJ)   $(OBJ): scriptname.asm nasm $(FORMAT) -o $(OBJ) scriptname.asm   clean: -rm $(BIN) -rm $(OBJ)
Give a code snippet in #x86_Assembly The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
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 |...
#AWK
AWK
  # syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK BEGIN { main("abcd","123456789") main("longer","short") main("hello","world") exit(0) } function main(Sa,Sb, La,Lb) { La = length(Sa) Lb = length(Sb) if (La > Lb) { printf("a>b\n%3d %s\n%3d %s\n\n",La,Sa,Lb,Sb) } else if (L...
Give a code snippet in #AWK 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the w...
#Transd
Transd
#lang transd   MainModule: { maxwLen: 9, minwLen: 3, dict: Vector<String>(), subWords: Vector<String>(),   procGrid: (λ grid String() cent String() subs Bool() (with cnt 0 (sort grid) (for w in dict where (and (neq (find w cent) -1) (match w "^[[:alpha:]]+$")) do (i...
Give a code snippet in #Transd A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain t...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#C.23
C#
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console;   class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0,...
Give a code snippet in #C.23 Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Resistor_mesh
Resistor mesh
Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
#Java
Java
import java.util.ArrayList; import java.util.List;   public class ResistorMesh { private static final int S = 10;   private static class Node { double v; int fixed;   Node(double v, int fixed) { this.v = v; this.fixed = fixed; } }   private static ...
Give a code snippet in #Java Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#AppleScript
AppleScript
set {year:y, month:m, day:d, weekday:w} to (current date)   tell (y * 10000 + m * 100 + d) as text to set shortFormat to text 1 thru 4 & "-" & text 5 thru 6 & "-" & text 7 thru 8 set longFormat to (w as text) & (", " & m) & (space & d) & (", " & y)   return (shortFormat & linefeed & longFormat)
Give a code snippet in #AppleScript This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Burlesque
Burlesque
blsq ) "Hello, ""world!"?+ "Hello, world!"
Give a code snippet in #Burlesque String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Java
Java
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List;   import org.apache.commons.lang3.StringUtils;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { priva...
Give a code snippet in #Java Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Action.21
Action!
CARD FUNC DecodeRomanDigit(CHAR c) IF c='I THEN RETURN (1) ELSEIF c='V THEN RETURN (5) ELSEIF c='X THEN RETURN (10) ELSEIF c='L THEN RETURN (50) ELSEIF c='C THEN RETURN (100) ELSEIF c='D THEN RETURN (500) ELSEIF c='M THEN RETURN (1000) FI RETURN (0)   CARD FUNC DecodeRomanNumber(CHAR ARRAY s) CARD res...
Give a code snippet in #Action.21 Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Wren
Wren
/* sockets.wren */   var AF_UNSPEC = 0 var SOCK_STREAM = 1   foreign class AddrInfo { foreign static getAddrInfo(name, service, req, pai)   construct new() {}   foreign family   foreign family=(f)   foreign sockType   foreign sockType=(st)   foreign protocol   foreign addr   foreign ...
Give a code snippet in #Wren For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Standard_ML
Standard ML
  val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world!" ) ;   fun serve listener portnr = let fun next () = let val (conn, conn_addr) = Socket.accept listener in case Posix.Process.fork () of NONE => ( Socket.sendVec(conn, txt); Socket.close conn ; ...
Give a code snippet in #Standard_ML The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested....
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#PureBasic
PureBasic
CopyFile("input.txt","output.txt")
Give a code snippet in #PureBasic File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a fi...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#C.2B.2B
C++
#include <iostream>   bool check_isbn13(std::string isbn) { int count = 0; int sum = 0;   for (auto ch : isbn) { /* skip hyphens or spaces */ if (ch == ' ' || ch == '-') { continue; } if (ch < '0' || ch > '9') { return false; } if (coun...
Give a code snippet in #C.2B.2B Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#PureBasic
PureBasic
Procedure Draw_a_Cuboid(Window, X,Y,Z) w=WindowWidth(Window) h=WindowHeight(Window) diag.f=1.9 If Not (w And h): ProcedureReturn: EndIf xscale.f = w/(x+z/diag)*0.98 yscale.f = h/(y+z/diag)*0.98 If xscale<yscale Scale.f = xscale Else Scale = yscale EndIf x*Scale: Y*Scale: Z*Scale CreateImag...
Give a code snippet in #PureBasic Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projectio...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Action.21
Action!
PROC Main() BYTE x,y,z,n BYTE ARRAY nuggets(101)   FOR n=0 TO 100 DO nuggets(n)=0 OD   FOR x=0 TO 100 STEP 6 DO FOR y=0 TO 100 STEP 9 DO FOR z=0 TO 100 STEP 20 DO n=x+y+z IF n<=100 THEN nuggets(n)=1 FI OD OD OD   n=100 DO IF nug...
Give a code snippet in #Action.21 Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#dc
dc
! ls
Give a code snippet in #dc Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#Modula-3
Modula-3
MODULE ArraySort EXPORTS Main;   IMPORT IntArraySort;   VAR arr := ARRAY [1..10] OF INTEGER{3, 6, 1, 2, 10, 7, 9, 4, 8, 5};   BEGIN IntArraySort.Sort(arr); END ArraySort.
Give a code snippet in #Modula-3 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/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#BASIC
BASIC
SUB MostarPos (N) DIM a(7) RESTORE a: FOR x = 0 TO 7: READ a(x): NEXT x DIM b(7) RESTORE b: FOR x = 0 TO 7: READ b(x): NEXT x   I = 7 WHILE a(I) > N I = I - 1 WEND M = N + b(I) R = (M \ 18) + 1 C = (M MOD 18) + 1 PRINT USING "Atomic number ### -> #_, ##"; N; R; C ...
Give a code snippet in #BASIC Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Python
Python
import time, winsound #, sys   char2morse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", "-": "-....-", ".": ".-.-.-", "/": "-..-.", "0": "-----", "1": ...
Give a code snippet in #Python Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignor...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Ada
Ada
Str  : String := "Hello World"; Length : constant Natural := Str'Size / 8;
Give a code snippet in #Ada Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme contai...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Eiffel
Eiffel
class MAIN creation main feature main is local x, y: INTEGER; retried: BOOLEAN; do x := 42; y := 0;   if not retried then io.put_real(x / y); else print("NaN%N"); end rescu...
Give a code snippet in #Eiffel Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#XPL0
XPL0
string 0; \Use zero-terminated strings   func Count(Stones, Jewels); \Return number of letters in Stones that match letters in Jewels char Stones, Jewels; int Cnt, I, J; [Cnt:= 0; I:= 0; while Jewels(I) do [J:= 0; while Stones(J) do [if Stones(J) = Jewels(I) then Cnt:= Cnt+1; J:= J+1; ...
Give a code snippet in #XPL0 Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Z80_Assembly
Z80 Assembly
ld a,(&C005) ;load A from memory (this is an arbitrary memory location designated as the home of our variable) cp 42 jp nz,ErrorHandler
Give a code snippet in #Z80_Assembly Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Lingo
Lingo
on htmlTable (data) str = "<table>"   -- table head put "<thead><tr><th>&nbsp;</th>" after str repeat with cell in data[1] put "<th>"&cell&"</th>" after str end repeat put "</tr></thead>" after str   -- table body put "<tbody>" after str cnt = data.count repeat with i = 2 to cnt put "<tr><td...
Give a code snippet in #Lingo Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Common_Lisp
Common Lisp
(defclass 3d-vector () ((x :type number :initarg :x) (y :type number :initarg :y) (z :type number :initarg :z)))   (defmethod print-object ((object 3d-vector) stream) (print-unreadable-object (object stream :type t) (with-slots (x y z) object (format stream "~a ~a ~a" x y z))))   (defun make-3d-vect...
Give a code snippet in #Common_Lisp A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Gema
Gema
*= ! ignore off content of input \B=Hello world!\! ! Start output with this text.
Give a code snippet in #Gema Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Arturo
Arturo
beadSort: function [items][ a: new items m: neg infinity s: 0   loop a 'x [ if x > m -> m: x ]   beads: array.of: m * size a 0   loop 0..dec size a 'i [ loop 0..dec a\[i] 'j -> beads\[j + i * m]: 1 ]   loop 0..dec m 'j [ s: 0 loop 0..dec si...
Give a code snippet in #Arturo 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/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Logo
Logo
to rotate.left :thing output lput first :thing butfirst :thing end to rotate.right :thing output fput last :thing butlast :thing end   make "text "|Hello World! | make "right? "true   to step.animation label :text ; graphical  ; type char 13 type :text ; textual wait 6 ; 1/10 second if button <> 0 [make...
Give a code snippet in #Logo Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task dem...
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.
#Lua
Lua
require"iuplua" l = iup.label{title="There have been no clicks yet."} b = iup.button{title="Click me!"} clicks = 0 function b:button_cb() clicks = clicks + 1 l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct. end dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"...
Give a code snippet in #Lua 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/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Ring
Ring
  limit = 100 sieve = list(limit) for i = 2 to limit for k = i*i to limit step i sieve[k] = 1 next if sieve[i] = 0 see "" + i + " " ok next  
Give a code snippet in #Ring This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   al...
christopher/rosetta-code