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/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
#Python
Python
import sys sys.stdout.write("Goodbye, World!")
Give a code snippet in #Python 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/Stan...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Perl
Perl
sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 } sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }   # Usage: foreach my $sequence (\&F, \&M) { print join(' ', map $sequence->($_), 0 .. 19), "\n"; }
Give a code snippet in #Perl Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n )...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Bracmat
Bracmat
( ( C = n k coef .  !arg:(?n,?k) & (!n+-1*!k:<!k:?k|) & 1:?coef & whl ' ( !k:>0 & !coef*!n*!k^-1:?coef & !k+-1:?k & !n+-1:?n ) & !coef ) & ( P = n k result .  !arg:(?n,?k) & !n+-1*!k:?k & 1:?result & whl ...
Give a code snippet in #Bracmat This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikiped...
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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   class RAnagramsV01 public   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public signals MalformedURLException, IOException parse arg localFile . isr = Reader if localFil...
Give a code snippet in #NetRexx 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Simula
Simula
statement::= if conditional_expression then statement else statement if X=Y then K:=I else K:=J statement::= if conditional_expression then statement if X=Y then K:=I
Give a code snippet in #Simula Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common...
christopher/rosetta-code
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#PARI.2FGP
PARI/GP
use constant PI => 3.14159; use constant MSG => "Hello World";
Give a code snippet in #PARI.2FGP Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#D
D
import std.stdio, std.math, std.algorithm, std.traits, std.typecons, std.numeric, std.range, std.conv;   template elementwiseMat(string op) { T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow { if (A.empty) return null; auto R = new typeof(return)(A.length, A[0].length); ...
Give a code snippet in #D Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as ...
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...
#Tcl
Tcl
set string "gHHH5YY++///\\"   regsub -all {(.)\1*} $string {\0, } string regsub {, $} $string {} string puts $string
Give a code snippet in #Tcl 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#Swift
Swift
func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) { let res = [x, y, z].sorted()   x = res[0] y = res[1] z = res[2] }   var x = "lions, tigers, and" var y = "bears, oh my!" var z = "(from the \"Wizard of OZ\")"   print("Before:") print("x = \(x)") print("y = \(y)") print("z = \(z)") print() ...
Give a code snippet in #Swift 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/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#zkl
zkl
var [const] words= // create hashed unixdict of striped words (word:True, ...) File("dict.txt").howza(11).pump(Dictionary().howza(8).add.fp1(True)); ss:=words.pump(List, // push stripped unixdict words through some functions fcn(w){ words.holds(w.reverse()) }, Void.Filter, // filter palindromes // create ("...
Give a code snippet in #zkl A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total ...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Lambdatalk
Lambdatalk
  {require lib_BN} // for big numbers   1) pascalian binomial coefficient C(n,p) = n!/(p!(n-p)!) = (n*(n-1)...(n-p+1))/(p*(p-1)...2*1)   {def coeff {lambda {:n :p} {BN.intPart {BN./ {S.reduce BN.* {S.serie :n {- :n :p -1} -1}} {S.reduce BN.* {S.serie :p 1 -1}}}}}} -> coeff   2) polynomial expansions of...
Give a code snippet in #Lambdatalk The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Sidef
Sidef
func harshad() { var n = 0; { ++n while !(n %% n.digits.sum); n; } }   var iter = harshad(); say 20.of { iter.run };   var n; do { n = iter.run } while (n <= 1000);   say n;
Give a code snippet in #Sidef The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#SQL
SQL
' ' String literal " " Identifier [ ] Identifier ` ` Identifier ? Numbered host parameter : Named host parameter $ Named host parameter @ Named host parameter ( ) Parentheses + Add - Subtract/negative * Multiply / Divide % Modulo & Bitwise AND | Bitwise OR ~ Bitwise NOT << Lef...
Give a code snippet in #SQL Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it t...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Fortran
Fortran
PROGRAM QUADRATIC   IMPLICIT NONE INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15) REAL(dp) :: a, b, c, e, discriminant, rroot1, rroot2 COMPLEX(dp) :: croot1, croot2   WRITE(*,*) "Enter the coefficients of the equation ax^2 + bx + c" WRITE(*, "(A)", ADVANCE="NO") "a = " READ *, a WRITE(*,"(A)", ADVANCE="NO") "...
Give a code snippet in #Fortran This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . You...
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]] On[Assert];myFun[1.0]
Give a code snippet in #Mathematica.2FWolfram_Language 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Java
Java
  public class MertensFunction {   public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { ...
Give a code snippet in #Java The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Clojure
Clojure
(defn sleep [ms] ; time in milliseconds (println "Sleeping...") (Thread/sleep ms) (println "Awake!")) ; call it (sleep 1000)
Give a code snippet in #Clojure Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thre...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#JavaScript
JavaScript
function running_stddev() { var n = 0; var sum = 0.0; var sum_sq = 0.0; return function(num) { n++; sum += num; sum_sq += num*num; return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) ); } }   var sd = running_stddev(); var nums = [2,4,4,4,5,5,7,9]; var stddev = []; ...
Give a code snippet in #JavaScript Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the ...
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. ...
#Fortran
Fortran
C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses C one nonstandard character on the line labelled 5001. Many F77 C compilers should be okay with it, but it is *not* standard. PROGRAM FORLOOP INTEGER I, J   DO 20 I = 1, 5 DO 10 J = 1, I C Print the ...
Give a code snippet in #Fortran “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 struc...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Rust
Rust
let v1 = vec![vec![1,2,3]; 10]; println!("Original address: {:p}", &v1); let mut v2; // Override rust protections on reading from uninitialized memory unsafe {v2 = mem::uninitialized();} let addr = &mut v2 as *mut _;   // ptr::write() though it takes v1 by value, v1s destructor is not run when it goes out of // scope,...
Give a code snippet in #Rust 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Perl
Perl
#!/usr/bin/perl   # http://www.rosettacode.org/wiki/Compiler/virtual_machine_interpreter use strict; # vm.pl - run rosetta code use warnings; use integer;   my ($binary, $pc, @stack, @data) = ('', 0);   <> =~ /Strings: (\d+)/ or die "bad header"; my @strings = map <> =~ tr/\n""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger,...
Give a code snippet in #Perl A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read inpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Perl
Perl
print join(" ", reverse split), "\n" for <DATA>; __DATA__ ---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert ---------------------...
Give a code snippet in #Perl Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by space...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#AppleScript
AppleScript
on sieveOfEratosthenes(limit) script o property numberList : {missing value} end script   repeat with n from 2 to limit set end of o's numberList to n end repeat   repeat with n from 2 to (limit ^ 0.5) div 1 if (item n of o's numberList is n) then repeat with mult...
Give a code snippet in #AppleScript Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS ...
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
#Fortran
Fortran
program bye write (*,'(a)',advance='no') 'Goodbye, World!' end program bye
Give a code snippet in #Fortran 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/Sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Toka
Toka
needs shell " ." " .\\.txt$" dir.listByPattern
Give a code snippet in #Toka Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, n...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#C.2B.2B
C++
#include <iostream> #include <sstream>   int main(int argc, char *argv[]) { using namespace std;   #if _WIN32 if (argc != 5) { cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n"; cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n"; } else { ...
Give a code snippet in #C.2B.2B Task Write script status to the Windows Event Log
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 ...
#Wren
Wren
var insertionSort = Fn.new { |a| for (i in 1..a.count-1) { var v = a[i] var j = i - 1 while (j >= 0 && a[j] > v) { a[j+1] = a[j] j = j - 1 } a[j+1] = v } }   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] for (a in ...
Give a code snippet in #Wren 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/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Aime
Aime
integer is_numeric(text s) { return !trap_q(alpha, s, 0); }   integer main(void) { if (!is_numeric("8192&*")) { o_text("Not numeric.\n"); } if (is_numeric("8192")) { o_text("Numeric.\n"); }   return 0; }
Give a code snippet in #Aime Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Ar...
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...
#PHP
PHP
<?php // Created with PHP 7.0   function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December');   foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('l...
Give a code snippet in #PHP 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-...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Factor
Factor
USING: kernel math.vectors sequences ;   : dot-product ( u v -- w ) 2dup [ length ] bi@ = [ v. ] [ "Vector lengths must be equal" throw ] if ;
Give a code snippet in #Factor Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Oz
Oz
declare class Demo from BaseObject meth test(...)=Msg {Record.forAll Msg Show} end end   D = {New Demo noop} Constructed = {List.toTuple test {List.number 1 10 1}} in {D test(1 2 3 4)} {D Constructed}
Give a code snippet in #Oz Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Rela...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Smalltalk
Smalltalk
Float e. Float pi. aNumber sqrt. aNumber log. "base 10 logarithm" aNumber ln. "natural logarithm" aNumber exp. "exponential" aNumber abs. "absolute value" aNumber floor. aNumber ceiling. aNumber raisedTo: anotherNumber
Give a code snippet in #Smalltalk Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Sidef
Sidef
func run_utm(state="", blank="", rules=[], tape=[blank], halt="", pos=0) {   if (pos < 0) { pos += tape.len; }   if (pos !~ tape.range) { die "Bad initial position"; }   loop { print "#{state}\t"; tape.range.each { |i| var v = tape[i]; print (i...
Give a code snippet in #Sidef One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
Numerical integration/Gauss-Legendre Quadrature
In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function W ( x ) {\displaystyle ...
#ooRexx
ooRexx
/*--------------------------------------------------------------------- * 31.10.2013 Walter Pachl Translation from REXX (from PL/I) * using ooRexx' rxmath package * which limits the precision to 16 digits *---------------------------------------------------------------...
Give a code snippet in #ooRexx In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Nemerle
Nemerle
def empty = ""; mutable fill_later = "";
Give a code snippet in #Nemerle Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. O...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#FutureBasic
FutureBasic
include "NSLog.incl"   void local fn Doit long penny, nickel, dime, quarter, count = 0   NSLogSetTabInterval(30)   for penny = 0 to 100 for nickel = 0 to 20 for dime = 0 to 10 for quarter = 0 to 4 if penny + nickel * 5 + dime * 10 + quarter * 25 == 100 NSLog(@"%ld pennies\t...
Give a code snippet in #FutureBasic There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Rebol
Rebol
  do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] foreach m system/locale/months [ prin rejoin ["^/^/ " m "^/^/ "] foreach day system/locale/days [prin join copy/part day 2 " "] print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] repeat i 31 [ if attempt [c: to...
Give a code snippet in #Rebol Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Go
Go
package main   import ( "fmt" "strings" "time" )   func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 ||...
Give a code snippet in #Go Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave of...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Sidef
Sidef
func best_shuffle(String orig) -> (String, Number) {   var s = orig.chars var t = s.shuffle   for i (^s) { for j (^s) { if (i!=j && t[i]!=s[j] && t[j]!=s[i]) { t[i, j] = t[j, i] break } } }   (t.join, s ~Z== t -> count(true)) } ...
Give a code snippet in #Sidef Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#D
D
  import std.stdio; import std.string; import std.range; import std.algorithm;   void main() { auto exts = ["zip", "rar", "7z", "gz", "archive", "A##"]; auto filenames = ["MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", ...
Give a code snippet in #D File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#D
D
import std.stdio;   /// Throw Exceptions /// Stack traces are generated compiling with the -g switch. void test1() { throw new Exception("Sample Exception"); }   /// Catch Exceptions void test2() { try { test1(); } catch (Exception ex) { writeln(ex); throw ex; // rethrow } }   /// ...
Give a code snippet in #D Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Thr...
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...
#Bracmat
Bracmat
   :?py { Initialize the accumulating result list. } & ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { This is the subject }  :  ? { Here starts the pattern }  %@?x  ?  %@?y  ?  %@?z ( ? & -1*!z^2+!x^2+!y^2...
Give a code snippet in #Bracmat 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Groovy
Groovy
enum Direction { East([0,1]), South([1,0]), West([0,-1]), North([-1,0]); private static _n private final stepDelta private bound   private Direction(delta) { stepDelta = delta }   public static setN(int n) { Direction._n = n North.bound = 0 South.bound = n-1 ...
Give a code snippet in #Groovy Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 1...
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)...
#REXX
REXX
/*REXX program counts the number of abundant/deficient/perfect numbers within a range.*/ parse arg low high . /*obtain optional arguments from the CL*/ high=word(high low 20000,1); low= word(low 1,1) /*obtain the LOW and HIGH values.*/ say center('integers from ' low " to " hi...
Give a code snippet in #REXX 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Scheme
Scheme
;; The American Soundex System ;; ;; The soundex code consist of the first letter of the name followed ;; by three digits. These three digits are determined by dropping the ;; letters a, e, i, o, u, h, w and y and adding three digits from the ;; remaining letters of the name according to the table below. There ;; are o...
Give a code snippet in #Scheme Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#F.23
F#
open System   let width = int( Console.ReadLine() ) let height = int( Console.ReadLine() ) let arr = Array2D.create width height 0 arr.[0,0] <- 42 printfn "%d" arr.[0,0]
Give a code snippet in #F.23 Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Vlang
Vlang
const ( input = '49927398716 49927398717 1234567812345678 1234567812345670'   t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] )   fn luhn(s string) bool { odd := s.len & 1 mut sum := 0 for i, c in s.split('') { if c < '0' || c > '9' { return false } if i&1 == odd { ...
Give a code snippet in #Vlang The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#JavaScript
JavaScript
  // Node 5.4.1 tested implementation (ES6) "use strict";   let arr = [4, 9, 0, 3, 1, 5]; let isSorted = true; while (isSorted){ for (let i = 0; i< arr.length - 1;i++){ if (arr[i] > arr[i + 1]) { let temp = arr[i]; arr[i] = arr[i + 1]; arr[i...
Give a code snippet in #JavaScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#AppleScript
AppleScript
-- allEqual :: [String] -> Bool on allEqual(xs) _and(zipWith(my _equal, xs, rest of xs)) end allEqual   -- azSorted :: [String] -> Bool on azSorted(xs) _and(zipWith(my azBeforeOrSame, xs, rest of xs)) end azSorted   -- _equal :: a -> a -> Bool on _equal(a, b) a = b end _equal   -- azBefore :: String -> Stri...
Give a code snippet in #AppleScript Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or ...
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...
#BASIC
BASIC
LPRINT "Hello World!"
Give a code snippet in #BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#11l
11l
F factors(=n) [Int] rt V f = 2 I n == 1 rt.append(1) E L I 0 == (n % f) rt.append(f) n I/= f I n == 1 R rt E f++ R rt   F sum_digits(=n) V sum = 0 L n > 0 V m = n % 10 sum += m n -= m ...
Give a code snippet in #11l Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are al...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6   FUNCTION ShoelaceArea(x() AS DOUBLE, y() AS DOUBLE) AS DOUBLE LOCAL i, j AS LONG LOCAL Area AS DOUBLE   j = UBOUND(x()) FOR i = LBOUND(x()) TO UBOUND(x()) Area += (y(j) + y(i)) * (x(j) - x(i)) j = i NEXT i FUNCTION = ABS(Area) / 2 END FUNCTION   FUNCTION PBMAIN (...
Give a code snippet in #PowerBASIC Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs retur...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagoras_tree
Pythagoras tree
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or ...
#Ada
Ada
with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Rectangles; with SDL.Events.Events;   procedure Pythagoras_Tree is   Width  : constant := 600; Height  : constant := 600; Level  : constant := 7;   type Point is record X, Y : Float; end record; B1 : constant Point := (X => ...
Give a code snippet in #Ada The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. Task Construct a Pythagoras tree of order 7 using ...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#AWK
AWK
105 3 Fizz 5 Buzz 7 Baxx
Give a code snippet in #AWK Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#Pari.2FGP
Pari/GP
a1 = [0, 1403580, -810728]; m1 = 2^32-209; a2 = [527612, 0, -1370589]; m2 = 2^32-22853; d = m1+1; seed(s)=x1=x2=[s,0,0]; next_int()= { my(x1i=a1*x1~%m1, x2i=a2*x2~%m2); x1 = [x1i, x1[1], x1[2]]; x2 = [x2i, x2[1], x2[2]]; (x1i-x2i)%m1 + 1; } next_float()=next_int()/d;   seed(1234567); vector(5,i,next_int()) seed...
Give a code snippet in #Pari.2FGP MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle Sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elixir
Elixir
defmodule Sort do def circle_sort(data) do List.to_tuple(data) |> circle_sort(0, length(data)-1) |> Tuple.to_list end   defp circle_sort(data, lo, hi) do case circle_sort(data, lo, hi, 0) do {result, 0} -> result {result, _} -> circle_sort(result, lo, hi) end end   defp circle_...
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/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#UnixPipes
UnixPipes
split() { (while read n ; do test $1 -gt $n && echo $n > $2 || echo $n > $3 done) }   qsort() { (read p; test -n "$p" && ( lc="1.$1" ; gc="2.$1" split $p >(qsort $lc >$lc) >(qsort $gc >$gc); cat $lc <(echo $p) $gc rm -f $lc $gc; )) }   cat to.sort | qsort
Give a code snippet in #UnixPipes 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#C.23
C#
using System;   class Program { static void Main(string[] args) { int[,] a = new int[10, 10]; Random r = new Random();   for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a[i, j] = r.Next(0, 21) + 1; } }   for (int i = 0; i ...
Give a code snippet in #C.23 Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#Bc
Bc
print "\a"
Give a code snippet in #Bc Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell withi...
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
#Ol
Ol
  ; matching: (define regex (string->regex "m/aa(bb|cc)dd/")) (print (regex "aabbddx")) ; => true (print (regex "aaccddx")) ; => true (print (regex "aabcddx")) ; => false   ; substitute part of a string: (define regex (string->regex "s/aa(bb|cc)dd/HAHAHA/")) (print (regex "aabbddx")) ; => HAHAHAx (print (regex "aaccddx...
Give a code snippet in #Ol Task   match a string against a regular expression   substitute part of a string using a regular expression
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 ...
#C
C
#include <stdio.h> #include <stdlib.h>   void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j]   for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i];   beads = calloc(1, max * len);   /* mark the beads */ for (i = 0; i < len; i++) for (...
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#E
E
def version := interp.getProps()["e.version"]
Give a code snippet in #E Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(blo...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#C.23
C#
using System;   namespace RosettaCode.CharacterCode { class Program { static void Main(string[] args) { Console.WriteLine((int) 'a'); //Prints "97" Console.WriteLine((char) 97); //Prints "a" } } }
Give a code snippet in #C.23 Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ALGOL_68
ALGOL 68
main:( LONG INT a=355, b=113; printf(($"a+b = "gl$, a + b)); printf(($"a-b = "gl$, a - b)); printf(($"a*b = a×b = "gl$, a * b)); printf(($"a/b = "gl$, a / b)); printf(($"a OVER b = a%b = a÷b = "gl$, a % b)); printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b)); printf(($"a UP b = a**b = a↑b = ...
Give a code snippet in #ALGOL_68 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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 stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#C.2B.2B
C++
#include <stack>
Give a code snippet in #C.2B.2B 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 stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Racket
Racket
#lang racket   (define (swap! vec i j) (let ([tmp (vector-ref vec i)]) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j tmp)))   (define (knuth-shuffle x) (if (list? x) (vector->list (knuth-shuffle (list->vector x))) (begin (for ([i (in-range (sub1 (vector-length x)) 0 -1)]) (d...
Give a code snippet in #Racket The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#OpenEdge.2FProgress
OpenEdge/Progress
  define variable r as integer no-undo extent 3. define variable m as integer no-undo initial 5. define variable n as integer no-undo initial 3. define variable max_n as integer no-undo.   max_n = m - n.   function combinations returns logical (input pos as integer, input val as integer): define variable i as integer...
Give a code snippet in #OpenEdge.2FProgress Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1...
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.
#MUMPS
MUMPS
  MV(A,U)  ;A is a list of values separated by the string U NEW MAX,T,I FOR I=1:1 SET T=$PIECE(A,U,I) QUIT:T="" S MAX=$SELECT(($DATA(MAX)=0):T,(MAX<T):T,(MAX>=T):MAX) QUIT MAX  
Give a code snippet in #MUMPS 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/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
#gnuplot
gnuplot
!ls
Give a code snippet in #gnuplot 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/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Retro
Retro
'__this_is_a_test___ s:trim-left '__this_is_a_test___ s:trim-right '__this_is_a_test___ s:trim
Give a code snippet in #Retro Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace re...
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 ...
#Eiffel
Eiffel
class APPLICATION create make feature make -- Demonstrate string reversal. do my_string := "Hello World!" my_string.mirror print (my_string) end my_string: STRING -- Used for reversal end
Give a code snippet in #Eiffel 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 Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Cellular_Automata is type Petri_Dish is array (Positive range <>) of Boolean;   procedure Step (Culture : in out Petri_Dish) is Left  : Boolean := False; This  : Boolean; Right : Boolean; begin for Index in Culture'First..Culture'Last - 1 ...
Give a code snippet in #Ada Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current g...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#PL.2FM
PL/M
100H:   /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END; /* CONSOLE OUTPUT ROUTINES */ PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PR$NL: PROCEDURE; CALL...
Give a code snippet in #PL.2FM A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#Raku
Raku
### Formatting ### my $t-style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"'; my $c-style = '"border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;'~ 'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'~ 'vertical-align: bottom;width: 3.25em...
Give a code snippet in #Raku Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─t...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Visual_Basic_.NET
Visual Basic .NET
  implement main open core, console   class predicates fizzbuzz : (integer) -> string procedure (i).   clauses fizzbuzz(X) = S :- X mod 15 = 0, S = "FizzBuzz", !. fizzbuzz(X) = S :- X mod 5 = 0, S = "Buzz", !. fizzbuzz(X) = S :- X mod 3 = 0, S = "Fizz", !. fizzbuzz(X) = S :- S = toString(X).   ...
Give a code snippet in #Visual_Basic_.NET Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   prin...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Icon
Icon
# # The Rosetta Code lexical analyzer in Icon with co-expressions. Based # upon the ATS implementation. # # Usage: lex [INPUTFILE [OUTPUTFILE]] # If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input # or standard output is used, respectively. *) #   $define EOF -1   $define TOKEN_ELSE 0 $defin...
Give a code snippet in #Icon Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#BBC_BASIC
BBC BASIC
number$ = "1" FOR i% = 1 TO 10 number$ = FNlooksay(number$) PRINT number$ NEXT END   DEF FNlooksay(n$) LOCAL i%, j%, c$, o$ i% = 1 REPEAT c$ = MID$(n$,i%,1) j% = i% + 1 WHILE MID$(n$,j%,1) = c$ j% += 1 ENDWHILE ...
Give a code snippet in #BBC_BASIC The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#PowerShell
PowerShell
  class Camera {} class MobilePhone {} class CameraPhone : Camera, MobilePhone {}  
Give a code snippet in #PowerShell Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and Mob...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#OCaml
OCaml
(* Ocamlgraph demo program: solving the Sudoku puzzle using graph coloring Copyright 2004-2007 Sylvain Conchon, Jean-Christophe Filliatre, Julien Signoles   This software is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2, with the...
Give a code snippet in #OCaml Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Go
Go
package main   import ( "fmt" "image/jpeg" "os" "log" "image" )   func loadJpeg(filename string) (image.Image, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close()   img, err := jpeg.Decode(f) if err != nil { return nil, err ...
Give a code snippet in #Go basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expec...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Sidef
Sidef
var sha = frequire('Digest::SHA'); say sha.sha256_hex('Rosetta code');
Give a code snippet in #Sidef SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b78...
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...
#PicoLisp
PicoLisp
(de sieve (N) (let Sieve (range 1 N) (set Sieve) (for I (cdr Sieve) (when I (for (S (nth Sieve (* I I)) S (nth (cdr S) I)) (set S) ) ) ) (filter bool Sieve) ) )
Give a code snippet in #PicoLisp 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; procedure Fraction_Reduction is   type Int_Array is array (Natural range <>) of Integer;   function indexOf(haystack : Int_Array; needle : Integer) return Integer is idx : Integer := 0; begin for straw of haystack loop ...
Give a code snippet in #Ada There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#OCaml
OCaml
let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;;   pow 1 ( * ) 2 16;; (* 65536 *) pow 1.0 ( *. ) 2.0 16;; (* 65536. *)   (* pow is not limited to exponentiation *) pow 0 ( + ) 2 16;; (* 32 *) pow "" ( ^ ) "abc " 10;; ...
Give a code snippet in #OCaml Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Common_Lisp
Common Lisp
(defpackage rosettacode.inverted-index (:use cl)) (in-package rosettacode.inverted-index)   ;; Return a list of tokens in the string LINE. This is rather ;; complicated as CL has no good standard function to do it. (defun tokenize (line) (let ((start 0) (len (length line))) (loop for s = (position-if #'alphanu...
Give a code snippet in #Common_Lisp An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query ter...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Racket
Racket
  -> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...  
Give a code snippet in #Racket Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Wal...
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 ...
#Fantom
Fantom
  abstract class X { Void method1 () { echo ("Method 1 in X") }   abstract Void method2 () }   class Y : X { // Y must override the abstract method in X override Void method2 () { echo ("Method 2 in Y") } }   class Main { public static Void main () { y := Y() y.method1 y.method2...
Give a code snippet in #Fantom 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 operati...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PureBasic
PureBasic
Macro StrTest(Check,tof) Print("Test "+Check+#TAB$) If tof=1 : PrintN("true") : Else : PrintN("false") : EndIf EndMacro   Procedure.b StrBool_eq(a$,b$)  : ProcedureReturn Bool(a$=b$)  : EndProcedure Procedure.b StrBool_n_eq(a$,b$) : ProcedureReturn Bool(a$<>b$)  : EndProcedure Proced...
Give a code snippet in #PureBasic 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Racket
Racket
#lang racket (module+ test (require tests/eli-tester)) (module+ test (test (map char->sms-digit (string->list "ABCDEFGHIJKLMNOPQRSTUVWXYZ.")) => (list 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 9 9 9 9 #f)))   (define char->sms-digit (match-lambda [(? char-lower-case? (app char-upcase C)) (char->sms-digi...
Give a code snippet in #Racket When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Delphi
Delphi
  unit main;   interface   uses Winapi.Windows, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, System.Math, System.Classes;   type TForm1 = class(TForm) tmr1: TTimer; procedure FormCreate(Sender: TObject); procedure tmr1Timer(Sender: TObject); private { Private declarations } public ...
Give a code snippet in #Delphi Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Persp...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Processing
Processing
int g_size = 10; color background_color = color (80, 80, 220); color runner = color (255, 50, 50); color visited_color = color(220, 240, 240); color done_color = color (100, 160, 250); int c_size;   Cell[][] cell; ArrayList<Cell> done = new ArrayList<Cell>(); ArrayList<Cell> visit = new ArrayList<Cell>(); Cell run_cell...
Give a code snippet in #Processing This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Scala
Scala
import org.fusesource.jansi.internal.CLibrary._   object IsATty extends App {   var enabled = true   def apply(enabled: Boolean): Boolean = { // We must be on some unix variant.. try { enabled && isatty(STDIN_FILENO) == 1 } catch { case ignore: Throwable => ignore.printStackTrac...
Give a code snippet in #Scala Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Swift
Swift
import Foundation   func largestProperDivisor(_ n : Int) -> Int? { guard n > 0 else { return nil } if (n & 1) == 0 { return n >> 1 } var p = 3 while p * p <= n { if n % p == 0 { return n / p } p += 2 } return 1 }   for n in (1..<101) { ...
Give a code snippet in #Swift Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigRat   var bernoulli = Fn.new { |n| if (n < 0) Fiber.abort("Argument must be non-negative") var a = List.filled(n+1, null) for (m in 0..n) { a[m] = BigRat.new(1, m+1) var j = m while (j >= 1) { a[j-1] = (a[j-1] - a[j]) * BigRat.ne...
Give a code snippet in #Wren Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Smalltalk
Smalltalk
|a| a := File name: 'input.txt'. (a lastModifyTime) printNl.
Give a code snippet in #Smalltalk Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Wren
Wren
var greedyWordWrap = Fn.new { |text, lineWidth| var words = text.split(" ") var sb = words[0] var spaceLeft = lineWidth - words[0].count for (word in words.skip(1)) { var len = word.count if (len + 1 > spaceLeft) { sb = sb + "\n" + word spaceLeft = lineWidth - len...
Give a code snippet in #Wren Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provi...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#ERRE
ERRE
PROGRAM KNUTH_SHUFFLE   CONST CARDS%=52   DIM PACK%[CARDS%]   BEGIN RANDOMIZE(TIMER) FOR I%=1 TO CARDS% DO PACK%[I%]=I% END FOR FOR N%=CARDS% TO 2 STEP -1 DO SWAP(PACK%[N%],PACK%[1+INT(N%*RND(1))]) END FOR FOR I%=1 TO CARDS% DO PRINT(PACK%[I%];) END FOR PRINT END PROGRAM  
Give a code snippet in #ERRE The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 t...
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 ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. 01 z PIC 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, ...
Give a code snippet in #COBOL 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/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#J
J
iter=: (, 1 , +@|.) @: (,~ 0j_1 ,~ 0j_1*|.) hilbert=: {{0j1+(%{:) +/\0,iter ^: y ''}}  
Give a code snippet in #J Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
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.
#IDL
IDL
b = a^3
Give a code snippet in #IDL Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code