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/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Nim
Nim
import math   proc yellowstone(n: int): seq[int] = assert n >= 3 result = @[1, 2, 3] var present = {1, 2, 3} var start = 4 while result.len < n: var candidate = start while true: if candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1: result.ad...
Give a code snippet in #Nim The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#PHP
PHP
file_put_contents($filename, $data)
Give a code snippet in #PHP Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#Ruby
Ruby
# Generate a continued fraction from a rational number   def r2cf(n1,n2) while n2 > 0 n1, (t1, n2) = n2, n1.divmod(n2) yield t1 end end
Give a code snippet in #Ruby Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 ...
#MAXScript
MAXScript
fn flipArr arr index = ( local new = #() for i = index to 1 by -1 do ( append new arr[i] ) join new (for i in (index+1) to arr.count collect arr[i]) return new )   fn pancakeSort arr = ( if arr.count < 2 then return arr else ( for i = arr.count to 1 by -1 do ( local newArr = for n in 1 to i collect a...
Give a code snippet in #MAXScript 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/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#JavaScript
JavaScript
(() => { 'use strict';   // hashJoin :: [Dict] -> [Dict] -> String -> [Dict] let hashJoin = (tblA, tblB, strJoin) => {   let [jA, jB] = strJoin.split('='), M = tblB.reduce((a, x) => { let id = x[jB]; return ( a[id] ? a[id].push(x) : a[i...
Give a code snippet in #JavaScript An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Groovy
Groovy
System.err.println("Goodbye, World!")
Give a code snippet in #Groovy Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Kotlin
Kotlin
// version 1.1   class TinyInt(i: Int) { private val value = makeTiny(i)   operator fun plus (other: TinyInt): TinyInt = TinyInt(this.value + other.value) operator fun minus(other: TinyInt): TinyInt = TinyInt(this.value - other.value) operator fun times(other: TinyInt): TinyInt = TinyInt(this.value * ot...
Give a code snippet in #Kotlin Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_W
ALGOL W
BEGIN % DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD  % INTEGER GREG, GMONTH, GDAY, GYEAR; STRING(16) ARRAY HOLY5 ( 0 :: 4 ); STRING(16) ARRAY HOLY50 ( 0 :: 4 ); STRING(16) ARRAY DISDAY ( 0 :: 4 ); STRING(16) ARRAY DISSSN ( 0 :: 4 ); INTEGER ARRAY MLENGT ( 0 ...
Give a code snippet in #ALGOL_W Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#APL
APL
r1 ← ⎕UCS ∘ {+/⍵,13×(⍵≥65)∧(⍵<78),(-(⍵≥78)∧(⍵≤90)),(⍵≥97)∧(⍵<110),(-(⍵≥110)∧(⍵≤122))} ∘ ⎕UCS rot13 ← { r1 ¨ ⍵ }
Give a code snippet in #APL Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#360_Assembly
360 Assembly
* Zig-zag matrix 15/08/2015 ZIGZAGMA CSECT USING ZIGZAGMA,R12 set base register LR R12,R15 establish addressability LA R9,N n : matrix size LA R6,1 i=1 LA R7,1 j=1 LR ...
Give a code snippet in #360_Assembly Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Scala
Scala
import java.awt._ import java.awt.image.BufferedImage   import javax.swing._   object JuliaSet extends App { SwingUtilities.invokeLater(() => new JFrame("Julia Set") {   class JuliaSet() extends JPanel { private val (maxIter, zoom) = (300, 1)   override def paintComponent(gg: Graphics): Unit...
Give a code snippet in #Scala Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Lua
Lua
local t = { ["foo"] = "bar", ["baz"] = 6, fortytwo = 7 }   for key,val in pairs(t) do print(string.format("%s: %s", key, val)) end
Give a code snippet in #Lua Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compo...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Pike
Pike
> Calendar.Discordian.now()->format_ext_ymd(); Result: "Pungenday, 59 Bureaucracy 3177" > Calendar.Discordian.Day(Calendar.Day(2011,11,11))->format_ext_ymd(); Result: "Setting Orange, 23 The Aftermath 3177" > Calendar.Discordian.Day(Calendar.Badi.Day(168,13,9))->format_ext_ymd(); Result: "Setting Orange, 23 The Af...
Give a code snippet in #Pike Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#PicoLisp
PicoLisp
  (in '(curl "https://sourceforge.net") # Open a pipe to 'curl' (out NIL (echo)) ) # Echo to standard output  
Give a code snippet in #PicoLisp Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Requ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#Clojure
Clojure
  (defn valid-date? [[y m d]] (and (<= 1 m 12) (<= 1 d 31)))   (defn date-str [[y m d]] (format "%4d-%02d-%02d" y m d))   (defn yr->date [y] (let [[_ m d] (re-find #"(..)(..)" (apply str (reverse (str y))))] [y (Long. m) (Long. d)]))   (defn palindrome-dates [start-yr n] (->> (iterate inc start-yr) ...
Give a code snippet in #Clojure Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a prog...
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)...
#ML
ML
fun proper (number, count, limit, remainder, results) where (count > limit) = rev results | (number, count, limit, remainder, results) = proper (number, count + 1, limit, number rem (count+1), if remainder = 0 then count :: results else results) | number = (proper (number, 1, number div 2, 0, [])) ...
Give a code snippet in #ML 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/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: rot (in string: stri, in integer: encodingKey) is func result var string: encodedStri is ""; local var char: ch is ' '; var integer: index is 0; begin encodedStri := stri; for ch key index range stri do if ch >= 'a' and ch <= 'z' then ...
Give a code snippet in #Seed7 Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Perl
Perl
use feature 'say'; use Socket qw(getaddrinfo getnameinfo);   my ($err, @res) = getaddrinfo('orange.kame.net', 0, { protocol=>Socket::IPPROTO_TCP } ); die "getaddrinfo error: $err" if $err;   say ((getnameinfo($_->{addr}, Socket::NI_NUMERICHOST))[1]) for @res
Give a code snippet in #Perl DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Phix
Phix
function rms(sequence s) atom sqsum = 0 for i=1 to length(s) do sqsum += power(s[i],2) end for return sqrt(sqsum/length(s)) end function ?rms({1,2,3,4,5,6,7,8,9,10})
Give a code snippet in #Phix Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
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 ...
#PHP
PHP
<?php // Read dictionary into array $dictionary = array_fill_keys(file( 'http://www.puzzlers.org/pub/wordlists/unixdict.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ), true); foreach (array_keys($dictionary) as $word) { $reversed_word = strrev($word); if (isset($dictionary[$reversed_word]) && $wo...
Give a code snippet in #PHP 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/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#PicoLisp
PicoLisp
(de neighbor (X Y Cost) (push (prop X 'neighbors) (cons Y Cost)) (push (prop Y 'neighbors) (cons X Cost)) )   (de dijkstra (Curr Dest) (let Cost 0 (until (== Curr Dest) (let (Min T Next) (for N (; Curr neighbors) (with (car N) (let D (+ Cost (cdr N))...
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. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves t...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Java
Java
public static long itFibN(int n) { if (n < 2) return n; long ans = 0; long n1 = 0; long n2 = 1; for(n--; n > 0; n--) { ans = n1 + n2; n1 = n2; n2 = ans; } return ans; }
Give a code snippet in #Java The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   System.print("The tau functions for the first 100 positive integers are:") for (i in 1..100) { Fmt.write("$2d ", Int.divisors(i).count) if (i % 20 == 0) System.print() }
Give a code snippet in #Wren Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to e...
#J
J
Substitute=: ({.@:[)`(I.@:(= {:)~)`]} NB. aside: demonstrate Substitution ] A =: ;/ i. 8 ┌─┬─┬─┬─┬─┬─┬─┬─┐ │0│1│2│3│4│5│6│7│ └─┴─┴─┴─┴─┴─┴─┴─┘ ] B =: ('xxxx' ; 3) ┌────┬─┐ │xxxx│3│ └────┴─┘ B Substitute A ┌─┬─┬─┬────┬─┬─┬─┬─┐ │0│1│2│xxxx│4│5│6│7│ └─┴─┴─┴────┴─┴─┴─┴─┘ B Substitute A , < 3 ┌─┬─┬─┬──...
Give a code snippet in #J A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Lasso
Lasso
define arithmetic_mean(a::staticarray)::decimal => { //sum of the list divided by its length return (with e in #a sum #e) / decimal(#a->size) } define geometric_mean(a::staticarray)::decimal => { // The geometric mean is the nth root of the product of the list local(prod = 1) with e in #a do => { #prod *= #e } re...
Give a code snippet in #Lasso Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldo...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#XQuery
XQuery
  (: Sequence of numbers from 1 to 10 :) let $array := (1 to 10)   (: Short version :) let $short := $array[. mod 2 = 0]   (: Long version with a FLWOR expression :) let $long := for $value in $array where $value mod 2 = 0 return $value   (: Show the results :) return <result> <short>{$s...
Give a code snippet in #XQuery Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#ABAP
ABAP
  TYPES: tty_int TYPE STANDARD TABLE OF i WITH NON-UNIQUE DEFAULT KEY.   DATA(itab) = VALUE tty_int( ( 1 ) ( 2 ) ( 3 ) ).   INSERT 4 INTO TABLE itab. APPEND 5 TO itab. DELETE itab INDEX 1.   cl_demo_output=>display( itab ). cl_demo_output=>disp...
Give a code snippet in #ABAP This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#ALGOL_60
ALGOL 60
for i:=5 step 5 until 25 do OUTINTEGER(i)
Give a code snippet in #ALGOL_60 Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#PicoLisp
PicoLisp
(de add (A B) (mapcar + A B) ) (de sub (A B) (mapcar - A B) ) (de mul (A B) (mapcar '((X) (* X B)) A) ) (de div (A B) (mapcar '((X) (*/ X B)) A) ) (let (X (5 7) Y (2 3)) (println (add X Y)) (println (sub X Y)) (println (mul X 11)) (println (div X 2)) )
Give a code snippet in #PicoLisp Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value...
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...
#XPL0
XPL0
func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat) int Year, Month, Day; \works for years from 1583 onward [if Month<=2 then [Month:= Month+12; Year:= Year-1]; return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400)/7); ];   int Year, Month, LastDay, WD; [Ye...
Give a code snippet in #XPL0 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/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) ...
#Kotlin
Kotlin
fun fizzBuzz() { for (number in 1..100) { println( when { number % 15 == 0 -> "FizzBuzz" number % 3 == 0 -> "Fizz" number % 5 == 0 -> "Buzz" else -> number } ) } }
Give a code snippet in #Kotlin 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   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#BASIC
BASIC
10 N% = RND(1) * 10 + 1 20 PRINT "A NUMBER FROM 1 "; 30 PRINT "TO 10 HAS BEEN "; 40 PRINT "RANDOMLY CHOSEN." 50 FOR Q = 0 TO 1 STEP 0 60 INPUT "ENTER A GUESS. "; G% 70 Q = G% = N% 80 NEXT 90 PRINT "WELL GUESSED!"
Give a code snippet in #BASIC Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Forth
Forth
: faccept ( -- f ) pad 32 accept pad swap >float 0= throw ; : >radians ( deg -- rad ) 180e f/ pi f* ; : >degrees ( rad -- deg ) pi f/ 180e f* ; : sundial cr ." Enter latitude: " faccept >radians fsin cr ." Enter longitude: " faccept cr ." Enter legal meridian: " faccept f- fnegate ( sin[latitude] -longi...
Give a code snippet in #Forth Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#M4
M4
define(`enums', `define(`$2',$1)`'ifelse(eval($#>2),1,`enums(incr($1),shift(shift($@)))')') define(`enum', `enums(1,$@)') enum(a,b,c,d) `c='c
Give a code snippet in #M4 Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Tcl
Tcl
package require Tcl 8.5   proc solveSokoban b { set cols [string length [lindex $b 0]] set dxes [list [expr {-$cols}] $cols -1 1] set i 0 foreach c [split [join $b ""] ""] { switch $c { " " {lappend bdc " "} "#" {lappend bdc "#"} "@" {lappend bdc " ";set startplayer $i } "$" {lappen...
Give a code snippet in #Tcl Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character ar...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Ruby
Ruby
str = "llo world" str.prepend("He") p str #=> "Hello world"
Give a code snippet in #Ruby 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/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Logo
Logo
to mult.table :n type "| | for [i 2 :n] [type form :i 4 0] (print) (print) for [i 2 :n] [ type form :i 2 0 for [j 2 :n] [ type ifelse :i > :j ["| |] [form :i*:j 4 0] ] (print) ] end   mult.table 12  
Give a code snippet in #Logo Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#Phix
Phix
-- -- demo\rosetta\Forest_fire.exw -- ============================ -- -- A burning cell turns into an empty cell -- A tree will burn if at least one neighbor is burning -- A tree ignites with probability F even if no neighbor is burning -- An empty space fills with a tree with probability P -- -- Draws bigger "pix...
Give a code snippet in #Phix This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and S...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#PowerShell
PowerShell
$days = @{ 1 = "first"; 2 = "second"; 3 = "third"; 4 = "fourth"; 5 = "fifth"; 6 = "sixth"; 7 = "seventh"; 8 = "eight"; 9 = "ninth"; 10 = "tenth"; 11 = "eleventh"; 12 = "twelfth"; }   $gifts = @{ 1 = 'A partridge in a pear tree'; 2 = 'Two turtle doves'; 3 = 'Th...
Give a code snippet in #PowerShell Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RSortCompsiteStructure public   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public sta...
Give a code snippet in #NetRexx Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#X86-64_Assembly
X86-64 Assembly
  option casemap:none option literals:on   printf proto :dword, :VARARG exit proto :dword   .data s db "Goodbye, World!",0   .data? d db 20 dup (?) dp dq ? tb dd ?   .code main proc lea rsi, s ;; Put the address of var S into the source index(RSI) xor rcx, rcx ...
Give a code snippet in #X86-64_Assembly This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun nshuffle (sequence) (loop for i from (length sequence) downto 2 do (rotatef (elt sequence (random i)) (elt sequence (1- i )))) sequence)   (defun sortedp (list predicate) (every predicate list (rest list)))   (defun bogosort (list predicate) (do ((list list (nshuffle list))) ...
Give a code snippet in #Common_Lisp 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 | Qu...
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 |...
#Oberon-2
Oberon-2
VAR a: LONGINT; VAR b: INTEGER; b := 10; a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
Give a code snippet in #Oberon-2 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/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 ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface NSString (Extended) -(NSString *)reverseString; @end   @implementation NSString (Extended) -(NSString *) reverseString { NSUInteger len = [self length]; NSMutableString *rtr=[NSMutableString stringWithCapacity:len]; // unichar buf[1];   while (len > ...
Give a code snippet in #Objective-C 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#BBC_BASIC
BBC BASIC
SIZE = 4  : MAX = SIZE-1 Won% = FALSE : Lost% = FALSE @% = 5 DIM Board(MAX,MAX),Stuck% 3   PROCBreed PROCPrint REPEAT Direction = GET-135 IF Direction > 0 AND Direction < 5 THEN Moved% = FALSE PROCShift PROCMerge PROCSh...
Give a code snippet in #BBC_BASIC Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, s...
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)...
#Nim
Nim
  proc sumProperDivisors(number: int) : int = if number < 2 : return 0 for i in 1 .. number div 2 : if number mod i == 0 : result += i   var sum : int deficient = 0 perfect = 0 abundant = 0   for n in 1 .. 20000 : sum = sumProperDivisors(n) if sum < n : inc(deficient) elif sum == n : inc(...
Give a code snippet in #Nim 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/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#Rust
Rust
use std::time::Instant; use separator::Separatable;   const NUMBER_OF_CUBAN_PRIMES: usize = 200; const COLUMNS: usize = 10; const LAST_CUBAN_PRIME: usize = 100_000;   fn main() { println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME); let start = ...
Give a code snippet in #Rust The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#GUISS
GUISS
Start,Programs,Accessories,Media Player,Menu:File,Open, Doubleclick:Icon:Sound.WAV,Button:OK,Button:Play
Give a code snippet in #GUISS Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Lingo
Lingo
-- v can be (2D) point, (3D) vector or list of integers/floats on mean (v) case ilk(v) of #point: cnt = 2 #vector: cnt = 3 #list: cnt = v.count otherwise: return end case sum = 0 repeat with i = 1 to cnt sum = sum + v[i] end repeat return float(sum)/cnt en...
Give a code snippet in #Lingo Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an esta...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#Crystal
Crystal
require "big"   EXPECTED = (1..9).map{ |d| Math.log10(1 + 1.0 / d) }   def fib(n) a, b = 0.to_big_i, 1.to_big_i (0...n).map { ret, a, b = a, b, a + b; ret } end   # powers of 3 as a test sequence def power_of_threes(n) (0...n).map { |k| 3.to_big_i ** k } end   def heads(s) s.map { |a| a.to_s[0].to_i } end   def...
Give a code snippet in #Crystal This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the firs...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Standard_ML
Standard ML
fun subsets xs = foldr (fn (x, rest) => rest @ map (fn ys => x::ys) rest) [[]] xs
Give a code snippet in #Standard_ML A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#REXX
REXX
/* REXX --------------------------------------------------------------- * Compute the Convex Hull for a set of points * Format of the input file: * (16,3) (12,17) (0,6) (-4,-6) (16,6) (16,-7) (16,-3) (17,-4) (5,19) * (19,-8) (3,16) (12,13) (3,-4) (17,5) (-3,15) (-3,-9) (0,11) (-9,-3) * (-4,-2) *------------------------...
Give a code snippet in #REXX Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,1...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Julia
Julia
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n)   const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base...
Give a code snippet in #Julia Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, t...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#R
R
(function(){x<-intToUtf8(34);s<-"(function(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})()
Give a code snippet in #R A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   sel...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
package main   import ( "fmt" "log" )   func main() { var n1, n2 int fmt.Print("enter number: ") if _, err := fmt.Scan(&n1); err != nil { log.Fatal(err) } fmt.Print("enter number: ") if _, err := fmt.Scan(&n2); err != nil { log.Fatal(err) } switch { case n1 < n2: fmt.Println(n1, "less than", n2) case ...
Give a code snippet in #Go Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#COBOL
COBOL
identification division. program-id. StripComments.   data division. working-storage section. 01 line-text pic x(64).   procedure division. main. move "apples, pears # and bananas" to line-text perform show-striped-text   mo...
Give a code snippet in #COBOL Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. W...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#Java
Java
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;   import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities;   ...
Give a code snippet in #Java In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI compon...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Yabasic
Yabasic
coconuts = 11   for ns = 2 to 9 dim hidden(ns) coconuts = int(coconuts / ns) * ns + 1 do nc = coconuts for s = 1 to ns+1 if mod(nc, ns) = 1 then hidden(s-1) = int(nc / ns) nc = nc - (hidden(s-1) + 1) if s = ns and not mod(nc, ns) th...
Give a code snippet in #Yabasic Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Tcl
Tcl
package require Tcl 8.5 package require http package require json package require struct::set   fconfigure stdout -buffering none   # Initialize a cache of lookups array set cache {} proc log msg { #puts -nonewline $msg }   proc get_tasks {category} { global cache if {[info exists cache($category)]} { retu...
Give a code snippet in #Tcl Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out abo...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Phix
Phix
constant inf = 1e300*1e300 function Path(integer u, integer v, sequence next) if next[u,v]=null then return "" end if sequence path = {sprintf("%d",u)} while u!=v do u = next[u,v] path = append(path,sprintf("%d",u)) end while return join(path,"->") end function procedure...
Give a code snippet in #Phix The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already bee...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#Action.21
Action!
DEFINE PTR="CARD"   PROC PrintArray(PTR ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI Print(a(i)) OD Put(']) PutE() RETURN   INT FUNC CustomComparator(CHAR ARRAY s1,s2) INT res   res=s2(0) res==-s1(0) IF res=0 THEN res=SCompare(s1,s2) FI RETURN (res)   INT...
Give a code snippet in #Action.21 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/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...
#PureBasic
PureBasic
Structure charInfo Char.s List Position.i() count.i ;number of occurrences of Char EndStructure   Structure cycleInfo Char.s Position.i EndStructure   Structure cycle List cycle.cycleInfo() EndStructure   Procedure.s shuffleWordLetters(word.s) Protected i Dim originalLetters.s(len(word) - 1) ...
Give a code snippet in #PureBasic 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#zkl
zkl
#!/Homer/craigd/Bin/zkl println(System.argv);
Give a code snippet in #zkl The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script na...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to compute the arithmetic-geomet...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   1.0e-15 var tolerance   def test over over - abs tolerance > enddef   def agm /# n1 n2 -- n3 #/ test while over over + 2 / rot rot * sqrt test endwhile enddef   1 1 2 sqrt / agm tostr ?
Give a code snippet in #Phixmonti This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#ALGOL_68
ALGOL 68
# find and count strong and weak primes # PR heap=128M PR # set heap memory size for Algol 68G # # returns a string representation of n with commas # PROC commatise = ( INT n )STRING: BEGIN STRING result := ""; ...
Give a code snippet in #ALGOL_68 Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Groovy
Groovy
def getAntiPrimes(def limit = 10) { def antiPrimes = [] def candidate = 1L def maxFactors = 0   while (antiPrimes.size() < limit) { def factors = factorize(candidate) if (factors.size() > maxFactors) { maxFactors = factors.size() antiPrimes << candidate } ...
Give a code snippet in #Groovy The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#DWScript
DWScript
public program() { var 四十二 := "♥♦♣♠"; // UTF8 string var строка := "Привет"w; // UTF16 string   console.writeLine:строка; console.writeLine:四十二; }
Give a code snippet in #DWScript As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Processing
Processing
  //Aamrun, 29th June 2022   size(1000,1000);   translate(width/2,height/2); rotate(3*PI/2); fill(#0000ff);   beginShape(); for(int i=0;i<10;i+=2){   vertex(450*cos(i*2*PI/5),450*sin(i*2*PI/5)); } endShape(CLOSE);  
Give a code snippet in #Processing A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or t...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Go
Go
package main   import ( "fmt" "math/rand" )   const samples = 1e6   func main() { fmt.Println("Generator 1 count 0 count  % 1 count") for n := 3; n <= 6; n++ { // function randN, per task description randN := func() int { if rand.Intn(n) == 0 { return 1 ...
Give a code snippet in #Go P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Scheme
Scheme
(define s "hello") (display (string-append s " literal")) (newline) (define s1 (string-append s " literal")) (display s1) (newline)
Give a code snippet in #Scheme String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string li...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Frink
Frink
  println[gcd[12345,98765]]  
Give a code snippet in #Frink Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#Erlang
Erlang
-module(srv). -export([start/0, wait/0]).   start() -> net_kernel:start([srv,shortnames]), erlang:set_cookie(node(), rosetta), Pid = spawn(srv,wait,[]), register(srv,Pid), io:fwrite("~p ready~n",[node(Pid)]), ok.   wait() -> receive {echo, Pid, Any} -> io:fwrite("-> ~p from ~p~n",...
Give a code snippet in #Erlang Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Lingo
Lingo
on hanoi (n, a, b, c) if n > 0 then hanoi(n-1, a, c, b) put "Move disk from" && a && "to" && c hanoi(n-1, b, a, c) end if end
Give a code snippet in #Lingo Task Solve the   Towers of Hanoi   problem with recursion.
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. ...
#AntLang
AntLang
milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo echo["Sleeping..."] sleep[milliseconds] echo["Awake!"]
Give a code snippet in #AntLang 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/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#XPL0
XPL0
def M=3; \array size char NowGen(M+2, M+2), \size with surrounding borders NewGen(M+2, M+2); int X, Y, I, J, N, Gen; code ChOut=8, CrLf=9;   [for Y:= 0 to M+1 do \set up initial state for X:= 0 to M+1 do [NowGen(X,Y):= ^ ; NewGen(X,Y):= ^ ]; NowGen(...
Give a code snippet in #XPL0 The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Emacs_Lisp
Emacs Lisp
(let ((number (1+ (random 10)))) (while (not (= (read-number "Guess the number ") number)) (message "Wrong, try again.")) (message "Well guessed! %d" number))
Give a code snippet in #Emacs_Lisp Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issu...
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 ...
#Lua
Lua
function dotprod(a, b) local ret = 0 for i = 1, #a do ret = ret + a[i] * b[i] end return ret end   print(dotprod({1, 3, -5}, {4, -2, 1}))
Give a code snippet in #Lua 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] ...
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...
#jq
jq
def luhn: def odds: . as $in | reduce range(0; length) as $i ([]; if ($i % 2) == 0 then . + [$in[$i]] else . end); def evens: . as $in | reduce range(1; length) as $i ([]; if ($i % 2) == 1 then . + [$in[$i]] else . end); def digits: map([.]|implode|tonumber); def sumdigits: tostring | explode | digits |...
Give a code snippet in #jq 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Forth
Forth
: third ( a b c -- a b c a ) 2 pick ; : reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n ) cells bounds do i @ third execute cell +loop nip ;   create a 1 , 2 , 3 , 4 , 5 ,   ' + 0 a 5 reduce . \ 15 ' * 1 a 5 reduce . \ 120
Give a code snippet in #Forth Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Batch_File
Batch File
  @echo off ::Prime list using trial division :: Unbounded (well, up to 2^31-1, but you'll kill it before :) :: skips factors of 2 and 3 in candidates and in divisors :: uses integer square root to find max divisor to test :: outputs numbers in rows of 10 right aligned primes setlocal enabledelayedexpansion   cls ech...
Give a code snippet in #Batch_File Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bei...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Oforth
Oforth
: multiplier(n1, n2) #[ n1 n2 * * ] ;   : firstClassNum | x xi y yi z zi | 2.0 ->x 0.5 ->xi 4.0 ->y 0.25 ->yi x y + ->z x y + inv ->zi [ x, y, z ] [ xi, yi, zi ] zipWith(#multiplier) map(#[ 0.5 swap perform ] ) . ;
Give a code snippet in #Oforth In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq;   static class Program { static int[] MianChowla(int n) { int[] mc = new int[n - 1 + 1]; HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>(); int sum; mc[0] = 1; sums.Add(2); for ...
Give a code snippet in #C.23 The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise...
christopher/rosetta-code
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory qw/fromdigits todigitstring/; use utf8; binmode('STDOUT', 'utf8');   sub first_square { my $n = shift; my $sr = substr('1023456789abcdef',0,$n); my $r = int fromdigits($sr, $n) ** .5; my @digits = reverse split '', $sr; TRY: while (1) { ...
Give a code snippet in #Perl Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the searc...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Common_Lisp
Common Lisp
(let ((val 0)) (loop do (incf val) (print val) while (/= 0 (mod val 6))))
Give a code snippet in #Common_Lisp Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   L...
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...
#Delphi
Delphi
  program Compare_a_list_of_strings;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type // generic alias for use helper. The "TArray<string>" will be work too TListString = TArray<string>;   TListStringHelper = record helper for TListString function AllEqual: boolean; function AllLessThan: boolean; ...
Give a code snippet in #Delphi 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...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Chapel
Chapel
use Random;   proc one_of_n(n) { var rand = new RandomStream(); var keep = 1;   for i in 2..n do if rand.getNext() < 1.0 / i then keep = i;   delete rand;   return keep; }
Give a code snippet in #Chapel A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second li...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref symbols   key0 = '0' key1 = 'key0'   hash = '.' -- Initialize the associative array 'hash' to '.' hash[key1] = 'value0' -- Set a specific key/value pair   say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't se...
Give a code snippet in #NetRexx Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#AmigaE
AmigaE
DEF ai[100] : ARRAY OF CHAR, -> static da: PTR TO CHAR, la: PTR TO CHAR   PROC main() da := New(100) -> or NEW la[100] IF da <> NIL ai[0] := da[0] -> first is 0 ai[99] := da[99] -> last is "size"-1 Dispose(da) ENDIF -> using NEW, we must specify the size even when -> "deallocating"...
Give a code snippet in #AmigaE This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retr...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Inverse_video
Terminal control/Inverse video
Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
#zkl
zkl
println("\e[7mReversed\e[m Normal");
Give a code snippet in #zkl Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Python
Python
def isPrime(n): for x in 2, 3: if not n % x: return n == x d = 5 while d * d <= n: for x in 2, 4: if not n % d: return False d += x return True   i = 42 n = 0 while n < 42: if isPrime(i): n += 1 print('n = {:2} {:20,...
Give a code snippet in #Python Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which...
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...
#C
C
  #include <stdio.h> #include <stdlib.h>   int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w;   if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 40...
Give a code snippet in #C 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...
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 ...
#Elm
Elm
  --There are multiple ways to create a function in Elm   --This is a named function multiply x y = x*y   --This is an anonymous function \x y -> x*y  
Give a code snippet in #Elm 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 fr...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Ruby
Ruby
require "prime" limit = 1_000_000   puts "First found longest run of ascending prime gaps up to #{limit}:" p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq puts "\nFirst found longest run of descending prime gaps up to #{limit}:" p Prime.each(limit).each_con...
Give a code snippet in #Ruby Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Python
Python
"ha" * 5 # ==> "hahahahaha"
Give a code snippet in #Python Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Ada
Ada
with Prime_Numbers, Ada.Text_IO;   procedure Test_Kth_Prime is   package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2); use Integer_Numbers;   Out_Length: constant Positive := 10; -- 10 k-th almost primes N: Positive; -- the "current number" to be checked   begin for K in 1 .. 5 loop ...
Give a code snippet in #Ada A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wher...
christopher/rosetta-code
http://rosettacode.org/wiki/Modified_random_distribution
Modified random distribution
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math" "math/rand" "strings" "time" )   func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } }   func commatize(n int) string { s...
Give a code snippet in #F.C5.8Drmul.C3.A6 Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement ...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> main: s=`curl -s -L https://rosettacode.org/wiki/HTTP` {s}len, lenght=0, mov(lenght) {"Size = ",lenght,"\nContent = \n",s}println exit(0)  
Give a code snippet in #Amazing_Hopper Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Chapel
Chapel
  config const gridHeight: int = 100; config const gridWidth: int = 100;   class PBMWriter { var imgDomain: domain(2); var imgData: [imgDomain] int;   proc PBMWriter( height: int, width: int ){ imgDomain = { 1..#height, 1..#width }; }   proc this( i : int, j : int) ref : int{ return this.imgData[ i, j...
Give a code snippet in #Chapel Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Dyalect
Dyalect
func compare(a, b) { if a < b { "A is less than B" } else if a > b { "A is more than B" } else { "A equals B" } }
Give a code snippet in #Dyalect Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Prolog
Prolog
plus :- read_line_to_codes(user_input,X), atom_codes(A, X), atomic_list_concat(L, ' ', A), maplist(atom_number, L, LN), sumlist(LN, N), write(N).
Give a code snippet in #Prolog A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separat...
christopher/rosetta-code