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/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Scala
Scala
import scala._ // Wild card -- all of scala is imported import scala.{ Predef => _, _ } // Exception, everything except Predef def f[M[_]] // Higher kinded type parameter def f(m: M[_]) // Existential type _ + _ // Anonymous function placeholder parameter m _ // Eta expansion of me...
Give a code snippet in #Scala Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#REXX
REXX
Note that the second set of angles: 90 180 270 360 is the same as: 90 180 -90 0 and: -270 -180 -90 -360 and other combinations.
Give a code snippet in #REXX When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first readi...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[ct, FunctionMatchQ, ValidFunctionQ, ProcessString] ct = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3...
Give a code snippet in #Mathematica.2FWolfram_Language The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: a...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Q
Q
q)l:2 9 3 8 4 7 q)max l 9
Give a code snippet in #Q Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#Nim
Nim
import algorithm, strformat, strutils, tables   type   Node = ref object edges: Table[char, Node] # Edges (forward links). link: Node # Suffix link (backward link). len: int # Length of the node.   Eertree = object nodes: seq[Node] rto: Node # Odd...
Give a code snippet in #Nim An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for th...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Python
Python
def circle(self, x0, y0, radius, colour=black): f = 1 - radius ddf_x = 1 ddf_y = -2 * radius x = 0 y = radius self.set(x0, y0 + radius, colour) self.set(x0, y0 - radius, colour) self.set(x0 + radius, y0, colour) self.set(x0 - radius, y0, colour)   while x < y: if f >= 0: ...
Give a code snippet in #Python Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#F.23
F#
> let compose f g x = f (g x);;   val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
Give a code snippet in #F.23 Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Scala
Scala
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}"   println(f" n cnt PROPER DIVISORS") val (count, list) = (1 to 20000).foldLeft( (0, List[Int]()) ) { (max, i) => val divisors = properDivisors(...
Give a code snippet in #Scala The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divis...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Gambas
Gambas
Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017 Dim siCount, siCounter, siLength As Short 'Counters Dim siLongest As Short = -1 'To stor...
Give a code snippet in #Gambas Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either le...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#.D0.9C.D0.9A-61.2F52
МК-61/52
1 П4   3 ^ 1 6 ПП 09 С/П   П7 <-> П0 КПП7 L0 12 В/О   ИП4 С/П КИП4 В/О
Give a code snippet in #.D0.9C.D0.9A-61.2F52 Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Prolog
Prolog
  iroot(_, 0, 0) :- !. iroot(M, N, R) :- M > 1, (N > 0 -> irootpos(M, N, R) ; N /\ 1 =:= 1, NegN is -N, irootpos(M, NegN, R0), R is -R0).   irootpos(N, A, R) :- X0 is 1 << (msb(A) div N), % initial guess is 2^(log2(A) / N) newton(N, A, X0, X1), iroot_loop(A, X1, N, A, R)...
Give a code snippet in #Prolog Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#TXR
TXR
#!/usr/bin/txr @(next :args) @(cases) @TO @SUBJ @ (maybe) @CC @ (or) @ (bind CC "") @ (end) @(or) @ (throw error "must specify at least To and Subject") @(end) @(next *stdin*) @(collect) @BODY @(end) @(output (open-command `mail -s "@SUBJ" -a CC: "@CC" "@TO"` "w")) @(repeat) @BODY @(end) . @(end)
Give a code snippet in #TXR Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. S...
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 ...
#Phix
Phix
with javascript_semantics requires("0.8.2") -- (just the use of papply() at the end) function levenshtein(string a, b) integer n = length(a), m = length(b) if n=0 then return m end if if m=0 then return n end if sequence d = repeat(repeat(0, m+1), n+1) for i=1 to n do d[i+1][1]...
Give a code snippet in #Phix This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may ...
#Raku
Raku
my $rows = 10; my $cols = 10;   my $message = q:to/END/; .....R.... ......O... .......S.. ........E. T........T .A........ ..C....... ...O...... ....D..... .....E.... END   my %dir = '→' => (1,0), '↘' => (1,1), '↓' => (0,1), '↙' => (-1,1), '←' => (-1,0), ...
Give a code snippet in #Raku A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spel...
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...
#Julia
Julia
  julia> perms(l) = isempty(l) ? [l] : [[x; y] for x in l for y in perms(setdiff(l, x))]  
Give a code snippet in #Julia 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   gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Common_Lisp
Common Lisp
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By...
Give a code snippet in #Common_Lisp 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Scheme
Scheme
; Racket has this built in, but it's not standard (define (take lst n) (if (or (null? lst) (<= n 0)) '() (cons (car lst) (take (cdr lst) (- n 1)))))   (let ((days '("first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth"))   (gifts '("A p...
Give a code snippet in #Scheme Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle Sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Action.21
Action!
DEFINE MAX_COUNT="100" INT ARRAY stack(MAX_COUNT) INT stackSize   PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1)...
Give a code snippet in #Action.21 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Nemerle
Nemerle
using System; using System.Console;   module StrRep { Repeat(this s : string, n : int) : string { String('x', n).Replace("x", s) }   Main() : void { WriteLine("ha".Repeat(5)); WriteLine("*".Repeat(5)); WriteLine(String('*', 5)); // repeating single char   } }
Give a code snippet in #Nemerle Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#jq
jq
def powerset: reduce .[] as $i ([[]]; reduce .[] as $r (.; . + [$r + [$i]]));
Give a code snippet in #jq A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Oforth
Oforth
: quibbing(l) -- string | i s | StringBuffer new "{" << l size dup 1- ->s loop: i [ l at(i) << i s < ifTrue: [ ", " << continue ] i s == ifTrue: [ " and " << ] ] "}" << dup freeze ;
Give a code snippet in #Oforth Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An i...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#KonsolScript
KonsolScript
function factorial(Number n):Number { Var:Number ret; if (n >= 0) { ret = 1; Var:Number i = 1; for (i = 1; i <= n; i++) { ret = ret * i; } } else { ret = 0; } return ret; }
Give a code snippet in #KonsolScript Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#J
J
  NB. define a stack class coclass 'Stack' create =: 3 : 'items =: i. 0' push =: 3 : '# items =: items , < y' top =: 3 : '> {: items' pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;') destroy =: codestroy cocurrent 'base'   names_Stack_'' NB. all names create destroy pop push ...
Give a code snippet in #J Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#GAP
GAP
IsEvenInt(n); IsOddInt(n);
Give a code snippet in #GAP Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide...
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) ...
#Maxima
Maxima
for n:1 thru 100 do if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline()) elseif mod(n, 3) = 0 then (sprint("Fizz"), newline()) elseif mod(n,5) = 0 then (sprint("Buzz"), newline()) else (sprint(n), newline());
Give a code snippet in #Maxima 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/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#PL.2FM
PL/M
100H:   /* FIND SUM OF SQUARE OF DIGITS OF NUMBER */ DIGIT$SQUARE: PROCEDURE (N) BYTE; DECLARE (N, T, D) BYTE; T = 0; DO WHILE N > 0; D = N MOD 10; T = T + D * D; N = N / 10; END; RETURN T; END DIGIT$SQUARE;   /* CHECK IF NUMBER IS HAPPY */ HAPPY: PROCEDURE (N) BYTE; DECL...
Give a code snippet in #PL.2FM From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Argile
Argile
use std   let X be an int for each X from 99 down to 1 prints X bottles of beer on the wall prints X bottles of beer prints "Take one down, pass it" around if X == 1 echo No more "beer." Call da "amber lamps" break X-- prints X bottles of beer on the wall "\n" X++ .:around :. -> text {X>59 ? "ar...
Give a code snippet in #Argile Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 9...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#JavaScript
JavaScript
// Sample classes for reflection function Super(name) { this.name = name; this.superOwn = function() { return 'super owned'; }; } Super.prototype = { constructor: Super className: 'super', toString: function() { return "Super(" + this.name + ")"; }, doSup: function() { return 'did super stuff'; ...
Give a code snippet in #JavaScript Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#C.23
C#
using System;   namespace AllSame { class Program { static void Analyze(string s) { Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length); if (s.Length > 1) { var b = s[0]; for (int i = 1; i < s.Length; i++) { ...
Give a code snippet in #C.23 Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each s...
christopher/rosetta-code
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f = Compile[{{ll, _Integer}, {n, _Integer}}, Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2}, l = Abs[ll]; digitcount = Floor[Log[10, l]]; log10power = Log[10, pwr]; raised = -1; found = 0; While[found < n, raised++; firstdigits = Floor[10^(FractionalPart[lo...
Give a code snippet in #Mathematica.2FWolfram_Language (This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#Factor
Factor
USING: kernel sequences ; IN: palindrome   : palindrome? ( string -- ? ) dup reverse = ;
Give a code snippet in #Factor Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Slate
Slate
#(1 2 3 4 5) select: [| :number | number isEven].
Give a code snippet in #Slate 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/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Euphoria
Euphoria
  include std/console.e include std/mathcons.e   sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}}   function atan2(atom y, atom x) return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y) end function   function MeanAngle(sequence angles) atom x = 0, y = 0 integer l = length(angles)   for i = 1 to length(ang...
Give a code snippet in #Euphoria When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first r...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#PARI.2FGP
PARI/GP
ssd(n)=n=digits(n); sum(i=1, #n, n[i]^2); happy(n)=while(n>6, n=ssd(n)); n==1; ct(n)=my(f=n!,s=10^n-1,d); forvec(v=vector(9,i,[0,n]), d=vector(9,i, if(i>8,n,v[i+1])-v[i]); if(happy(sum(i=1,9,d[i]*i^2)), s-=f/prod(i=1,9,d[i]!)/v[1]!), 1); s; ct(8)
Give a code snippet in #PARI.2FGP If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate =...
christopher/rosetta-code
http://rosettacode.org/wiki/Topological_sort
Topological sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Java
Java
import java.util.*;   public class TopologicalSort {   public static void main(String[] args) { String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05," + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";   Graph g = new Graph(s, new int[][]{ {2, 0}...
Give a code snippet in #Java Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#C.2B.2B
C++
    /* function with no arguments */ foo();  
Give a code snippet in #C.2B.2B Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a ...
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.
#Factor
Factor
10 <iota> >array [ even? ] filter . ! prints { 0 2 4 6 8 }
Give a code snippet in #Factor 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/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)...
#Wren
Wren
import "/dynamic" for Tuple, Struct   var Point = Tuple.create("Point", ["x", "y"])   var Triangle = Struct.create("Triangle", ["p1", "p2", "p3"])   var det2D = Fn.new { |t| return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) }   var checkTriWinding = Fn...
Give a code snippet in #Wren 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/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 ...
#OPL
OPL
FIBON: REM Fibonacci sequence is generated to the Organiser II floating point variable limit. REM CLEAR/ON key quits. REM Mikesan - http://forum.psion2.org/ LOCAL A,B,C A=1 :B=1 :C=1 PRINT A, DO C=A+B A=B B=C PRINT A, UNTIL GET=1
Give a code snippet in #OPL 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 g...
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Keyboard
Simulate input/Keyboard
Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
#REXX
REXX
/*REXX pgm shows how to use the REXX/PC PRESS cmd to simulate keyboard input.*/   call press 'This text will be put into a buffer as if it came from the keyboard'   /* [↑] text will be available for any program to use (including DOS).*/ /*stick a fork in it, we're all d...
Give a code snippet in #REXX Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { val s1 = "abracadabra" val s2 = "abra" println("$s1 begins with $s2 : ${s1.startsWith(s2)}") println("$s1 ends with $s2  : ${s1.endsWith(s2)}") val b = s2 in s1 print("$s1 contains $s2  : $b") if (b) println(" at locations ${s1.index...
Give a code snippet in #Kotlin 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/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#F.23
F#
  open System.IO open System.Xml.XPath   let xml = new StringReader(""" <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item ...
Give a code snippet in #F.23 Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #4...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Objective-C
Objective-C
@interface Demo : NSObject { // Omitted ... }   - (double) hypotenuseOfX: (double)x andY: (double)y; - (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;   @end
Give a code snippet in #Objective-C Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relie...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET x=5: GO SUB 1000: PRINT "5! = ";r 999 STOP 1000 REM ************* 1001 REM * FACTORIAL * 1002 REM ************* 1010 LET r=1 1020 IF x<2 THEN RETURN 1030 FOR i=2 TO x: LET r=r*i: NEXT i 1040 RETURN
Give a code snippet in #ZX_Spectrum_Basic Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the fact...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Phix
Phix
function play(integer prisoners, iterations, bool optimal) sequence drawers = shuffle(tagset(prisoners)) integer pardoned = 0 bool found = false for i=1 to iterations do drawers = shuffle(drawers) for prisoner=1 to prisoners do found = false integer drawer = iff(o...
Give a code snippet in #Phix The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start ou...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Forth
Forth
char c emit s" string" type
Give a code snippet in #Forth Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena   FOR y% = 0 TO Height%-1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) r% = rgb% >> 16 g% = (rgb% >> 8) AND &FF b% = rgb% AND &FF l% = INT(0.3*r% ...
Give a code snippet in #BBC_BASIC Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward convers...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Ursala
Ursala
#import std #import nat   xor = ~&Y&& not ~&B # either and not both   btog = xor*+ zipp0@iitBX # map xor over the argument zipped with its shift   gtob = ~&y+ =><0> ^C/xor@lrhPX ~&r # fold xor over the next input with previous output   #show+   test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,b...
Give a code snippet in #Ursala Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Elena
Elena
import system'math; import extensions; import extensions'text;   struct Quaternion { rprop real A; rprop real B; rprop real C; rprop real D;   constructor new(a, b, c, d) <= new(cast real(a), cast real(b), cast real(c), cast real(d));   constructor new(real a, real b, real c, real d) ...
Give a code snippet in #Elena Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Ada
Ada
generic type Element_Type is private; Zero : Element_Type; One : Element_Type; with function "+" (Left, Right : Element_Type) return Element_Type is <>; with function "-" (Left, Right : Element_Type) return Element_Type is <>; with function "*" (Left, Right : Element_Type) return Element_Type is <>; ...
Give a code snippet in #Ada Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#REXX
REXX
/*REXX pgm finds and displays bare language (<lang>) tags without a language specified. */ parse arg iFID . /*obtain optional argument from the CL.*/ if iFID=='' | iFID="," then iFID= 'BARELANG.HTM' /*Not specified? Then assume default*/ call lineout iFID ...
Give a code snippet in #REXX Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should displa...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#AutoHotkey
AutoHotkey
nth := ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"] lines := ["A partridge in a pear tree." ,"Two turtle doves and" ,"Three french hens" ,"Four calling birds" ,"Five golden rings" ,"Six geese a-laying" ,"Seven swans a-swimming" ,"Eight maids a...
Give a code snippet in #AutoHotkey Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Factor
Factor
USING: formatting calendar io ;   now "%Y-%m-%d" strftime print now "%A, %B %d, %Y" strftime print
Give a code snippet in #Factor This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/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 |...
#Ruby
Ruby
def logic(a, b) print 'a and b: ', a && b, "\n" print 'a or b: ' , a || b, "\n" print 'not a: ' , !a , "\n" print 'a xor b: ' , a ^ b, "\n" end
Give a code snippet in #Ruby Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#Factor
Factor
sudo apt-get install gfortran
Give a code snippet in #Factor Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Component_Pascal
Component Pascal
  MODULE Operations; IMPORT StdLog,Args,Strings;   PROCEDURE Max(s: ARRAY OF INTEGER): INTEGER; VAR i: INTEGER; max: INTEGER; BEGIN max := MIN(INTEGER); FOR i := 0 TO LEN(s) - 1 DO max := MAX(max,s[i]); END; RETURN max END Max;   PROCEDURE DoMax*; VAR sq: POINTER TO ARRAY OF INTEGER; p: Args.Params; i,n,don...
Give a code snippet in #Component_Pascal Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit1 { Group Quick { Private: Function partition { Read &A(), p, r x = A(r) i = p-1 For j=p to r-1 { If .LE(A(j), x) Then { i++ ...
Give a code snippet in #M2000_Interpreter 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Groovy
Groovy
def bigNumber = 5G ** (4 ** (3 ** 2))
Give a code snippet in #Groovy Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#HolyC
HolyC
U0 BottlesOfBeer (I64 initial=99) { // This is made I64 rather than U64 // Because, a U64 would overflow // At the end of the loop, thus it would loop forever (i-- would be 0-1 so it overflows and is always greater than or equal to 0) I64 i = initial;   for (; i >= 0; i--) { if (i == 1) { // Just a string on...
Give a code snippet in #HolyC Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Perl
Perl
use Crypt::Random::Seed; my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values
Give a code snippet in #Perl Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Erlang
Erlang
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]).   egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}.   mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefi...
Give a code snippet in #Erlang Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\display...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#MUMPS
MUMPS
BullCow New bull,cow,guess,guessed,ii,number,pos,x Set number="",x=1234567890 For ii=1:1:4 Do . Set pos=$Random($Length(x))+1 . Set number=number_$Extract(x,pos) . Set $Extract(x,pos)="" . Quit Write !,"The computer has selected a number that consists" Write !,"of four different digits." Write !!,"As you are g...
Give a code snippet in #MUMPS Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Prolog
Prolog
% Find the largest integer divisible by all it's digits, with no digit repeated. % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % We go for a generic algorithm here. Test for divisibility is done by % calculating the least common multiplier for all digits, and testing % whether a...
Give a code snippet in #Prolog Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Racket
Racket
  #lang racket (require net/uri-codec) (uri-encode "http://foo bar/")  
Give a code snippet in #Racket Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes...
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich 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, a Wieferich prime is a prime number p such th...
#Java
Java
import java.util.*;   public class WieferichPrimes { public static void main(String[] args) { final int limit = 5000; System.out.printf("Wieferich primes less than %d:\n", limit); for (Integer p : wieferichPrimes(limit)) System.out.println(p); }   private static boole...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Wieferich 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, a Wieferich prime...
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)...
#Ruby
Ruby
require "matrix"   def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end   def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p...
Give a code snippet in #Ruby 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/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => {   // sternBrocot :: Generator [Int] const sternBrocot = () => { const go = xs => { const x = snd(xs); return tail(append(xs, [fst(xs) + x, x])); }; return fmapGen(head, iterate(go, [...
Give a code snippet in #JavaScript For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#MiniScript
MiniScript
tokens = 12   print "Nim Game" print "Starting with " + tokens + " tokens." print   printRemaining = function() print tokens + " tokens remaining." print end function   playerTurn = function(take) take = floor(val(take)) if take < 1 or take > 3 then print "Take must be between 1 and 3." return false end if   ...
Give a code snippet in #MiniScript Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player t...
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...
#Sidef
Sidef
func jaro(s, t) {   return 1 if (s == t)   var s_len = s.len var t_len = t.len   var match_distance = ((s_len `max` t_len) // 2 - 1)   var s_matches = [] var t_matches = []   var matches = 0 var transpositions = 0   for i (^s_len) { var start = (0 `max` i-match_distance) ...
Give a code snippet in #Sidef 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Frink
Frink
a = 5^4^3^2 as = "$a" // Coerce to string println["Length=" + length[as] + ", " + left[as,20] + "..." + right[as,20]]
Give a code snippet in #Frink Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#JavaScript
JavaScript
// IdentityMatrix is a "subclass" of Matrix function IdentityMatrix(n) { this.height = n; this.width = n; this.mtx = []; for (var i = 0; i < n; i++) { this.mtx[i] = []; for (var j = 0; j < n; j++) { this.mtx[i][j] = (i == j ? 1 : 0); } } } IdentityMatrix.prototype...
Give a code snippet in #JavaScript Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#Wren
Wren
import "random" for Random import "os" for Process   var args = Process.arguments var games = (args.count == 0) ? 100 : Num.fromString(args[0])   var Rand = Random.new() var Die = 1..6 var Goal = 100   class Player { construct new(strategy) { _score = 0 _ante = 0 _rolls = 0 _strate...
Give a code snippet in #Wren Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strat...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Python
Python
def get_pixel_colour(i_x, i_y): import win32gui i_desktop_window_id = win32gui.GetDesktopWindow() i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id) long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y) i_colour = int(long_colour) win32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc) ...
Give a code snippet in #Python Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { k=0; n=0; printf("First twenty Harshad numbers are:\n "); while (k<20) { if (isharshad(++n)) { printf("%i ",n); ++k; } } n = 1000; while (!isharshad(++n)); printf("\nFirst Harshad number larger than 1000 is \n  %i\n",n); }   function isharshad(n) { s = 0; for (i=0; i<len...
Give a code snippet in #AWK The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#XPL0
XPL0
code ChOut=8, CrLf=9, Sound=39; string 0; \use zero-terminated strings   proc Morse(Msg); \Output Msg string as audible International Morse code char Msg; char C, D; int Code, Vol; [Code:= [" ", \space ".-.-..",".-..-.", " ", "...-..-"," ", ...
Give a code snippet in #XPL0 Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Joy
Joy
  DEFINE units == [ "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen" ];   tens == [ "ten" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety" ];   convert6 == [1000000 <] [1000 ...
Give a code snippet in #Joy Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positi...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Forth
Forth
\ Rossetta Code Write language name in 3D ASCII \ Simple Method   : l1 ." /\\\\\\\\\\\\\ /\\\\ /\\\\\\\ /\\\\\\\\\\\\\ /\\\ /\\\" CR ; : l2 ." \/\\\///////// /\\\//\\\ /\\\/////\\\ \//////\\\//// \/\\\ \/\\\" CR ; : l3 ." \/\\\ /\\\/ \///\\\ \/\\\ \/\\\ \/\\\ \/\\\ ...
Give a code snippet in #Forth Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#D
D
import std.stdio, std.conv, std.range, std.typecons, std.bigInt;   auto rev(in BigInt n) { return n.text.retro.text.BigInt; }   alias Res = Tuple!(bool, BigInt);   Res lychrel(BigInt n) { static Res[BigInt] cache; if (n in cache) return cache[n];   auto r = n.rev; auto res = Res(true, n); ...
Give a code snippet in #D   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most star...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Elixir
Elixir
defmodule Fork do def start do spawn(fn -> child end) IO.puts "This is the original process" end   def child, do: IO.puts "This is the new process" end   Fork.start
Give a code snippet in #Elixir Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Racket
Racket
  #lang racket ;; Using boolean #t/#f instead of 1/0 (define ((randN n)) (zero? (random n))) (define ((unbiased biased)) (let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))   ;; Counts (define N 1000000) (for ([n (in-range 3 7)]) (define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100))) ...
Give a code snippet in #Racket P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Rust
Rust
extern crate rand;   use rand::Rng;   fn main() { let array = [5,1,2,5,6,7,8,1,2,4,5]; let mut rng = rand::thread_rng();   println!("{}", rng.choose(&array).unwrap()); }
Give a code snippet in #Rust Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Processing
Processing
// Lines that begin with two slashes, thus, are comments: they // will be ignored by the machine.   // First we must declare a variable, n, suitable to store an integer:   int n;   // Each statement we address to the machine must end with a semicolon.   // To begin with, the value of n will be zero:   n = 0;   // Now w...
Give a code snippet in #Processing Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic...
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...
#Raku
Raku
class Pixel { has Int ($.R, $.G, $.B) } class Bitmap { has Int ($.width, $.height); has Pixel @.data;   method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] } }   role PPM { method P6 returns Blob { "P6\n{self.width} {self.height}\n255\n...
Give a code snippet in #Raku 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Elixir
Elixir
defmodule RC do def find_miss_perm(head, perms) do all_permutations(head) -- perms end   defp all_permutations(string) do list = String.split(string, "", trim: true) Enum.map(permutations(list), fn x -> Enum.join(x) end) end   defp permutations([]), do: [[]] defp permutations(list), do: (for x <...
Give a code snippet in #Elixir ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#Julia
Julia
ispalindrome(n, bas) = (s = string(n, base=bas); s == reverse(s)) prin3online(n) = println(lpad(n, 15), lpad(string(n, base=2), 40), lpad(string(n, base=3), 30)) reversebase3(n) = (x = 0; while n != 0 x = 3x + (n %3); n = div(n, 3); end; x)   function printpalindromes(N) lo, hi, pow2, pow3, count, i = 0, 1, 1, 1, 1...
Give a code snippet in #Julia Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   bas...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Pascal
Pascal
foo
Give a code snippet in #Pascal Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Nim
Nim
import tables, strutils, strformat   type operator = tuple[prec:int, rassoc:bool]   let ops = newTable[string, operator]( [ ("^", (4, true )), ("*", (3, false)), ("/", (3, false)), ("+", (2, false)), ("-", (2, false)) ])   proc shuntRPN(tokens:seq[string]): string = var stack: seq[string] var op:s...
Give a code snippet in #Nim Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representi...
christopher/rosetta-code
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#F.23
F#
#!/usr/bin/env fsharpi let server_tz = try // CLR on Windows System.TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time") with // Mono  :? System.TimeZoneNotFoundException -> System.TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin")   let get url = ...
Give a code snippet in #F.23 Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Forth
Forth
CREATE BUF 0 , \ single-character look-ahead buffer : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : >INT ( -- n) >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC ...
Give a code snippet in #Forth A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read inp...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Zig
Zig
const std = @import("std");   pub fn main() !void { const stdout = std.io.getStdOut().writer(); var i: i32 = undefined; var address_of_i: *i32 = &i;   try stdout.print("{x}\n", .{@ptrToInt(address_of_i)}); }
Give a code snippet in #Zig Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#COBOL
COBOL
identification division. program-id. bogo-sort-program. data division. working-storage section. 01 array-to-sort. 05 item-table. 10 item pic 999 occurs 10 times. 01 randomization. 05 random-seed pic 9(8). 05 random-index pic 9. 01 flags-counters-etc. 05 array-i...
Give a code snippet in #COBOL 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/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#JavaScript
JavaScript
// define base64 data; in this case the data is the string: "Hello, world!" const base64 = 'SGVsbG8sIHdvcmxkIQ=='; // atob is a built-in function. console.log(atob(base64));
Give a code snippet in #JavaScript See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed outp...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#0815
0815
  <:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~ =}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~%  
Give a code snippet in #0815 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Julia
Julia
function superellipse(n, a, b, step::Int=100) @assert n > 0 && a > 0 && b > 0 na = 2 / n pc = 2π / step t = 0 xp = Vector{Float64}(undef, step + 1) yp = Vector{Float64}(undef, step + 1) for i in 0:step # because sin^n(x) is mathematically the same as (sin(x))^n... xp[i+1] = ...
Give a code snippet in #Julia A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#68000_Assembly
68000 Assembly
Sunday equ 0 Monday equ 1 Tuesday equ 2 Wednesday equ 3 Thursday equ 4 Friday equ 5 Saturday equ 6
Give a code snippet in #68000_Assembly Task Create an enumeration of constants with and without explicit values.
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 ...
#Visual_FoxPro
Visual FoxPro
  LOCAL i As Integer, n As Integer, lcOut As String CLOSE DATABASES ALL CLEAR CREATE CURSOR nums (num I) INDEX ON num TAG num COLLATE "Machine" SET ORDER TO 0 n = 50 RAND(-1) FOR i = 1 TO n INSERT INTO nums VALUES (RanInt(1, 10)) ENDFOR SELECT num, COUNT(num) As cnt FROM nums ; GROUP BY num INTO CURSOR grouped LIST...
Give a code snippet in #Visual_FoxPro Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Fortran
Fortran
program recursion_depth   implicit none   call recurse (1)   contains   recursive subroutine recurse (i)   implicit none integer, intent (in) :: i   write (*, '(i0)') i call recurse (i + 1)   end subroutine recurse   end program recursion_depth
Give a code snippet in #Fortran Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#11l
11l
F mandelbrot(a) R (0.<50).reduce(0i, (z, _) -> z * z + @a)   F step(start, step, iterations) R (0 .< iterations).map(i -> @start + (i * @step))   V rows = (step(1, -0.05, 41).map(y -> (step(-2.0, 0.0315, 80).map(x -> (I abs(mandelbrot(x + 1i * @y)) < 2 {‘*’} E ‘ ’))))) print(rows.map(row -> row.join(‘’)).join("\n...
Give a code snippet in #11l Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
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...
#BBC_BASIC
BBC BASIC
DIM List%(3) List%() = 1, 2, 3, 4 FOR perm% = 1 TO 24 FOR i% = 0 TO DIM(List%(),1) PRINT List%(i%); NEXT PRINT PROC_NextPermutation(List%()) NEXT END   DEF PROC_NextPermutation(A%()) LOCAL first, last, elementcount, pos elementcou...
Give a code snippet in #BBC_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 permutations   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Sidef
Sidef
func writedat(filename, x, y, x_precision=3, y_precision=5) { var fh = File(filename).open_w   for a,b in (x ~Z y) { fh.printf("%.*g\t%.*g\n", x_precision, a, y_precision, b) }   fh.close }   var x = [1, 2, 3, 1e11] var y = x.map{.sqrt}   writedat('sqrt.dat', x, y)
Give a code snippet in #Sidef Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, ...
christopher/rosetta-code