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/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Tcl
Tcl
package require TclOO oo::class create Point { variable X Y constructor {x y} { set X $x set Y $y } method x args { set X {*}$args } method y args { set Y {*}$args } method print {} { puts "Point($X,$Y)" } method copy {} { set copy ...
Give a code snippet in #Tcl Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Slate
Slate
define: #pairs -> ({'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3} as: Dictionary). pairs keysAndValuesDo: [| :key :value | inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')' ].   pairs keysDo: [| :key | inform: '(k, v) = (' ; key printString ; ', ' ; (pairs at: key) printString ; ')' ]...
Give a code snippet in #Slate Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Com...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11;   func Binomial(N, K); int N, K; int M, B, I; [M:= K; if K>N/2 the M:= N-K; B:=1; for I:= 1 to M do B:= B*(N-M+I)/I; return B; ];   int N, K; [for N:= 0 to 9 do [for K:= 0 to 9 do [if N>=K then IntOut(0, Binomial(N,K)); ChOut(0, 9\tab\); ]; CrLf(0);...
Give a code snippet in #XPL0 This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Groovy
Groovy
class FloydWarshall { static void main(String[] args) { int[][] weights = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] int numVertices = 4   floydWarshall(weights, numVertices) }   static void floydWarshall(int[][] weights, int numVertices) { double[][] dist = ne...
Give a code snippet in #Groovy The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already b...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#CoffeeScript
CoffeeScript
  spell_integer = (n) -> tens = [null, null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]   small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "s...
Give a code snippet in #CoffeeScript Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program bogosort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Vala
Vala
  uint i = 0; while (++i < uint.MAX) stdout.printf("%u\n", i);  
Give a code snippet in #Vala Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations lim...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#PureBasic
PureBasic
Procedure ImageGrayout(image) Protected w, h, x, y, r, g, b, gray, color   w = ImageWidth(image) h = ImageHeight(image) StartDrawing(ImageOutput(image)) For x = 0 To w - 1 For y = 0 To h - 1 color = Point(x, y) r = Red(color) g = Green(color) b = Blue(color) gray = 0...
Give a code snippet in #PureBasic Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward convers...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Action.21
Action!
PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN len=255-text(0) FI IF len THEN srcPtr=suffix+1 dstPtr=text+text(0)+1 MoveBlock(dstPtr,srcPtr,len) text(0)==+suffix(0) FI RETURN   PROC Prepend(CHAR ARRAY text,prefix) CHAR ...
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/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. 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 Burrows–Wheeler transform (BWT, also called block-s...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   const int STX = 0x02; const int ETX = 0x03;   void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; }   std::string bwt(const std::string &s) { for (char c...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. 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 Burrows–Wheeler tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#V
V
$stack puts   ./args.v a b c =[args.v a b c]
Give a code snippet in #V Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Natural_sorting
Natural 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 Shell Sort ...
#Scala
Scala
object NaturalSorting { implicit object ArrayOrdering extends Ordering[Array[String]] { // 4 val INT = "([0-9]+)".r def compare(a: Array[String], b: Array[String]) = { val l = Math.min(a.length, b.length) (0 until l).prefixLength(i => a(i) equals b(i)) match { case i if i == l => Math.sign...
Give a code snippet in #Scala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#PureBasic
PureBasic
While Inkey(): Wend
Give a code snippet in #PureBasic Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
christopher/rosetta-code
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Num...
#Tcl
Tcl
package require Tcl 8.6   oo::class create StraddlingCheckerboardCypher { variable encmap decmap constructor table { # Sanity check the table foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { error "bad checkerboard table" } ...
Give a code snippet in #Tcl Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Perl
Perl
use feature 'say';   # Perl arrays are internally always one-dimensional, but multi-dimension arrays are supported via references. # So a two-dimensional array is an arrays-of-arrays, (with 'rows' that are references to arrays), while a # three-dimensional array is an array of arrays-of-arrays, and so on. There are no...
Give a code snippet in #Perl For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Scala
Scala
for (i <- (0 until n)) yield new Foo()
Give a code snippet in #Scala Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are consider...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Crystal
Crystal
def knuthShuffle(items : Array) i = items.size-1 while i > 1 j = Random.rand(0..i) items.swap(i, j)   i -= 1 end end
Give a code snippet in #Crystal The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from ...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#BQN
BQN
Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷   •Show 5 Div 0 •Show 5 Div 5 •Show 0 Div 0
Give a code snippet in #BQN Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
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 ...
#R
R
  #lang R   assignVec <- Vectorize("assign", c("x", "value")) `%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) # define multiple global assignments operator  
Give a code snippet in #R Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#BCPL
BCPL
get "libhdr"   // Generate the N'th term of the Recaman sequence // given terms 0 to N-1. let generate(a, n) be a!n := n=0 -> 0, valof $( let subterm = a!(n-1) - n let addterm = a!(n-1) + n if subterm <= 0 resultis addterm for i=0 to n-1 if a!i = subterm resultis addterm ...
Give a code snippet in #BCPL The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Pascal
Pascal
program Cuboid_Demo(output);   procedure DoCuboid(sWidth, sHeight, Depth: integer); const widthScale = 4; heightScale = 3; type TPage = array of array of char; var Cuboid: TPage; i, j: integer; Width, Height: integer; totalWidth, totalHeight: integer; begin Width := widthScale ...
Give a code snippet in #Pascal Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection i...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Print[DateList[]] Print[AbsoluteTime[]]
Give a code snippet in #Mathematica.2FWolfram_Language Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performa...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#ColdFusion
ColdFusion
  <cfset testArray = ["apple","orange"]> <cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>  
Give a code snippet in #ColdFusion Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter ...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#VBScript
VBScript
  For i = 0 To 20 WScript.StdOut.WriteLine Oct(i) Next  
Give a code snippet in #VBScript Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Fortran
Fortran
  program demo_edit_distance character(len=:),allocatable :: sources(:),targets(:) integer,allocatable :: answers(:),expected(:)   sources=[character(len=20) :: "kitten", "rosettacode", "Saturday", "sleep", "qwerty", "Fortran" ] targets=[character(len=20) :: "sitting", "raisethysword", "Sunday", "f...
Give a code snippet in #Fortran This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and c...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#SNOBOL4
SNOBOL4
newstring = "This is creating and saving" " a new single string " "starting with three separate strings."
Give a code snippet in #SNOBOL4 Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: number is 0; begin for number range 1 to 100 do if number rem 15 = 0 then writeln("FizzBuzz"); elsif number rem 5 = 0 then writeln("Buzz"); elsif number rem 3 = 0 then writeln("Fizz"); els...
Give a code snippet in #Seed7 Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
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...
#AWK
AWK
  # syntax: GAWK -f HAVERSINE_FORMULA.AWK # converted from Python BEGIN { distance(36.12,-86.67,33.94,-118.40) # BNA to LAX exit(0) } function distance(lat1,lon1,lat2,lon2, a,c,dlat,dlon) { dlat = radians(lat2-lat1) dlon = radians(lon2-lon1) lat1 = radians(lat1) lat2 = radians(lat2) a = (si...
Give a code snippet in #AWK 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 equati...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Julia
Julia
  function aliquotclassifier{T<:Integer}(n::T) a = T[n] b = divisorsum(a[end]) len = 1 while len < 17 && !(b in a) && 0 < b && b < 2^47+1 push!(a, b) b = divisorsum(a[end]) len += 1 end if b in a 1 < len || return ("Perfect", a) if b == a[1] 2 ...
Give a code snippet in #Julia An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Java
Java
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider;   public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe";   private static cla...
Give a code snippet in #Java x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Racket
Racket
#lang racket/base   (require racket/match racket/string math/number-theory)   (define simplify-arithmetic-expression (letrec ((s-a-e (match-lambda [(list (and op '+) l ... (list '+ m ...) r ...) (s-a-e `(,op ,@l ,@m ,@r))] [(list (and op '+) l ... (? number? n...
Give a code snippet in #Racket In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expres...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program stableSort641.s */   /* use merge sort and pointer table */ /* but use a extra table of pointer for the merge */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for ...
Give a code snippet in #AArch64_Assembly Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#PowerShell
PowerShell
  function Get-EquilibriumIndex ( $Sequence ) { $Indexes = 0..($Sequence.Count - 1) $EqulibriumIndex = @()   ForEach ( $TestIndex in $Indexes ) { $Left = 0 $Right = 0 ForEach ( $Index in $Indexes ) { If ( $Index -lt $TestIndex ) { $Left += $Se...
Give a code snippet in #PowerShell An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Stata
Stata
qui sum x di r(max)
Give a code snippet in #Stata Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/French_Republican_calendar
French Republican calendar
Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of...
#Sidef
Sidef
require('DateTime')   var month_names = %w( Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse Germinal Floréal Prairial Messidor Thermidor Fructidor )   var intercalary = [ 'Fête de la vertu', 'Fête du génie', 'Fête du travail', ...
Give a code snippet in #Sidef Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messido...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Scheme
Scheme
(define-syntax lons (syntax-rules () ((_ lar ldr) (delay (cons lar (delay ldr))))))   (define (lar lons) (car (force lons)))   (define (ldr lons) (force (cdr (force lons))))   (define (lap proc . llists) (lons (apply proc (map lar llists)) (apply lap proc (map ldr llists))))   (define (take n llist) (if (...
Give a code snippet in #Scheme Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Python
Python
from collections import defaultdict from itertools import product from pprint import pprint as pp   cube2n = {x**3:x for x in range(1, 1201)} sum2cubes = defaultdict(set) for c1, c2 in product(cube2n, cube2n): if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))   taxied = sorted((k, v) for k,v in sum2cubes.i...
Give a code snippet in #Python A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also k...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#UnixPipes
UnixPipes
yes SPAM
Give a code snippet in #UnixPipes Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#PHP
PHP
<?php $pid = pcntl_fork(); if ($pid == 0) echo "This is the new process\n"; else if ($pid > 0) echo "This is the original process\n"; else echo "ERROR: Something went wrong\n"; ?>
Give a code snippet in #PHP Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Haskell
Haskell
module Main (main) where   main :: IO () main = writeFile "/dev/tape" "Hello from Rosetta Code!"
Give a code snippet in #Haskell The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#CoffeeScript
CoffeeScript
for var_name in ['PATH', 'HOME', 'LANG', 'USER'] console.log var_name, process.env[var_name]
Give a code snippet in #CoffeeScript Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#C
C
#include <stdbool.h> #include <stdio.h> #include <glib.h>   typedef struct word_count_tag { const char* word; size_t count; } word_count;   int compare_word_count(const void* p1, const void* p2) { const word_count* w1 = p1; const word_count* w2 = p2; if (w1->count > w2->count) return -1; ...
Give a code snippet in #C Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#FunL
FunL
$stdout = int( '1a', 16 )
Give a code snippet in #FunL Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary,...
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...
#SQL
SQL
  CREATE TABLE "numbers" ("datapoint" INTEGER);   INSERT INTO "numbers" SELECT rownum FROM tab;   SELECT SUM("datapoint")/COUNT(*) FROM "numbers";  
Give a code snippet in #SQL 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 establ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Perl
Perl
use Benchmark;   timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };   sub job1 { ...job1 code... } sub job2 { ...job2 code... }
Give a code snippet in #Perl Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish thes...
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 ...
#ATS
ATS
  fun fib_rec(n: int): int = if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n  
Give a code snippet in #ATS The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Prolog
Prolog
:- use_module(library(clpfd)).   roman :- LA = [ _ , 2010, _, 1449, _], LR = ['MDCCLXXXIX', _ , 'CX', _, 'MDCLXVI'], maplist(roman, LA, LR), maplist(my_print,LA, LR).     roman(A, R) :- A #> 0, roman(A, [u, t, h, th], LR, []), label([A]), parse_Roman(CR, LR, []), atom_chars(R, CR)....
Give a code snippet in #Prolog Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Commodore_BASIC
Commodore BASIC
1 rem password generator 2 rem rosetta code 10 g$(1)="abcdefghijklmnopqrstuvwxyz" 15 g$(2)="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 20 g$(3)="0123456789" 25 g$(4)="<>!@#$%^&*()[];:'.?/" 30 print chr$(147);chr$(14) 35 print "Password Generator":print 40 print "Press H for help, or any":print "other key to begin.":print 45 get k$:if...
Give a code snippet in #Commodore_BASIC Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%...
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...
#SSEM
SSEM
00101000000000100000000000000000 0. -20 to c 11001000000000010000000000000000 1. Sub. 19 10101000000001100000000000000000 2. c to 21 10101000000000100000000000000000 3. -21 to c 00000000000000110000000000000000 4. Test 10001000000000000000000000000000 5. 17 to CI 10101000000001100000000000000000 6. c to 2...
Give a code snippet in #SSEM Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Scheme
Scheme
(define (ncsubseq lst) (let recurse ((s 0) (lst lst)) (if (null? lst) (if (>= s 3) '(()) '()) (let ((x (car lst)) (xs (cdr lst))) (if (even? s) (append (map (lambda (ys) (cons x ys)) (r...
Give a code snippet in #Scheme Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first a...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#REXX
REXX
/*REXX program outputs its own 1─line source.*/ say sourceline(1)
Give a code snippet in #REXX A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Fortran
Fortran
  SUBROUTINE CROAK(GASP) !A dying message. CHARACTER*(*) GASP !The message. WRITE (6,*) "Oh dear! ",GASP !The gasp. STOP "Alas." !The death. END !Goodbye, cruel world.   MODULE LYCHREL SEARCH !Assistants for the pursuit of Lychrel numbers. INTEGER LOTSADIGITS,BASE !Par...
Give a code snippet in #Fortran   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to mos...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#AWK
AWK
# simulate a struct using associative arrays function complex(arr, re, im) { arr["re"] = re arr["im"] = im }   function re(cmplx) { return cmplx["re"] }   function im(cmplx) { return cmplx["im"] }   function printComplex(cmplx) { print re(cmplx), im(cmplx) }   function abs2(cmplx) { return re(cm...
Give a code snippet in #AWK A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyl...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#PHP
PHP
<?php function lookup($r,$c) { $table = array( array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),...
Give a code snippet in #PHP The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Quackery
Quackery
( . . . . . . . . . . . . . . . . . . )   ( The computer will ignore anything between parentheses, providing there is a space or carriage return on either side of each parenthesis. )   ( . . . . . . . . . . . . . . . . . . )   ( A ...
Give a code snippet in #Quackery Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic C...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Kotlin
Kotlin
import java.math.BigInteger   fun factorial(n: BigInteger): BigInteger { if (n == BigInteger.ZERO) return BigInteger.ONE if (n == BigInteger.ONE) return BigInteger.ONE var prod = BigInteger.ONE var num = n while (num > BigInteger.ONE) { prod *= num num-- } return prod }   fun...
Give a code snippet in #Kotlin Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Scheme
Scheme
; Save bitmap to external file (define (save-pbm bitmap filename) (define f (open-output-file filename)) (simple-format f "P1\n~A ~A\n" (list-ref (array-dimensions bitmap) 0) (list-ref (array-dimensions bitmap) 1)) (do ((c 0 (+ c 1))) ((eqv? c (list-ref (array-dimensions bitmap) 1))) (do ((r 0 (+ r 1))) ((eqv? ...
Give a code snippet in #Scheme Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initi...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Maple
Maple
AccumulatorFactory := proc( initial := 0 ) local total := initial; proc( val := 1 ) total := total + val end end proc:
Give a code snippet in #Maple A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pas...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Go
Go
package main   import ( "fmt" )   func main() { var d, n, o, u, u89 int64   for n = 1; n < 100000000; n++ { o = n for { u = 0 for { d = o%10 o = (o - d) / 10 u += d*d if o == 0 { break } } if u == 89 || u == 1 { if u == 89 { u89++ } break } o = u } } fmt.Pr...
Give a code snippet in #Go If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#hexiscript
hexiscript
println "File \"input.txt\"? " + (exists "input.txt") println "Dir \"docs\"? " + (exists "docs/") println "File \"/input.txt\"? " + (exists "/input.txt") println "Dir \"/docs\"? " + (exists "/docs/")
Give a code snippet in #hexiscript Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it work...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", ...
Give a code snippet in #C.23 A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Quackery
Quackery
/O> 0 0 ** ...   Stack: 1  
Give a code snippet in #Quackery Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#F.23
F#
let bitwise a b = printfn "a and b: %d" (a &&& b) printfn "a or b: %d" (a ||| b) printfn "a xor b: %d" (a ^^^ b) printfn "not a: %d" (~~~a) printfn "a shl b: %d" (a <<< b) printfn "a shr b: %d" (a >>> b) // arithmetic shift printfn "a shr b: %d" ((uint32 a) >>> b) // logical shif...
Give a code snippet in #F.23 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#xEec
xEec
i# i# ma h#10 r o# p o$ p
Give a code snippet in #xEec A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#TXR
TXR
$ txr -p '(n-perm-k 10 10)' 3628800
Give a code snippet in #TXR Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#uBasic.2F4tH
uBasic/4tH
Print FUNC(_MulInv(42, 2017)) End   _MulInv Param(2) Local(5)   c@ = b@ f@ = 0 g@ = 1   If b@ = 1 Then Return   Do While a@ > 1 e@ = a@ / b@ d@ = b@ b@ = a@ % b@ a@ = d@   d@ = f@ f@ = g@ - e@ * f@ g@ = d@ Loop   If g@ < 0 Then g@ = g@ + c@ Return (g@)
Give a code snippet in #uBasic.2F4tH From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Groovy
Groovy
def keys = ['a','b','c'] def vals = ['aaa', 'bbb', 'ccc'] def hash = [:] keys.eachWithIndex { key, i -> hash[key] = vals[i] }
Give a code snippet in #Groovy Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
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....
#J
J
lcstr=:4 :0 C=. ({.~ 1+$) x=/y M=. >./ (* * * >. * + (_1&|.)@:|:^:2)^:_ C N=. >./ M y {~ (M i. N)-i.-N )
Give a code snippet in #J 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#C
C
#include <unistd.h> //for isatty() #include <stdio.h> //for fileno()   int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
Give a code snippet in #C Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#Kotlin
Kotlin
// version 1.2.0   import kotlin.math.abs   // Holes A=0, B=1, …, H=7 // With connections: const val conn = """ A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H """   val connections = listOf( 0 to 2, 0 to 3, 0 to 4, // A to C, D,...
Give a code snippet in #Kotlin You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Raku
Raku
sub equilibrium_index(@list) { my ($left,$right) = 0, [+] @list;   gather for @list.kv -> $i, $x { $right -= $x; take $i if $left == $right; $left += $x; } }   my @list = -7, 1, 5, 2, -4, 3, 0; .say for equilibrium_index(@list).grep(/\d/);
Give a code snippet in #Raku An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#D
D
import std.stdio, std.math, std.conv, std.algorithm, std.array;   double f(in double x) pure nothrow { return x.abs.sqrt + 5 * x ^^ 3; }   void main() { double[] data;   while (true) { "Please enter eleven numbers on a line: ".write; data = readln.split.map!(to!double).array; if (dat...
Give a code snippet in #D The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giv...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Mercury
Mercury
  :- module input_loop. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :- io.stdin_stream(Stdin, !IO), io.stdout_stream(Stdout, !IO), read_and_print_lines(Stdin, Stdout, !IO).   :- pred read_and_print_lines(io.text_input_stream::in, io.text_out...
Give a code snippet in #Mercury Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Scala
Scala
val q = "\"" * 3 val c = """val q = "\"" * 3 val c = %s%s%s println(c format (q, c, q)) """ println(c format (q, c, q))
Give a code snippet in #Scala A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#C.23
C#
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
Give a code snippet in #C.23 Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, El...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#C.23
C#
class Program { static void Main(string[] args) { Random random = new Random(); while (true) { int a = random.Next(20); Console.WriteLine(a); if (a == 10) break; int b = random.Next(20) Console.WriteLine(b); ...
Give a code snippet in #C.23 Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. I...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Sparkling
Sparkling
spn:3> repeat("na", 8) .. " Batman!" = nananananananana Batman!
Give a code snippet in #Sparkling Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*",...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Nim
Nim
import bitmap   proc setPixel(img: Image; x, y: int; color: Color) {.inline.} = # Set a pixel at a given color. # Ignore if the point is outside of the image. if x in 0..<img.w and y in 0..<img.h: img[x, y] = color     proc drawCircle(img: Image; center: Point; radius: Natural; color: Color) = ## Draw a cir...
Give a code snippet in #Nim Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#R
R
library(gWidgets) library(gWidgetstcltk) win <- gwindow() lab <- glabel("There have been no clicks yet", container=win) btn <- gbutton("click me", container=win, handle=function(h, ...) { val <- as.numeric(svalue(lab)) svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1)) } )
Give a code snippet in #R Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#PureBasic
PureBasic
#Window1 = 0 #Image1 = 0 #ImgGadget = 0   #NUM_PARTICLES = 3000 #width = 200 #height = 200 #xmax = #width -3 #ymax = #height -3 Define.i Event ,i ,x,y   If OpenWindow(#Window1, 0, 0, #width, #height, "Brownian Tree PureBasic Example", #PB_Window_SystemMenu ) If CreateImage(#Ima...
Give a code snippet in #PureBasic Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The in...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Factor
Factor
: spam ( -- ) "SPAM" print spam ;
Give a code snippet in #Factor Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#zkl
zkl
fcn move(n, from,to,via){ if (n>0){ move(n-1, from,via,to); println("Move disk from pole %d to pole %d".fmt(from, to)); move(n-1, via,to,from); } } move(3, 1,2,3);
Give a code snippet in #zkl Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Standard_ML
Standard ML
  List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;  
Give a code snippet in #Standard_ML Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Phixmonti
Phixmonti
argument 1 get ?
Give a code snippet in #Phixmonti The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the scr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#SNOBOL4
SNOBOL4
define('sieve(n)i,j,k,p,str,res') :(sieve_end) sieve i = lt(i,n - 1) i + 1 :f(sv1) str = str (i + 1) ' ' :(sieve) sv1 str break(' ') . j span(' ') = :f(return) sieve = sieve j ' ' sieve = gt(j ^ 2,n) sieve str :s(return) ;* Opt1 res = '' str (arb ' ') @p ((j ^ 2) ' ...
Give a code snippet in #SNOBOL4 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes  ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Ada
Ada
with Ada.Text_IO;   procedure Nth is   function Suffix(N: Natural) return String is begin if N mod 10 = 1 and then N mod 100 /= 11 then return "st"; elsif N mod 10 = 2 and then N mod 100 /= 12 then return "nd"; elsif N mod 10 = 3 and then N mod 100 /= 13 then return "rd"; else return "t...
Give a code snippet in #Ada Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show h...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Plain_English
Plain English
\All required helper routines already exist in Plain English: \ \To cut a number in half: \Divide the number by 2. \ \To double a number: \Add the number to the number. \ \To decide if a number is odd: \Privatize the number. \Bitwise and the number with 1. \If the number is 0, say no. \Say yes.   To run: Start up. Put ...
Give a code snippet in #Plain_English Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainder...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Forth
Forth
include lib/selcsort.4th \ use a tiny sorting algorithm   150 value left \ capacity in 1/10th kilo   create items \ list of items ," beef" 38 , 3600 , \ description, weight, price (cents) ," pork" 54 , 4300 , \ weight in...
Give a code snippet in #Forth A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the...
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...
#Scheme
Scheme
(define (string-top s) (if (string=? s "") s (substring s 0 (- (string-length s) 1))))   (define (string-tail s) (if (string=? s "") s (substring s 1 (string-length s))))   (define (string-top-tail s) (string-tail (string-top s)))
Give a code snippet in #Scheme 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Racket
Racket
#lang racket (require math)   (define sqrt5 (sqrt 5)) (define phi (* 0.5 (+ 1 sqrt5)))   ;; What is the nth fibonnaci number, shifted by 2 so that ;; F(0) = 1, F(1) = 2, ...? ;; (define (F n) (fibonacci (+ n 2)))   ;; What is the largest n such that F(n) <= m? ;; (define (F* m) (let ([n (- (inexact->exact (round (/...
Give a code snippet in #Racket This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Action.21
Action!
SET EndProg=*
Give a code snippet in #Action.21 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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Sidef
Sidef
var arr = [1,2,3,4,5];   # Creates a new array var new = arr.grep {|i| i %% 2}; say new.dump; # => [2, 4]   # Destructive (at variable level) arr.grep! {|i| i %% 2}; say arr.dump; # => [2, 4]
Give a code snippet in #Sidef Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#TI-83_BASIC
TI-83 BASIC
5->N DelVar [F] {N,N}→dim([F]) 1→A: N→B 1→C: N→D 0→E: E→G 1→I: 1→J For(K,1,N*N) K-1→[F](I,J) If E=0: Then If J<D: Then J+1→J Else: 1→G I+1→I: A+1→A End End If E=1: Then If I<B: Then I+1→I Else: 2→G J-1→J: D-1→D End End If E=2: Then If J>C: Then J-1→J Else: 3→G I-1→I: B-1→B End End If E=3: Then If I>A: Then I-1→I E...
Give a code snippet in #TI-83_BASIC Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Action.21
Action!
DEFINE MAXSIZE="12"   INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 207 210 212 215 217 219 222 224 226 228 230 232 234 236 237 239 241 242 243 245...
Give a code snippet in #Action.21 Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#MAXScript
MAXScript
-- Returns filesize in bytes or 0 if the file is missing getFileSize "index.txt" getFileSize "\index.txt"
Give a code snippet in #MAXScript Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Fortran
Fortran
module matmod implicit none   ! Overloading the ** operator does not work because the compiler cannot ! differentiate between matrix exponentiation and the elementwise raising ! of an array to a power therefore we define a new operator interface operator (.matpow.) module procedure matrix_exp end interface   ...
Give a code snippet in #Fortran Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Oz
Oz
fun {IsNumeric S} {String.isInt S} orelse {String.isFloat S} end
Give a code snippet in #Oz Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Arra...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Kotlin
Kotlin
// version 1.1.2   val oneNames = listOf( "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen") val tenNames = listOf( "", "", "twenty", "thirty", "...
Give a code snippet in #Kotlin Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Dyalect
Dyalect
func isPerfect(num) { var sum = 0 for i in 1..<num { if !i { break } if num % i == 0 { sum += i } } return sum == num }   let max = 33550337 print("Perfect numbers from 0 to \(max):")   for x in 0..max { if isPerfect(x) { print("\(x) is...
Give a code snippet in #Dyalect Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itse...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#Rust
Rust
// [dependencies] // chrono = "0.4"   fn is_palindrome(s: &str) -> bool { s.chars().rev().eq(s.chars()) }   fn main() { let mut date = chrono::Utc::today(); let mut count = 0; while count < 15 { if is_palindrome(&date.format("%Y%m%d").to_string()) { println!("{}", date.format("%F"));...
Give a code snippet in #Rust Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program...
christopher/rosetta-code