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/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Futhark
Futhark
  if <condition> then <truebranch> else <falsebranch>  
Give a code snippet in #Futhark Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Commo...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#AppleScript
AppleScript
on isPrime(n) if (n < 2) then return false set f to n - 1 repeat with i from (n - 2) to 2 by -1 set f to f * i mod n end repeat   return ((f + 1) mod n = 0) end isPrime   local output, n set output to {} repeat with n from 0 to 500 if (isPrime(n)) then set end of output to n end repeat o...
Give a code snippet in #AppleScript Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#Batch_File
Batch File
@ECHO OFF SETLOCAL EnableExtensions EnableDelayedExpansion :: GnomeSort.cmd in WinNT Batch using pseudo array. :: Set the number of random elements to sort. SET numElements=100 :: Decrement numElements for use in zero-based loops as in (0, 1, %numElements% - 1). SET /A tmpElements=%numElements% - 1 :: Create array of ...
Give a code snippet in #Batch_File 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/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...
#Sidef
Sidef
require('XML::XPath');   var x = %s'XML::XPath'.new(ARGF.slurp);   [x.findnodes('//item[1]')][0]; say [x.findnodes('//price')].map{x.getNodeText(_)}; [x.findnodes('//name')];
Give a code snippet in #Sidef 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 #...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Scala
Scala
object Huffman { import scala.collection.mutable.{Map, PriorityQueue}   sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree   def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) ...
Give a code snippet in #Scala Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you c...
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...
#MapBasic
MapBasic
Include "MapBasic.def"   DECLARE SUB Main DECLARE FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING   FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING DIM tmpint1 AS INTEGER, tmpint2 AS INTEGER, tmpstr1 AS STRING, tmpstr2 AS STRING DIM L0 AS INTEGER, L1 AS INTEGE...
Give a code snippet in #MapBasic 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 th...
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...
#J
J
factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ properDivisors=: factors -. ]
Give a code snippet in #J 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#jq
jq
# Use Zeller's Congruence to determine the day of the week, given # year, month and day as integers in the conventional way. # If iso == "iso" or "ISO", then emit an integer in 1 -- 7 where # 1 represents Monday, 2 Tuesday, etc; # otherwise emit 0 for Saturday, 1 for Sunday, etc. # def day_of_week(year; month; day; is...
Give a code snippet in #jq A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 200...
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...
#AsciiDots
AsciiDots
/-99#-. />*$_#-$_" bottles of beer on the wall, "-$_#-$" bottles of beer."\ |[-]1#-----" ,dnuora ti ssap dna nwod eno ekaT"_$-----------------/ | | | | &-".llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG"$\ | |/$""-$"No more bottles of beer on the wall, no more bottles of beer."---/ | |\".llaw eht no...
Give a code snippet in #AsciiDots 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 ...
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.
#Forth
Forth
variable a : assert a @ 42 <> throw ;   41 a ! assert
Give a code snippet in #Forth 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/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Futhark
Futhark
  let kprime(n: i32, k: i32): bool = let (p,f) = (2, 0) let (n,_,f) = loop (n, p, f) while f < k && p*p <= n do let (n,f) = loop (n, f) while 0 == n % p do (n/p, f+1) in (n, p+1, f) in f + (if n > 1 then 1 else 0) == k   let main(m: i32): [][]i32 = let f k = let ps = replicate 10 0 let (_,...
Give a code snippet in #Futhark A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-balancing binary search tree....
#Nim
Nim
#[ AVL tree adapted from Julienne Walker's presentation at http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.   Uses bounded recursive versions for insertion and deletion. ]#   type   # Objects strored in the tree must be comparable. Comparable = concept x, y (x == y) is bool (x < y)...
Give a code snippet in #Nim This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Ol
Ol
  (define (digital-root num) (if (less? num 10) num (let loop ((num num) (sum 0)) (if (zero? num) (digital-root sum) (loop (div num 10) (+ sum (mod num 10)))))))   (print (digital-root 627615)) (print (digital-root 39390)) (print (digital-root 588225)) (print (digital-roo...
Give a code snippet in #Ol The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , rep...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Module Multiply (a, b) { Push a*b } Multiply 10, 5 Print Number=50   Module Multiply { Push Number*Number }   Multiply 10, 5 Print Number=50 \\ push before call Push 10, 5 Multiply Read A Print A=50 ...
Give a code snippet in #M2000_Interpreter A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not ...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
GUI/Maximum window dimensions
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an...
#Racket
Racket
  #lang racket/gui (define-values [W H] (let ([f (new frame% [label "test"])]) (begin0 (send* f (maximize #t) (show #t) (get-client-size)) (send f show #f)))) (printf "~ax~a\n" W H)  
Give a code snippet in #Racket The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjus...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Emacs_Lisp
Emacs Lisp
(md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680" (secure-hash 'md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680"
Give a code snippet in #Emacs_Lisp Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin primality test or Rabin–Miller prima...
#Elixir
Elixir
  defmodule Prime do use Application alias :math, as: Math alias :rand, as: Rand   def start( _type, _args ) do primes = 5..1000 |> Enum.filter( fn( x ) -> (rem x, 2) == 1 end ) |> Enum.filter( fn( x ) -> miller_rabin?( x, 10) == True end ) IO.inspect( primes, label: "Primes: ", limit: :infi...
Give a code snippet in #Elixir This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin prim...
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.
#Racket
Racket
  #lang racket (require (planet neil/charterm:3:0)) (with-charterm (charterm-clear-screen) (charterm-cursor 3 6) (displayln "Hello World"))  
Give a code snippet in #Racket 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
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...
#Fortran
Fortran
  SUBROUTINE COMBSORT(A,N) INTEGER A(*) !The array. INTEGER N !The count. INTEGER H,T !Assistants. LOGICAL CURSE H = N - 1 !Last - First, and not +1. 1 H = MAX(1,H*10/13) !The special feature. IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. CURSE = .FALSE. !...
Give a code snippet in #Fortran 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 3...
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...
#AppleScript
AppleScript
set L to {3, 2, 1, 0, -1, -2, -3}   set evens to {} set odds to {}   repeat with x in L if (x mod 2 = 0) then set the end of evens to x's contents else set the end of odds to x's contents end if end repeat   return {even:evens, odd:odds}
Give a code snippet in #AppleScript 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Objeck
Objeck
  bundle Default { class HighOrder { function : Main(args : String[]) ~ Nil { f := GetSize(String) ~ Int; Print(f); }   function : GetSize(s : String) ~ Int { return s->Size(); }   function : Print(func : (String)~Int) ~ Nil { func("Hello World!")->PrintLine(); } } } ...
Give a code snippet in #Objeck Task Pass a function     as an argument     to another function. Related task   First-class functions
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...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def save over over chain ps> swap 0 put >ps enddef   def permute /# l l -- #/ len 2 > if len for drop pop swap rot swap 1 put swap permute endfor else save rotate save rotate endif swap len if pop rot rot 0 put else d...
Give a code snippet in #Phixmonti 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/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Perl
Perl
use strict; my @c = (); # create an empty "array" collection   # fill it push @c, 10, 11, 12; push @c, 65; # print it print join(" ",@c) . "\n";   # create an empty hash my %h = (); # add some pair $h{'one'} = 1; $h{'two'} = 2; # print it foreach my $i ( keys %h ) { print $i . " -> " . $h{$i} . "\n"; }
Give a code snippet in #Perl This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Sidef
Sidef
func rms(a) { sqrt(a.map{.**2}.sum / a.len) }   say rms(1..10)
Give a code snippet in #Sidef Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Free_Pascal
Free Pascal
type /// domain for Fibonacci function /// where result is within nativeUInt // You can not name it fibonacciDomain, // since the Fibonacci function itself // is defined for all whole numbers // but the result beyond F(n) exceeds high(nativeUInt). fibonacciLeftInverseRange = {$ifdef CPU64} 0..93 {$else} 0..47 ...
Give a code snippet in #Free_Pascal 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 solutio...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Ring_2
Ring
  load "stdlib.ring" load "guilib.ring"   size = 8 newSize = size count = 0 sizeBoard = 0 Queens = list(size) Board = [] badBoard = []   win = null nMoves = 0 oldx = 0 oldy = 0 bWidth = 0 bHeight = 0   moveX = 550 moveY = 140 ### Open Window on Screen Position sizeX = 800 sizeY = 800 ### Size of Window   Button = nul...
Give a code snippet in #Ring_2 Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's ...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Nim
Nim
import json {.experimental: "dotOperators".} template `.=`(js: JsonNode, field: untyped, value: untyped) = js[astToStr(field)] = %value template `.`(js: JsonNode, field: untyped): JsonNode = js[astToStr(field)] var obj = newJObject() obj.foo = "bar" echo(obj.foo) obj.key = 3 echo(obj.key)
Give a code snippet in #Nim Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprog...
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...
#ALGOL_68
ALGOL 68
main: ( printf($"Goodbye, World!"l$) )
Give a code snippet in #ALGOL_68 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 langu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#Eiffel
Eiffel
  class STOOGE_SORT feature stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER) -- Sorted array in ascending order. require ar_not_empty: ar.count >= 0 i_in_range: i>=1 j_in_range: j <= ar.count boundary_set: i<=j local t: REAL_64 third: INTEGER swap: INTEGER do if ar[j]< ar[i] then sw...
Give a code snippet in #Eiffel 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/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#PL.2FI
PL/I
perfectTotient: procedure options(main); gcd: procedure(aa, bb) returns(fixed); declare (aa, bb, a, b, c) fixed; a = aa; b = bb; do while(b ^= 0); c = a; a = b; b = mod(c, b); end; return(a); end gcd;   totient: procedure(n...
Give a code snippet in #PL.2FI Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Slate
Slate
`(4 + 5) evaluate. `(4 + 5) evaluateIn: prototypes.
Give a code snippet in #Slate Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applica...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#D
D
import std.stdio, std.string, std.algorithm, std.conv, std.random, std.ascii, std.array, std.range, std.math;   struct GameBoard { dchar[9] board = "123456789"; enum : dchar { human = 'X', computer = 'O' } enum Game { going, humanWins, computerWins, draw }   const pure nothrow @safe @nogc invaria...
Give a code snippet in #D Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Ti...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#LiveCode
LiveCode
put urlDecode("http%3A%2F%2Ffoo%20bar%2F") & cr & \ urlDecode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")
Give a code snippet in #LiveCode This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencod...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#AutoHotkey
AutoHotkey
Gui, Add, Text,, Hello Gui, Show
Give a code snippet in #AutoHotkey Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Python
Python
from __future__ import division # Only necessary for Python 2.X from math import factorial from random import randrange   MAX_N = 20 TIMES = 1000000   def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))   def test(n, times): count = 0 for i in range(times): ...
Give a code snippet in #Python Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#FreeBASIC
FreeBASIC
type ll_int n as integer nxt as ll_int ptr end type
Give a code snippet in #FreeBASIC singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element...
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...
#ACL2
ACL2
(defun str-rest (str) (coerce (rest (coerce str 'list)) 'string))   (defun rdc (xs) (if (endp (rest xs)) nil (cons (first xs) (rdc (rest xs)))))   (defun str-rdc (str) (coerce (rdc (coerce str 'list)) 'string))   (str-rdc "string") (str-rest "string") (str-rest (str-rdc "string"))
Give a code snippet in #ACL2 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algor...
#EchoLisp
EchoLisp
  (require 'bigint) ;; test equality mod p (define-syntax-rule (mod= a b p) (zero? (% (- a b) p))) ;; assign mod p (define-syntax-rule (mod:≡ s v p) (set! s (% v p)))   (define (Legendre a p) (powmod a (/ (1- p) 2) p))   (define (Tonelli n p) (unless (= 1 (Legendre n p)) (error "not a square (mod p)" (list...
Give a code snippet in #EchoLisp This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Erlang
Erlang
  walk_dir(Path, Pattern) -> filelib:fold_files( Path, Pattern, true, % Recurse fun(File, Accumulator) -> [File|Accumulator] end, [] )  
Give a code snippet in #Erlang Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Wal...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#jq
jq
jq -R . csv2html.csv | jq -r -s -f csv2html.jq  
Give a code snippet in #jq 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 Creat...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Locomotive_Basic
Locomotive Basic
10 INPUT "Enter a string: ",a$ 20 GOSUB 50 30 PRINT b$ 40 END 50 FOR i=1 TO LEN(a$) 60 n=ASC(MID$(a$,i,1)) 70 e=255 80 IF n>64 AND n<91 THEN e=90 ' uppercase 90 IF n>96 AND n<123 THEN e=122 ' lowercase 100 IF e<255 THEN n=n+13 110 IF n>e THEN n=n-26 120 b$=b$+CHR$(n) 130 NEXT 140 RETURN
Give a code snippet in #Locomotive_Basic Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#zkl
zkl
const CNT =0d1_000_000; sieve  :=Import("sieve.zkl",False,False,False).postponed_sieve; conspiracy:=Dictionary(); Utils.Generator(sieve).reduce(CNT,'wrap(digit,p){ d:=p%10; conspiracy.incV("%d → %d count:".fmt(digit,d)); d }); foreach key in (conspiracy.keys.sort()){ v:=conspiracy[key].toFloat(); print...
Give a code snippet in #zkl A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preference...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Julia
Julia
  blank = "" nonblank = "!"   println("The length of blank is ", length(blank)) println("That blank is empty is ", isempty(blank)) println("That blank is not empty is ", !isempty(blank))   println() println("The length of nonblank is ", length(nonblank)) println("That nonblank is empty is ", isempty(nonblank)) println(...
Give a code snippet in #Julia Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Oth...
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 ...
#Pike
Pike
int fibIter(int n) { int fibPrev, fib, i; if (n < 2) { return 1; } fibPrev = 0; fib = 1; for (i = 1; i < n; i++) { int oldFib = fib; fib += fibPrev; fibPrev = oldFib; } return fib; }
Give a code snippet in #Pike 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/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#8th
8th
  : compare \ n m -- 2dup n:= if "They are equal" . cr then 2dup n:< if "First less than second" . cr then n:> if "First greater than second" . cr then ;  
Give a code snippet in #8th 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/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#AWK
AWK
  # syntax: GAWK -f MAGNANIMOUS_NUMBERS.AWK # converted from C BEGIN { magnanimous(1,45) magnanimous(241,250) magnanimous(391,400) exit(0) } function is_magnanimous(n, p,q,r) { if (n < 10) { return(1) } for (p=10; ; p*=10) { q = int(n/p) r = n % p if (!is_prime(q+r)) { return(...
Give a code snippet in #AWK A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3...
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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
fib := function(n) local a; a := [[0, 1], [1, 1]]^n; return a[1][2]; end;
Give a code snippet in #F.C5.8Drmul.C3.A6 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#EchoLisp
EchoLisp
  (lib 'math) ;; for poly multiplication   ;; convert string of decimal digits to polynomial ;; "1234" → x^3 +2x^2 +3x +4 ;; least-significant digit first (define (string->long N) (reverse (map string->number (string->list N))))   ;; convert polynomial to string (define (long->string N) (if (pair? N) (string-appen...
Give a code snippet in #EchoLisp Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Progress
Progress
a=1 ; The ';' indicates that a comment starts b=2*a: a=b*33 ; b will now be 2, and a=66
Give a code snippet in #Progress Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#BASIC256
BASIC256
arraybase 1 dim byValue = {10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100} dim byLimit = {6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96}   for byCount = 1 to 100 for byCheck = 0 to byLimit[?] if byCount < byLimit[byCheck] then exit for next byCheck ...
Give a code snippet in #BASIC256 A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Ruby
Ruby
class LastL_FirstL def initialize(names) @names = names.dup @first = names.group_by {|name| name[0]} @sequences = [] end   def add_name(seq) last_letter = seq[-1][-1] potentials = @first.include?(last_letter) ? (@first[last_letter] - seq) : [] if potentials.empty? @sequences << seq ...
Give a code snippet in #Ruby A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cat...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#APL
APL
mayan←{ ds←6 4⍴' . .. ... ....────' d←{ ⍵=0:4 4⍴¯14↑'Θ' ds[1+5⌊0⌈⍵-15 10 5 0;] }¨20(⊥⍣¯1)⍵ top←'╔',(1↓∊(≢d)⍴⊂'╦════'),'╗' btm←'╚',(1↓∊(≢d)⍴⊂'╩════'),'╝' top⍪((⊃,/'║',¨d),'║')⍪btm }
Give a code snippet in #APL Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Prolog
Prolog
:- use_module(library(clpfd)).   caesar :- L1 = "The five boxing wizards jump quickly", writef("Original : %s\n", [L1]),   % encryption of the sentence encoding(3, L1, L2) , writef("Encoding : %s\n", [L2]),   % deciphering on the encoded sentence encoding(3, L3, L2), writef("Decoding : %s\n", [L3]).   % encodin...
Give a code snippet in #Prolog Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Draco
Draco
proc nonrec main() void: byte DOORS = 100; [DOORS+1] bool door_open; unsigned DOORS i, j;   /* make sure all doors are closed */ for i from 1 upto DOORS do door_open[i] := false od;   /* pass through the doors */ for i from 1 upto DOORS do for j from i by i upto DOORS do ...
Give a code snippet in #Draco There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, .....
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#ERRE
ERRE
    PROGRAM SIERP_CARPET   ! for rosettacode.org   !$INTEGER   BEGIN OPEN("O",1,"OUT.PRN") PRINT(CHR$(12);) !CLS DEPTH=3 DIMM=1   FOR I=0 TO DEPTH-1 DO DIMM=DIMM*3 END FOR   FOR I=0 TO DIMM-1 DO FOR J=0 TO DIMM-1 DO D=DIMM DIV 3 REPEAT EXIT IF ((I MOD (D*3)) DIV D=1 AND (J MOD (D*3)) DIV ...
Give a code snippet in #ERRE Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. RPN. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 9 Feb 2020. ************************************************************ ** Program Abstract: ** Create a stack-based evaluator for an expression in ** re...
Give a code snippet in #COBOL Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RP...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS/Authenticated
HTTPS/Authenticated
The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
#Lasso
Lasso
local(username = 'hello',password = 'world') local(x = curl('https://sourceforge.net')) #x->set(CURLOPT_USERPWD, #username + ':' + #password) local(y = #x->result) #y->asString
Give a code snippet in #Lasso The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Vlang
Vlang
const ( width = 81 height = 5 )   fn cantor(mut lines [][]u8, start int, len int, index int) { seg := len / 3 if seg == 0 { return } for i in index.. height { for j in start + seg..start + 2 * seg { lines[i][j] = ' '[0] } } cantor(mut lines, start, seg...
Give a code snippet in #Vlang Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Vlang
Vlang
import strconv   fn main() { // cache factorials from 0 to 11 mut fact := [12]u64{} fact[0] = 1 for n := u64(1); n < 12; n++ { fact[n] = fact[n-1] * n }   for b := 9; b <= 12; b++ { println("The factorions for base $b are:") for i := u64(1); i < 1500000; i++ { ...
Give a code snippet in #Vlang Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#SNUSP
SNUSP
/++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/
Give a code snippet in #SNUSP Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algor...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Class Solution ReadOnly root1 As BigInteger ReadOnly root2 As BigInteger ReadOnly exists As Boolean   Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean) root1 = r1 root2 = r2 exists = e End ...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computatio...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Lily
Lily
var doors = List.fill(100, false)   for i in 0...99: for j in i...99 by i + 1: doors[j] = !doors[j]   # The type must be specified since the list starts off empty. var open_doors: List[Integer] = []   doors.each_index{|i| if doors[i]: open_doors.push(i + 1) }   print($"Open doors: ^(open_doors)"...
Give a code snippet in #Lily There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ......
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 ...
#Ruby
Ruby
x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' x, y, z = [x, y, z].sort puts x, y, z   x, y, z = 7.7444e4, -12, 18/2r # Float, Integer, Rational; taken from Perl 6 x, y, z = [x, y, z].sort puts x, y, z  
Give a code snippet in #Ruby 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/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 |...
#PARI.2FGP
PARI/GP
startsWith(string, prefix)={ string=Vec(string); prefix=Vec(prefix); if(#prefix > #string, return(0)); for(i=1,#prefix,if(prefix[i]!=string[i], return(0))); 1 }; contains(string, inner)={ my(good); string=Vec(string); inner=Vec(inner); for(i=0,#string-#inner, good=1; for(j=1,#inner, if(i...
Give a code snippet in #PARI.2FGP Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Lobster
Lobster
import std def lcs(a, b) -> string: var out = "" let lengths = map(a.length * b.length): 0 var greatestLength = 0 for(a) x, i: for(b) y, j: if x == y: if i == 0 or j == 0: lengths[i * b.length + j] = 1 else: leng...
Give a code snippet in #Lobster Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consec...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Julia
Julia
  const PFCUT = [6:5:101]//100 const PFVAL = [10:8:26, 32:6:50, 54:4:98, 100]//100   function pricefraction{T<:FloatingPoint}(a::T) zero(T) <= a || error("a = ", a, ", but it must be >= 0.") a <= one(T) || error("a = ", a, ", but it must be <= 1.") convert(T, PFVAL[findfirst(a .< PFCUT)]) end   test = [0.:0...
Give a code snippet in #Julia A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#PARI.2FGP
PARI/GP
wrap(s,len)={ my(t="",cur); s=Vec(s); for(i=1,#s, if(s[i]==" ", if(cur>#t, print1(" "t); cur-=#t+1 , print1("\n"t); cur=len-#t ); t="" , t=concat(t,s[i]) ) ); if(cur>#t, print1(" "t) , print1("\n"t) ) }; King="And so let fre...
Give a code snippet in #PARI.2FGP Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rendezvous
Rendezvous
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
#AutoHotkey
AutoHotkey
OnMessage(0x4a, "PrintMonitor") SetTimer, print2, 400   print1: print("Old Mother Goose") print("When she wanted to wander,") print("Would ride through the air") print("On a very fine gander.") print("Jack's mother came in,") print("And caught the goose soon,") print("And mounting its back,") print("Fle...
Give a code snippet in #AutoHotkey Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#PARI.2FGP
PARI/GP
lex(u,v)<1
Give a code snippet in #PARI.2FGP sorting 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/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Python
Python
  # rare.py # find rare numbers # by kHz   from math import floor, sqrt from datetime import datetime   def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start   def is_square(n): s = floor(sqrt(n + 0.5)) re...
Give a code snippet in #Python Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be p...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#zkl
zkl
var n=20; [[(x,y,z); [1..n]; {[x..n]}; {[y..n]},{ x*x + y*y == z*z }; _]] //-->L(L(3,4,5),L(5,12,13),L(6,8,10),L(8,15,17),L(9,12,15),L(12,16,20))
Give a code snippet in #zkl A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the ...
christopher/rosetta-code
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#OxygenBasic
OxygenBasic
  '============ class History '============   indexbase 0   string buf sys ii,ld,pb   method constructor(sys n=1000, l=sizeof sys) {buf=nuls n*l : pb=strptr buf : ld=l : ii=0} method destructor () {clear} ' method setup(sys n=1000, l=sizeof sys) {buf=nuls n*l : pb=strptr buf : ld=l : ii=0} method clear() ...
Give a code snippet in #OxygenBasic Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variab...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Action.21
Action!
  CHAR ARRAY S1,S2   Proc Main() S1="Hello, " S2="world!"; Sassign(S1,S2,S1(0)+1) Print(S1) Return  
Give a code snippet in #Action.21 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) every (s := 0) +:= !args write((real(s)/(0 ~= *args)) | 0) end
Give a code snippet in #Icon_and_Unicon Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language h...
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...
#Python
Python
from collections import namedtuple import math   class Q(namedtuple('Quaternion', 'real, i, j, k')): 'Quaternion type: Q(real=0.0, i=0.0, j=0.0, k=0.0)'   __slots__ = ()   def __new__(_cls, real=0.0, i=0.0, j=0.0, k=0.0): 'Defaults all parts of quaternion to zero' return super().__new__(_c...
Give a code snippet in #Python 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/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Go
Go
package main   import "fmt"   // sudoku puzzle representation is an 81 character string var puzzle = "" + "394 267 " + " 3 4 " + "5 69 2 " + " 45 9 " + "6 7" + " 7 58 " + " 1 67 8" + " 9 8 " + " 264 735"   func main() { printGrid("puzzle:", puzzle) ...
Give a code snippet in #Go Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elixir
Elixir
defmodule Order do def disjoint(m,n) do IO.write "#{Enum.join(m," ")} | #{Enum.join(n," ")} -> " Enum.chunk(n,2) |> Enum.reduce({m,0}, fn [x,y],{m,from} -> md = Enum.drop(m, from) if x > y and x in md and y in md do if Enum.find_index(md,&(&1==x)) > Enum.find_index(md,&(&1==y)...
Give a code snippet in #Elixir Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#jq
jq
"一二三四五六七八九十"[1:]' => "二三四五六七八九十"   "一二三四五六七八九十"[:-1]' => "一二三四五六七八九"   "一二三四五六七八九十"[1:-1]' => "二三四五六七八九"   "a"[1:-1] # => ""  
Give a code snippet in #jq 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#Perl
Perl
without js -- (tasks) sequence sems = {} constant COUNTER = 1, QUEUE = 2 function semaphore(integer n) if n>0 then sems = append(sems,{n,{}}) return length(sems) else return 0 end if end function procedure acquire(integer id) if sems[id][COUNTER]=0 then task_suspend(t...
Give a code snippet in #Perl The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, re...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } re...
Give a code snippet in #Go The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#AWK
AWK
  # syntax: GAWK -f SUBLEQ.AWK SUBLEQ.TXT # converted from Java BEGIN { instruction_pointer = 0 } { printf("%s\n",$0) for (i=1; i<=NF; i++) { if ($i == "*") { ncomments++ break } mem[instruction_pointer++] = $i } } END { if (instruction_pointer == 0) { print("er...
Give a code snippet in #AWK Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of sign...
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 .
#Lambdatalk
Lambdatalk
  {def mandel   {def mandel.r {lambda {:iter :cx :cy :norm :x :y :count} {if {> :count :iter} // then norm < 4 then o // inside the set else {if {> :norm 4} // then iter > max then . // out...
Give a code snippet in #Lambdatalk 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/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...
#zkl
zkl
const notesName="NOTES.TXT"; args:=vm.arglist; if (not args) { try{ File(notesName).read(*).text.print(); } catch{println("no file")} } else{ f:=File(notesName,"a+"); f.writeln(Time.Date.ctime(),"\n\t",args.concat(" ")); f.close(); }
Give a code snippet in #zkl 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/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#SQL
SQL
  --Setup DROP TABLE IF EXISTS board; CREATE TABLE board (p CHAR, r INTEGER, c INTEGER); INSERT INTO board VALUES('.', 0, 0),('.', 0, 1),('.', 0, 2),('.', 1, 0),('.', 1, 1),('.', 1, 2),('.', 2, 0),('.', 2, 1),('.', 2, 2);     -- Use a trigger for move events DROP TRIGGER IF EXISTS after_moved; CREATE TRIGGER after_move...
Give a code snippet in #SQL Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Nim
Nim
import streams   type Interpreter = object mem: seq[int] ip: int input, output: Stream   proc load(prog: openArray[int]; inp, outp: Stream): Interpreter = Interpreter(mem: prog, input: inp, output: outp)   proc run(i: var Interpreter) = while i.ip >= 0: let A = i.mem[i.ip] let B = i.mem[i.ip+1...
Give a code snippet in #Nim Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of sign...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Delphi
Delphi
  program RPG_Attributes_Generator;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Generics.Collections;   type TListOfInt = class(TList<Integer>) public function Sum: Integer; function FindAll(func: Tfunc<Integer, Boolean>): TListOfInt; function Join(const sep: string): string; ...
Give a code snippet in #Delphi RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-s...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Maple
Maple
iterated_totient := proc(n::posint, total) if NumberTheory:-Totient(n) = 1 then return total + 1; else return iterated_totient(NumberTheory:-Totient(n), total + NumberTheory:-Totient(n)); end if; end proc:   isPerfect := n -> evalb(iterated_totient(n, 0) = n):   count := 0: num_list := []: for i while count < ...
Give a code snippet in #Maple Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"]   For siCount = 0 To 9 Print cCollection[Str(siCount)] Next   End
Give a code snippet in #Gambas This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#C.2B.2B
C++
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector>   const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind N...
Give a code snippet in #C.2B.2B This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUP...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Sidef
Sidef
func gen_pow(m) { var e = 0; func { e++ ** m }; }   func gen_filter(g1, g2) { var v2 = g2.run; func { loop { var v1 = g1.run; while (v1 > v2) { v2 = g2.run }; v1 == v2 || return v1; } } }   # Create generators. var squares = gen_pow(2); var cubes =...
Give a code snippet in #Sidef A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an equation important in navigation, g...
#True_BASIC
True BASIC
  DEF Haversine (lat1, long1, lat2, long2) OPTION ANGLE RADIANS LET R = 6372.8  !radio terrestre en km. LET dLat = RAD(lat2-lat1) LET dLong = RAD(long2-long1) LET lat1 = RAD(lat1) LET lat2 = RAD(lat2) LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * C...
Give a code snippet in #True_BASIC This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#uBasic.2F4tH
uBasic/4tH
For n = 0 To 9 Push n : Gosub _coef : Gosub _drop Print "(x-1)^";n;" = "; Push n : Gosub _show Print Next   Print Print "primes (never mind the 1):";   For n = 1 To 34 Push n : Gosub _isprime If Pop() Then Print " ";n; Next   Print End   ' show polynomial expansions _s...
Give a code snippet in #uBasic.2F4tH The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Delphi
Delphi
  defmodule SieveofEratosthenes do def init(lim) do find_primes(2,lim,(2..lim)) end   def find_primes(count,lim,nums) when (count * count) > lim do nums end   def find_primes(count,lim,nums) when (count * count) <= lim do find_primes(count+1,lim,Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count...
Give a code snippet in #Delphi Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   prim...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Arturo
Arturo
loop 1..30 'x [ fs: [1] if x<>1 -> fs: factors.prime x print [pad to :string x 3 "=" join.with:" x " to [:string] fs] ]
Give a code snippet in #Arturo Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it woul...
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 ...
#VBA
VBA
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If Wo...
Give a code snippet in #VBA 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 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand 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 ...
#Haskell
Haskell
-- Same merge as in Merge Sort merge :: (Ord a) => [a] -> [a] -> [a] merge [] ys = ys merge xs [] = xs merge (x : xs) (y : ys) | x <= y = x : merge xs (y : ys) | otherwise = y : merge (x : xs) ys   strandSort :: (Ord a) => [a] -> [a] strandSort [] = [] strandSort (x : xs) = merge strand (strandSort rest) where (stra...
Give a code snippet in #Haskell Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#BBC_BASIC
BBC BASIC
REM This is a comment which is ignored by the compiler *| This is a comment which is compiled but ignored at run time
Give a code snippet in #BBC_BASIC Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) nr := integer(args[1]) | 3 # Default to 3x3 nc := integer(args[2]) | 3   A := list(nr) every !A := list(nc)   x := ?nr # Select a random element y := ?nc   A[x][y] := &pi write("A[",x,"][",y,"] -> ",A[x][y]) end
Give a code snippet in #Icon_and_Unicon Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   ...
#Factor
Factor
USING: grouping io kernel lists lists.lazy math math.extras prettyprint tools.memory.private ;   : rises-and-falls-equal? ( n -- ? ) 0 swap 10 /mod swap [ 10 /mod rot over - sgn rotd + spin ] until-zero drop 0 = ;   : OEIS:A296712 ( -- list ) 1 lfrom [ rises-and-falls-equal? ] lfilter ;   ! Task "The first ...
Give a code snippet in #Factor When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#Raku
Raku
sub fringe ($tree) { multi sub fringey (Pair $node) { fringey $_ for $node.kv; } multi sub fringey ( Any $leaf) { take $leaf; }   gather fringey $tree; }   sub samefringe ($a, $b) { fringe($a) eqv fringe($b) }   # Testing:   my $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8; my $b = 1 => (( 2 => 3 ) => (4 => (5 ...
Give a code snippet in #Raku Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution i...
christopher/rosetta-code