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/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Phix
Phix
function increment(integer i, inc=1) return i+inc end function ?increment(5) -- shows 6 ?increment(5,2) -- shows 7
Give a code snippet in #Phix Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexi...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Python
Python
import math from collections import Counter   def entropy(s): p, lns = Counter(s), float(len(s)) return -sum( count/lns * math.log(count/lns, 2) for count in p.values())   with open(__file__) as f: b=f.read()   print(entropy(b))
Give a code snippet in #Python Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#11l
11l
F derangements(n) [[Int]] r V perm = Array(0 .< n) L I all(enumerate(perm).map((indx, p) -> indx != p)) r [+]= perm I !perm.next_permutation() L.break R r   F subfact(n) -> Int64 R I n < 2 {1 - n} E (subfact(n - 1) + subfact(n - 2)) * (n - 1)   V n = 4 print(‘Derangements of...
Give a code snippet in #11l A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n,...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <stdexcept> using namespace std;   typedef std::pair<double, double> TriPoint;   inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); }   void CheckTriW...
Give a code snippet in #C.2B.2B Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#zkl
zkl
println(Void); 1+Void if(Void){} else { 23 }
Give a code snippet in #zkl
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Haskell
Haskell
data Fruit = Apple | Banana | Cherry deriving Enum
Give a code snippet in #Haskell Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian] NormalizeAngle[d_, full_] := Module[{a = d}, If[Abs[a/full] > 4, a = a - Sign[a] full (Quotient[Abs[a], full] - 4) ]; While[a < -full, a += full]; While[a > full, a -= full]; a ] ClearAll[Degree2Gradian, Degree2Mil...
Give a code snippet in #Mathematica.2FWolfram_Language This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Nim
Nim
import strutils, sequtils, sugar   proc mdroot(n: int): tuple[mp, mdr: int] = var mdr = @[n] while mdr[mdr.high] > 9: var n = 1 for dig in $mdr[mdr.high]: n *= parseInt($dig) mdr.add n (mdr.high, mdr[mdr.high])   for n in [123321, 7739, 893, 899998]: echo align($n, 6)," ",mdroot(n) echo ""   v...
Give a code snippet in #Nim The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\...
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 ...
#Maple
Maple
flip := proc(arr, i) local start, temp, icopy; temp, start, icopy := 0,1,i: while (start < icopy) do arr[start], arr[icopy] := arr[icopy], arr[start]: start:=start+1: icopy:=icopy-1: end do: end proc: findMax := proc(arr, i) local Max, j: Max := 1: for j from 1 to i do if arr[j] > arr[Max] then Max := j:...
Give a code snippet in #Maple 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/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Scala
Scala
object FindCommonDirectoryPath extends App { def commonPath(paths: List[String]): String = { def common(a: List[String], b: List[String]): List[String] = (a, b) match { case (a :: as, b :: bs) if a equals b => a :: common(as, bs) case _ => Nil } if (paths.length < 2) paths.headOption.getOrElse...
Give a code snippet in #Scala Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the d...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Pop11
Pop11
uses objectclass; define :class Point; slot x = 0; slot y = 0; enddefine;   define :class Circle; slot x = 0; slot y = 0; slot r = 1; enddefine;   define :method print(p : Point); printf('Point(' >< x(p) >< ', ' >< y(p) >< ')\n'); enddefine;   define :method print(p : Circle); printf('Circle...
Give a code snippet in #Pop11 Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Neko
Neko
/** <doc>Generate lower case ASCII, in Neko</doc> **/   var slot = 25 var generated = $smake(slot + 1) var lower_a = $sget("a", 0)   /* 'a'+25 down to 'a'+0 */ while slot >= 0 { $sset(generated, slot, slot + lower_a) slot -= 1 }   $print(generated, "\n")
Give a code snippet in #Neko Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a r...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#EchoLisp
EchoLisp
  (require 'struct) (require 'hash) (require 'sql)   (define H null) ;; cache (define T (make-table (struct goodies (name valeur poids volume )))) (define-syntax-rule (name i) (table-xref T i 0)) (define-syntax-rule (valeur i) (table-xref T i 1)) (define-syntax-rule (poids i) (table-xref T i 2)) (define-syntax-rule (vo...
Give a code snippet in #EchoLisp A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Ring
Ring
  # Project : Stem-and-leaf plot   data = list(120) data = [12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, ...
Give a code snippet in #Ring Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#C.23
C#
#include <iostream> #include <string> #include <random>   int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd());   std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) <...
Give a code snippet in #C.23 The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#PowerShell
PowerShell
  <# .Synopsis Finds the deepest common directory path of files passed through the pipeline. .Parameter File PowerShell file object. #> function Get-CommonPath { [CmdletBinding()] param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [System.IO.FileInfo] $File ) process { ...
Give a code snippet in #PowerShell Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Liberty_BASIC
Liberty BASIC
  n=3 dim a(n+1) '+1 needed due to bug in LB that checks loop condition ' until (i=0) or (a(i)<a(i+1)) 'before executing i=i-1 in loop body. for i=1 to n: a(i)=i: next do for i=1 to n: print a(i);: next: print i=n do i=i-1 loop until (i=0) or (a(i)<a(i+1)) j=i+1 k=n while j<k 'swap a(j)...
Give a code snippet in #Liberty_BASIC Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutation...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Batch_File
Batch File
:: Draw a Sphere Task from Rosetta Code :: Batch File Implementation   @echo off rem -------------- define arithmetic "functions" rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744 rem integer sqrt arithmetic function by Aacini and penpen rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t...
Give a code snippet in #Batch_File Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#AWK
AWK
  # syntax: GAWK -f TAKE_NOTES.AWK [notes ... ] # examples: # GAWK -f TAKE_NOTES.AWK Hello world # GAWK -f TAKE_NOTES.AWK A "B C" D # GAWK -f TAKE_NOTES.AWK BEGIN { log_name = "NOTES.TXT" (ARGC == 1) ? show_log() : update_log() exit(0) } function show_log( rec) { while (getline rec <log_name > 0)...
Give a code snippet in #AWK Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT f...
christopher/rosetta-code
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not u...
#Arturo
Arturo
duffinian?: function [n]-> and? [not? prime? n] [ fn: factors n [1] = intersection factors sum fn fn ]   first50: new [] i: 0 while [50 > size first50][ if duffinian? i -> 'first50 ++ i i: i + 1 ]   print "The first 50 Duffinian numbers:" loop split.every: 10 firs...
Give a code snippet in #Arturo A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Java
Java
public class BoxingTheCompass{ private static String[] points = new String[32];   public static void main(String[] args){ buildPoints();   double heading = 0;   for(int i = 0; i<= 32;i++){ heading = i * 11.25; switch(i % 3){ case 1: ...
Give a code snippet in #Java There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and dis...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Arturo
Arturo
parseFasta: function [data][ result: #[] current: ø loop split.lines data 'line [ if? `>` = first line [ current: slice line 1 (size line)-1 set result current "" ] else -> set result current (get result current)++line ] return result ]   t...
Give a code snippet in #Arturo In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rose...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Haskell
Haskell
cof :: [Double] cof = [ 76.18009172947146 , -86.50532032941677 , 24.01409824083091 , -1.231739572450155 , 0.001208650973866179 , -0.000005395239384953 ]   ser :: Double ser = 1.000000000190015   gammaln :: Double -> Double gammaln xx = let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5) ser_ = ser...
Give a code snippet in #Haskell Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/l...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Erlang
Erlang
1> erlang:system_info(wordsize). 4
Give a code snippet in #Erlang Print the word size and endianness of the host machine. See also: Variable size/Get
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...
#11l
11l
T Vector Float x, y   F (x, y) .x = x .y = y   F +(vector) R Vector(.x + vector.x, .y + vector.y)   F -(vector) R Vector(.x - vector.x, .y - vector.y)   F *(mult) R Vector(.x * mult, .y * mult)   F /(denom) R Vector(.x / denom, .y / denom)   F String() R ‘(...
Give a code snippet in #11l 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 (len...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Vala
Vala
void main() { const int N = 15; uint64[] t = {0, 1}; for (int i = 1; i <= N; i++) { for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1]; t[i + 1] = t[i]; for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1]; print(@"$(t[i + 1] - t[i]) "); } print("\n"); }
Give a code snippet in #Vala Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#ALGOL_68
ALGOL 68
BEGIN # calculate elements of Sylvestor's Sequence # PR precision 200 PR # set the number of digits for LONG LONG modes # # returns an array set to the forst n elements of Sylvestor's Sequence # # starting from 2, the elements are the product of the previous # # ...
Give a code snippet in #ALGOL_68 This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylveste...
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) ...
#Fermat
Fermat
  for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od
Give a code snippet in #Fermat 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/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statemen...
#Perl
Perl
use List::Util 'sum';   my @condition = ( sub { 0 }, # dummy sub for index 0 sub { 13==@_ }, sub { 3==sum @_[7..12] }, sub { 2==sum @_[2,4,6,8,10,12] }, sub { $_[5] ? ($_[6] and $_[7]) : 1 }, sub { !$_[2] and !$_[3] a...
Give a code snippet in #Perl This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If stat...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#BQN
BQN
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} (1+•Show) _while_ (≤⟜∞) 1
Give a code snippet in #BQN Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limi...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Phix
Phix
without js -- (file i/o, sleep, task_yield, wait_key) constant filename = "passwd.txt" integer fn constant rec1 = {"jsmith","x",1001,1000,{"Joe Smith","Room 1007","(234)555-8917","(234)555-0077","jsmith@rosettacode.org"},"/home/jsmith","/bin/bash"}, rec2 = {"jdoe","x",1002,1000,{"Jane Doe","Room 1004","(234)555-891...
Give a code snippet in #Phix Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most us...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#REBOL
REBOL
rebol [ Title: "Formatted Numeric Output" URL: http://rosettacode.org/wiki/Formatted_Numeric_Output ]   ; REBOL has no built-in facilities for printing pictured output. ; However, it's not too hard to cook something up using the ; string manipulation facilities.   zeropad: func [ "Pad number with zeros or spaces. ...
Give a code snippet in #REBOL Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Ada
Ada
generic type Real is digits <>; with function Sqrt(X: Real) return Real; with function "**"(X: Real; Y: Real) return Real; package Approximation is   type Number is private;   -- create an approximation function Approx(Value: Real; Sigma: Real) return Number;   -- unary operations and conversion Re...
Give a code snippet in #Ada If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#GAP
GAP
PolynomialRegression := function(x, y, n) local a; a := List([0 .. n], i -> List(x, s -> s^i)); return TransposedMat((a * TransposedMat(a))^-1 * a * TransposedMat([y]))[1]; end;   x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; y := [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];   # Return coefficients in...
Give a code snippet in #GAP Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients a...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Phix
Phix
with javascript_semantics string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" function ls(integer n) if n>length(aleph) then ?9/0 end if -- too big... atom t1 = time()+1 sequence tn = tagset(n), -- {1..n} vcs = repeat(tn,n), -- valid for cols res = ...
Give a code snippet in #Phix A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Perl
Perl
sub prime { my $n = shift || $_; $n % $_ or return for 2 .. sqrt $n; $n > 1 }   print join(', ' => grep prime, 1..100), "\n";
Give a code snippet in #Perl Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops ...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#BQN
BQN
EckStep ← ⊢∾(⊑⊑∘⌽∊1↓⌽)◶(0˙)‿((⊑1+⊑⊐˜ 1↓⊢)⌽) Eck ← {(EckStep⍟(𝕩-1))⥊0} (Eck 10)≍990↓Eck 1000
Give a code snippet in #BQN The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured p...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Python
Python
from PIL import Image   img = Image.new('RGB', (320, 240)) pixels = img.load() pixels[100,100] = (255,0,0) img.show()  
Give a code snippet in #Python Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_turtle_graphics
Simple turtle graphics
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. See imag...
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color import "./turtle" for Turtle   class Main { construct new(width, height) { Window.resize(width, height) Canvas.resize(width, height) Window.title = "Simple turtle graphics" _w = width _h = height }   init() ...
Give a code snippet in #Wren The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#Erlang
Erlang
1> true and false. false 2> false or true. true 3> true xor false. true 4> not false. true 5> not (true and true). false
Give a code snippet in #Erlang Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Rust
Rust
const FILE: &'static str = include_str!("./unixdict.txt");   fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; for c in s.to_lowercase().chars() { if c < prev { return false; } prev = c; }   return true; }   fn find_longest_ordered_words(dict: Vec<&str>) -> Vec<...
Give a code snippet in #Rust An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally...
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.
#E
E
pragma.enable("accumulator") accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }
Give a code snippet in #E 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/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#PicoLisp
PicoLisp
(de streamMerge @ (let Heap (make (while (args) (let? Fd (next) (if (in Fd (read)) (link (cons @ Fd)) (close Fd) ) ) ) ) (make (while Heap (link (caar (setq Heap (sort Heap)))) (if (in (cdar Heap) (re...
Give a code snippet in #PicoLisp 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#FreeBASIC
FreeBASIC
Dim As Integer n, num, pnum Dim As Ulongint m, p Dim As Ulongint limit = 18446744073709551615   Print "The first 15 terms of OEIS:A073916 are:" For n = 1 To 15 num = 0 For m = 1 To limit pnum = 0 For p = 1 To limit If (m Mod p = 0) Then pnum += 1 Next p If pnum = n Th...
Give a code snippet in #FreeBASIC Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION E(1000) E(0)=0 THROUGH L1, FOR I=0, 1, I.GE.1000 THROUGH L2, FOR J=I-1, -1, J.L.0 WHENEVER E(J).E.E(I) E(I+1) = I-J TRANSFER TO L1 END OF CONDITIONAL L2 CONTINUE ...
Give a code snippet in #MAD The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured p...
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 ...
#Kabap
Kabap
  // Calculate the $n'th Fibonacci number   // Set this to how many in the sequence to generate $n = 10;   // These are what hold the current calculation $a = 0; $b = 1;   // This holds the complete sequence that is generated $sequence = "";   // Prepare a loop $i = 0; :calcnextnumber; $i = $i++;   // Do the calculat...
Give a code snippet in #Kabap 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/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Lua
Lua
-- Return an iterator to produce every permutation of list function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] ...
Give a code snippet in #Lua A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n,...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#D
D
import std.stdio, std.typecons, std.algorithm;     mixin template ret(string z) { mixin({ string res;   auto r = z.split(" = "); auto m = r[0].split(", "); auto s = m.join("_");   res ~= "auto " ~ s ~ " = " ~ r[1] ~ ";"; foreach(i, n; m){ res ~= "auto " ~ ...
Give a code snippet in #D Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Python
Python
  import random   class WumpusGame(object):     def __init__(self, edges=[]):   # Create arbitrary caves from a list of edges (see the end of the script for example). if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] ...
Give a code snippet in #Python This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game...
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...
#Retro
Retro
: checkGuess ( gn-gf || f ) over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;   : think ( -n ) random abs 10 mod 1+ ;   : guess ( - ) "I'm thinking of a number between 1 and 10.\n" puts "Try to guess it!\n" puts think [ getToken toNumber checkGuess ] while "You got it!\n" puts ;  
Give a code snippet in #Retro 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/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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program concatStr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Java
Java
double[] list = new double[1000]; double mean = 1.0, std = 0.5; Random rng = new Random(); for(int i = 0;i<list.length;i++) { list[i] = mean + std * rng.nextGaussian(); }
Give a code snippet in #Java Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#REXX
REXX
/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth. */ numeric digits 100 /*ensure enough decimal digits. */ call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ call hamming 1691 ...
Give a code snippet in #REXX Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program permutationSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include ...
Give a code snippet in #ARM_Assembly 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#AWK
AWK
  # syntax: GAWK -f STEM-AND-LEAF_PLOT.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 ...
Give a code snippet in #AWK Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 12...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Euphoria
Euphoria
 
Give a code snippet in #Euphoria Task Create the simplest possible program that is still considered "correct."
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 ...
#Forth
Forth
\ sort 3 integers VARIABLE X VARIABLE Y VARIABLE Z   : VARS@ ( --- n n n) X @ Y @ Z @ ; \ read variables : VARS! ( n n n -- ) Z ! Y ! X ! ; \ store variables   : ?SWAP ( a b -- a b) \ conditional swap 2DUP < IF SWAP THEN ;   : SORT3INTS ( a b c -- c b a)  ?SWAP >R  ?SWAP R>  ?SWAP ;
Give a code snippet in #Forth 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/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Clojure
Clojure
(defprotocol Printable (print-it [this] "Prints out the Printable."))   (deftype Point [x y] Printable (print-it [this] (println (str "Point: " x " " y))))   (defn create-point "Redundant constructor function." [x y] (Point. x y))   (deftype Circle [x y r] Printable (print-it [this] (println (str "Circl...
Give a code snippet in #Clojure Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Sidef
Sidef
func is_prime_digital(n) { n.is_prime && n.digits.all { .is_prime } }   say is_prime_digital.first(25).join(',') say is_prime_digital.nth(100)
Give a code snippet in #Sidef The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hund...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Java
Java
import java.util.Arrays;   public class FourSquares { public static void main(String[] args) { fourSquare(1, 7, true, true); fourSquare(3, 9, true, true); fourSquare(0, 9, false, false); }   private static void fourSquare(int low, int high, boolean unique, boolean print) { in...
Give a code snippet in #Java 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#11l
11l
F token_with_escape(a, escape = ‘^’, separator = ‘|’) [String] result V token = ‘’ V state = 0 L(c) a I state == 0 I c == escape state = 1 E I c == separator result.append(token) token = ‘’ E token ‘’= c E I state == 1 ...
Give a code snippet in #11l Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitt...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Arturo
Arturo
convertKelvins: function [k][ #[ celcius: k - 273.15 fahrenheit: (k * 9/5.0)-459.67 rankine: k * 9/5.0 ] ]   print convertKelvins 100
Give a code snippet in #Arturo There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#ALGOL-M
ALGOL-M
begin integer function square(x); integer x; square := x * x;   integer function cube(x); integer x; cube := x * x * x;   integer c, s, seen; seen := 0; while seen < 30 do begin while cube(c) < square(s) do c := c + 1; if square(s) <> cube(c) then begin if (seen/5 <> (seen-1)/5) then write(...
Give a code snippet in #ALGOL-M Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
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...
#Ada
Ada
package Integer_Exponentiation is -- int^int procedure Exponentiate (Argument : in Integer; Exponent : in Natural; Result  : out Integer); function "**" (Left  : Integer; Right : Natural) return Integer;   -- real^int p...
Give a code snippet in #Ada 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 proce...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#Icon_and_Unicon
Icon and Unicon
procedure deepcopy(A, cache) #: return a deepcopy of A local k   /cache := table() # used to handle multireferenced objects if \cache[A] then return cache[A]   case type(A) of { "table"|"list": { cache[A] := copy(A) every cache[A][k := key(A)] := deepcopy(A[k], ca...
Give a code snippet in #Icon_and_Unicon Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de addComplex (A B) (cons (+ (car A) (car B)) # Real (+ (cdr A) (cdr B)) ) ) # Imag   (de mulComplex (A B) (cons (- (*/ (car A) (car B) 1.0) (*/ (cdr A) (cdr B) 1.0) ) (+ (*/ (car A) (cdr B) 1.0) (*/ (cdr A) (car B) 1.0)...
Give a code snippet in #PicoLisp A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displa...
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) ...
#Delphi
Delphi
program FizzBuzz;   {$APPTYPE CONSOLE}   uses SysUtils;   var i: Integer; begin for i := 1 to 100 do begin if i mod 15 = 0 then Writeln('FizzBuzz') else if i mod 3 = 0 then Writeln('Fizz') else if i mod 5 = 0 then Writeln('Buzz') else Writeln(i); end; end.
Give a code snippet in #Delphi 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/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Objeck
Objeck
class SumDigits { function : Main(args : String[]) ~ Nil { SumDigit(1)->PrintLine(); SumDigit(12345)->PrintLine(); SumDigit(0xfe, 16)->PrintLine(); SumDigit(0xf0e, 16)->PrintLine(); }   function : SumDigit(value : Int, base : Int := 10) ~ Int { sum := 0; do { sum += value % base; ...
Give a code snippet in #Objeck Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#MATLAB
MATLAB
>> unique([1 2 6 3 6 4 5 6])   ans =   1 2 3 4 5 6
Give a code snippet in #MATLAB 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/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.
#Maple
Maple
  > map( sqrt, [ 1.1, 3.2, 5.7 ] ); [1.048808848, 1.788854382, 2.387467277]   > map( x -> x + 1, { 1, 3, 5 } ); {2, 4, 6}   > sqrt~( [ 1.1, 3.2, 5.7 ] ); [1.048808848, 1.788854382, 2.387467277]   > (x -> x + 1)~( { 1, 3, 5 } ); ...
Give a code snippet in #Maple Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Lasso
Lasso
define randomparens(num::integer,open::string='[',close::string=']') => { local(out) = array   with i in 1 to #num do { #out->insert(']', integer_random(1,#out->size || 1)) #out->insert('[', integer_random(1,#out->size || 1)) } return #out->join }   define validateparens(input::string,o...
Give a code snippet in #Lasso Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-n...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#D
D
bool semiprime(long n) pure nothrow @safe @nogc { auto nf = 0; foreach (immutable i; 2 .. n + 1) { while (n % i == 0) { if (nf == 2) return false; nf++; n /= i; } } return nf == 2; }   void main() { import std.stdio;   foreach (...
Give a code snippet in #D Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Tcl
Tcl
package require ripemd160 package require sha256   # Exactly the algorithm from https://en.bitcoin.it/wiki/Base58Check_encoding proc base58encode data { set digits "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" for {set zeroes 0} {[string index $data 0] eq "\x00"} {incr zeroes} { set data [string...
Give a code snippet in #Tcl Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in orde...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Elixir
Elixir
import Integer   defmodule Rectangle do def cut_it(h, w) when is_odd(h) and is_odd(w), do: 0 def cut_it(h, w) when is_odd(h), do: cut_it(w, h) def cut_it(_, 1), do: 1 def cut_it(h, 2), do: h def cut_it(2, w), do: w def cut_it(h, w) do grid = List.duplicate(false, (h + 1) * (w + 1)) t = div(h, 2) * ...
Give a code snippet in #Elixir A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such path...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#BBC_BASIC
BBC BASIC
SYS "LoadLibrary", "URLMON.DLL" TO urlmon% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF% SYS "LoadLibrary", "WININET.DLL" TO wininet% SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%   url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" file$ = @tmp$+"n...
Give a code snippet in #BBC_BASIC Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off thi...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#AWK
AWK
  # syntax: GAWK -f MOBIUS_FUNCTION.AWK # converted from Java BEGIN { printf("first 199 terms of the mobius sequence:\n ") for (n=1; n<200; n++) { printf("%3d",mobius(n)) if ((n+1) % 20 == 0) { printf("\n") } } exit(0) } function mobius(n, i,j,mu_max) { if (n in MU) { ...
Give a code snippet in #AWK The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Kotlin
Kotlin
// version 1.0.6   fun fibWord(n: Int): String { if (n < 1) throw IllegalArgumentException("Argument can't be less than 1") if (n == 1) return "1" val words = Array(n){ "" } words[0] = "1" words[1] = "0" for (i in 2 until n) words[i] = words[i - 1] + words[i - 2] return words[n - 1] }   fun ...
Give a code snippet in #Kotlin The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#ALGOL_68
ALGOL 68
INT a, b; read((a, b)) PR ASSERT a >= 0 & b > 0 PR;
Give a code snippet in #ALGOL_68 Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Go
Go
package main   import ( "fmt" "os" )   // A fairly close port of the Bentley code, but parameterized to better // conform to the algorithm description in the task, which didn't assume // constants for i, j, m, and seed. also parameterized here are k, // the reordering factor, and s, the number of intial number...
Give a code snippet in #Go A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Picat
Picat
go => test("upraisers"), test("Δημοτική"), nl.   test(S) => println(s=S), println(butfirst=S.slice(2)), println(butfirst=S.tail), println(butfirst=S[2..S.len]),   println(butlast=S.but_last()),   println(butfirst_butlast=S.tail.but_last), println(butfirst_butlast=slice(S,2,S.length-1)), println(...
Give a code snippet in #Picat The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed I...
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 ...
#Julia
Julia
julia> 四十二 = "voilà"; julia> println(四十二) voilà
Give a code snippet in #Julia 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#lambdatalk
lambdatalk
  {def move {lambda {:n :from :to :via} {if {<= :n 0} then > else {move {- :n 1} :from :via :to} move disk :n from :from to :to {br} {move {- :n 1} :via :to :from} }}} -> move {move 4 A B C} > move disk 1 from A to C > move disk 2 from A to B > move disk 1 from C to B > move disk 3 from A to C...
Give a code snippet in #lambdatalk Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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
var jortSort = function( array ) {   // sort the array var originalArray = array.slice(0); array.sort( function(a,b){return a - b} );   // compare to see if it was originally sorted for (var i = 0; i < originalArray.length; ++i) { if (originalArray[i] !== array[i]) return false; }   return true; };
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/Jaro_similarity
Jaro similarity
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an exact match. Definition The...
#Nim
Nim
import lenientops   func jaro(s1, s2: string): float =   if s1.len == 0 and s2.len == 0: return 1 if s1.len == 0 or s2.len == 0: return 0   let matchDistance = max(s1.len, s2.len) div 2 - 1 var s1Matches = newSeq[bool](s1.len) var s2Matches = newSeq[bool](s2.len) var matches = 0 for i in 0..s1.high: f...
Give a code snippet in #Nim The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   0   equates to no similarities and   1   is an e...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#zkl
zkl
#define name [0|1] #if [0|1|name] #else, #endif
Give a code snippet in #zkl Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" mean...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#MiniZinc
MiniZinc
  %Latin Squares in Reduced Form. Nigel Galloway, September 5th., 2019 include "alldifferent.mzn"; int: N; array[1..N,1..N] of var 1..N: p; constraint forall(n in 1..N)(p[1,n]=n /\ p[n,1]=n); constraint forall(n in 1..N)(alldifferent([p[n,g]|g in 1..N])/\alldifferent([p[g,n]|g in 1..N]));  
Give a code snippet in #MiniZinc A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Wren
Wren
var func = Fn.new { |n| var i = 1 while (true) { if (i == 1) { i = i + 1 continue // jumps to next iteration } System.print(i) if (i == n) break // exits while loop i = i + 1 } if (n < 3) return // exits function System.print(n + 1) }  ...
Give a code snippet in #Wren Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Sum_Of_Squares is type Float_Array is array (Integer range <>) of Float;   function Sum_Of_Squares (X : Float_Array) return Float is Sum : Float := 0.0; begin for I in X'Range loop Sum := Sum + X (I) ** 2; end loop; return Su...
Give a code snippet in #Ada Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Home_primes
Home primes
This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of an integer n greater than 1 is...
#REXX
REXX
/*REXX program finds and displays the home prime of a range of positive integers. */ numeric digits 20 /*ensure handling of larger integers. */ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 2 ...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Action.21
Action!
INCLUDE "H6:RGBCIRCL.ACT" ;from task Midpoint circle algorithm   RGB black,white,yellow,blue   DEFINE PTR="CARD" TYPE PointB=[BYTE px,py] TYPE Queue=[PTR qfront,qrear,qdata INT capacity]   PROC QueueInit(Queue POINTER q) DEFINE MAXSIZE="500" CARD ARRAY a(MAXSIZE)   q.qfront=0 q.qrear=0 q.capacity=MAXSIZE q....
Give a code snippet in #Action.21 Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point tow...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#11l
11l
V n = BigInt(‘9516311845790656153499716760847001433441357’) V e = BigInt(65537) V d = BigInt(‘5617843187844953170308463622230283376298685’)   V txt = ‘Rosetta Code’   print(‘Plain text: ’txt)   V txtN = txt.reduce(BigInt(0), (a, b) -> a * 256 + b.code) print(‘Plain text as a number: ’txtN)   V enc = pow(txt...
Give a code snippet in #11l Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption i...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#PureBasic
PureBasic
;Forward procedure declare defined with no arguments and that returns a string Declare.s booTwo() ;Forward procedure declare defined with two arguments and that returns a float Declare.f moo(x.f, y.f) ;Forward procedure declare with two arguments and an optional argument and that returns a float Declare.f cmoo(x.f, y.f...
Give a code snippet in #PureBasic Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restricti...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Positional_read
Terminal control/Positional read
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, r...
#Perl
Perl
# 20200917 added Perl programming solution   use strict; use warnings;   use Curses;   initscr or die;   my $win = Curses->new;   foreach my $row (0..9) { $win->addstr( $row , 0, join('', map { chr(int(rand(50)) + 41) } (0..9))) };   my $icol = 3 - 1; my $irow = 6 - 1;   my $ch = $win->inch($irow,$icol);   $win->add...
Give a code snippet in #Perl Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display r...
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...
#Plain_English
Plain English
To run: Start up. Play guess the number. Wait for the escape key. Shut down.   To play guess the number: Pick a secret number between 1 and 10. Write "I picked a secret number between 1 and 10." to the console. Loop. Write "What is your guess? " to the console without advancing. Read a number from the console. If the n...
Give a code snippet in #Plain_English 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Kotlin
Kotlin
// version 1.1.3   val csv = "Character,Speech\n" + "The multitude,The messiah! Show us the messiah!\n" + "Brians mother,<angry>Now you listen here! He's not the messiah; " + "he's a very naughty boy! Now go away!</angry>\n" + "The multitude,Who are you?\n" + "Brians mother,I'm his mother; that...
Give a code snippet in #Kotlin Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Crystal
Crystal
  puts [1, 2, 3, 4, 5].sample(1)  
Give a code snippet in #Crystal Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#ALGOL_68
ALGOL 68
# Calculate Levenshtein distance between strings - translated from the Action! sample # BEGIN   PROC damerau levenshtein distance = (STRING str1, str2)INT: BEGIN   INT m=UPB str1; INT n=UPB str2;   (0:m,0:n)INT matrix;   FOR i FROM 0 TO m DO FOR j FROM 0 TO n DO matrix(i,j):=0 OD OD; FOR i TO m DO matrix(i,1)...
Give a code snippet in #ALGOL_68 This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#jq
jq
# Output: an array of the words when read around the rim def read_teacup: . as $in | [range(0; length) | $in[.:] + $in[:.] ];   # Boolean def is_teacup_word($dict): . as $in | all( range(1; length); . as $i | $dict[ $in[$i:] + $in[:$i] ]) ;   # Output: a stream of the eligible teacup words def teacup_words: d...
Give a code snippet in #jq On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still en...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. LOOK-AND-SAY-SEQ.   DATA DIVISION. WORKING-STORAGE SECTION. 01 SEQUENCES. 02 CUR-SEQ PIC X(80) VALUE "1". 02 CUR-CHARS REDEFINES CUR-SEQ PIC X OCCURS 80 TIMES INDEXED BY CI. ...
Give a code snippet in #COBOL 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#PHP
PHP
  echo "\033[".$x.",".$y."H"; // Position line $y and column $x. echo "\033[".$n."A"; // Up $n lines. echo "\033[".$n."B"; // Down $n lines. echo "\033[".$n."C"; // Forward $n columns. echo "\033[".$n."D"; // Backward $n columns. echo "\033[2J"; // Clear the screen, move to (0,0).  
Give a code snippet in #PHP Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code