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/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
#Ol
Ol
  (define (isatty? fd) (syscall 16 fd 19)) (print (if (isatty? stdin) "Input comes from tty." "Input doesn't come from tty."))  
Give a code snippet in #Ol 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/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 ...
#SNOBOL4
SNOBOL4
A = "true" * "if-then-else" if A "true" :s(goTrue)f(goFalse) goTrue output = "A is TRUE" :(fi) goFalse output = "A is not TRUE" :(fi) fi   * "switch" switch A ("true" | "false") . switch :s($("case" switch))f(default) casetrue output = "A is TRUE" :(esac) casefalse output = "A is FALSE" :(esac) default output = "...
Give a code snippet in #SNOBOL4 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/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#CMake
CMake
# Show random integer from 0 to 9999. string(RANDOM LENGTH 4 ALPHABET 0123456789 number) math(EXPR number "${number} + 0") # Remove extra leading 0s. message(STATUS ${number})
Give a code snippet in #CMake The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorith...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Groovy
Groovy
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 }   def makePermutation; makePermutation = { list, i -> def n = list.size() if (n < 2) return list def fact = factorial(n-1) assert i < fact*n   def index = i.intdiv(fact) [list[index]] + makePermutation(list[0..<index] + list[(i...
Give a code snippet in #Groovy 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/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#J
J
countBases=: (({.;#)/.~)@, totalBases=: #@,   require 'format/printf'   printSequence=: verb define 'Sequence:' printf '' '%4d: %s' printf ((- {.)@(+/\)@:(#"1) ,.&<"_1 ]) y '\n Base Count\n-----------' printf '' '%5s: %4d' printf countBases y '-----------\nTotal = %3d' printf totalBases y )
Give a code snippet in #J Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGAT...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Clojure
Clojure
(defn decode [str] (String. (.decode (java.util.Base64/getDecoder) str)))   (decode "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")  
Give a code snippet in #Clojure See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Go
Go
package main   import ( "fmt" "strings" )   func main() { s := "Hello,How,Are,You,Today" fmt.Println(strings.Join(strings.Split(s, ","), ".")) }
Give a code snippet in #Go Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks relat...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into ...
#Phix
Phix
with javascript_semantics sequence words = unix_dict() function right_length(string word, integer l) return length(word)=l end function function one_away(string a, b) return sum(sq_ne(a,b))=1 end function function dca(sequence s, n) return append(deep_copy(s),n) end function procedure word_ladder(string a, b) s...
Give a code snippet in #Phix Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the follo...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#Common_Lisp
Common Lisp
  (format t "札幌~%") (format t "~C~%" (code-char #x00A3))  
Give a code snippet in #Common_Lisp Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#FutureBasic
FutureBasic
  include "ConsoleWindow"   local fn DoUnixCommand( cmd as str255 ) dim as str255 s   open "Unix", 2, cmd while ( not eof(2) ) line input #2, s print s wend close 2 end fn   fn DoUnixCommand( "ls -A" )  
Give a code snippet in #FutureBasic Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#PicoLisp
PicoLisp
(de rdConf (File) (in File (while (read) (set @ (or (pack (clip (line))) T)) ) ) )   (rdConf "conf.txt") (println FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY) (bye)
Give a code snippet in #PicoLisp The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon a...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#C.2B.2B
C++
  #include <windows.h> #include <iostream>   //----------------------------------------------------------------------------------------- using namespace std;   //----------------------------------------------------------------------------------------- const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, ...
Give a code snippet in #C.2B.2B Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed ...
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...
#Groovy
Groovy
println 'ha' * 5
Give a code snippet in #Groovy Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#COBOL
COBOL
MOVE "Hello" TO src MOVE src TO dst
Give a code snippet in #COBOL This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
christopher/rosetta-code
http://rosettacode.org/wiki/List_rooted_trees
List rooted trees
You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all...
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => bagPatterns(5) .join('\n');   // BAG PATTERNS ---------------------------------------   // bagPatterns :: Int -> [String] const bagPatterns = n => nub(map( composeList([ commasFromTree, de...
Give a code snippet in #JavaScript You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are variou...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#FunL
FunL
data Employee( name, id, salary, dept )   employees = [ Employee( 'Tyler Bennett', 'E10297', 32000, 'D101' ), Employee( 'John Rappl', 'E21437', 47000, 'D050' ), Employee( 'George Woltman', 'E00127', 53500, 'D101' ), Employee( 'Adam Smith', 'E63535', 18000, 'D202' ), Employee( 'Claire Buckman', 'E39876', 27800...
Give a code snippet in #FunL Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,S...
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...
#SSEM
SSEM
01000000000000000000000000000000 26. 2 01111000000000000000000000000000 27. 30 10000000000000000000000000000000 28. 1 01011000000000000000000000000000 29. 26 11000000000000000000000000000000 30. 3 00000000000000000000000000000000 31. 0
Give a code snippet in #SSEM 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 defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#MATLAB
MATLAB
function [closest,closestpair] = closestPair(xP,yP)   N = numel(xP);   if(N <= 3)   %Brute force closestpair if(N < 2) closest = +Inf; closestpair = {}; else closest = norm(xP{1}-xP{2}); closestpair = {xP{1},xP{2}};   fo...
Give a code snippet in #MATLAB This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Zoomscript
Zoomscript
var randnum var guess randnum & random 1 10 guess = 0 while ne randnum guess print "I'm thinking of a number between 1 and 10. What is it? " guess & get if lt guess randnum print "Too low. Try again!" println endif if gt guess randnum print "Too high. Try again!" println endif endwhile print "Correct number. You win!"
Give a code snippet in #Zoomscript Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Xtend
Xtend
  package com.rosetta.example   import java.io.File import java.io.PrintStream   class WriteFile { def static main( String ... args ) { val fout = new PrintStream(new File(args.get(0))) fout.println("Some text.") fout.close } }  
Give a code snippet in #Xtend Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wren
Wren
import "/sort" for Sort   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3], ["echo", "lima", "charlie", "whiskey", "golf", "papa", "alfa", "india", "foxtrot", "kilo"] ] for (a in as) { System.print("Before: %(a)") Sort.quick(a) System.print("After : %(a)") System...
Give a code snippet in #Wren 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/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#VBScript
VBScript
  Function multsum35(n) For i = 1 To n - 1 If i Mod 3 = 0 Or i Mod 5 = 0 Then multsum35 = multsum35 + i End If Next End Function   WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0))) WScript.StdOut.WriteLine  
Give a code snippet in #VBScript Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Modula-2
Modula-2
MODULE McNuggets; FROM InOut IMPORT WriteCard, WriteString, WriteLn;   CONST Max = 100; VAR a, b, c: CARDINAL; nugget: ARRAY [0..Max] OF BOOLEAN;   BEGIN FOR a := 0 TO Max DO nugget[a] := FALSE; END;   FOR a := 0 TO Max BY 6 DO FOR b := a TO Max BY 9 DO FOR c := b TO Max BY 2...
Give a code snippet in #Modula-2 Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A M...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function list = cocktailSort(list)   %We have to do this because the do...while loop doesn't exist in MATLAB swapped = true;   while swapped   %Bubble sort down the list swapped = false; for i = (1:numel(list)-1) if( list(i) > list(i+1) ) list([i i+1]) ...
Give a code snippet in #MATLAB_.2F_Octave 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/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...
#Wren
Wren
import "/pattern" for Pattern   var doc = """ <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"...
Give a code snippet in #Wren Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #4...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Groovy
Groovy
class FractionReduction { static void main(String[] args) { for (int size = 2; size <= 5; size++) { reduce(size) } }   private static void reduce(int numDigits) { System.out.printf("Fractions with digits of length %d where cancellation is valid. Examples:%n", numDigits) ...
Give a code snippet in #Groovy There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#D
D
import std.stdio, std.algorithm, std.range, std.conv, std.string;   bool isSelfDescribing(in long n) pure nothrow @safe { auto nu = n.text.representation.map!q{ a - '0' }; return nu.length.iota.map!(a => nu.count(a)).equal(nu); }   void main() { 4_000_000.iota.filter!isSelfDescribing.writeln; }
Give a code snippet in #D Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit ...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#PARI.2FGP
PARI/GP
Function: _@_ Help: x@y: compute the lesser of x and y, or 0, whichever is larger. Section: symbolic_operators C-Name: gmin0 Prototype: GG Description: (small, small):small smin0ss($1, $2) (mp, mp):mp gmin0($1, $2) (gen, gen):gen gmin0($1, $2)
Give a code snippet in #PARI.2FGP Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Erlang
Erlang
Src = "Hello". Dst = Src.
Give a code snippet in #Erlang This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
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 ...
#VAX_Assembly
VAX Assembly
0000 0000 1 .entry main,0 7E 7CFD 0002 2 clro -(sp) ;result buffer 5E DD 0005 3 pushl sp ;pointer to buffer 10 DD 0007 4 pushl #16 ;descriptor: len of buffer ...
Give a code snippet in #VAX_Assembly 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 soluti...
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...
#Ela
Ela
[] <. _ = true _ <. [] = false (x::xs) <. (y::ys) | x == y = xs <. ys | else = x < y   [1,2,1,3,2] <. [1,2,0,4,4,0,0,0]
Give a code snippet in #Ela 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#DBL
DBL
; ; Variables examples for DBL version 4 by Dario B. ;   .DEFINE NR,10  ;const .DEFINE AP,"PIPPO"  ;const     RECORD CUSTOM COD, D5 NAME, A80 ZIP, D6 CITY, A80 ;-----------------------   RECORD   ALPHA, A5  ;alphanumeric NUMBR, D5  ;number DECML, F5....
Give a code snippet in #DBL Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#R
R
exp(1) # e pi # pi sqrt(x) # square root log(x) # natural logarithm log10(x) # base 10 logarithm log(x, y) # arbitrary base logarithm exp(x) # exponential abs(x) # absolute value floor(x) # floor ceiling(x) #...
Give a code snippet in #R Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magni...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Sparkling
Sparkling
let contents = readfile("foo.txt");
Give a code snippet in #Sparkling Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished i...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#C
C
  /*   David Lambert, 2010-Dec-09   filter producing morse beep commands.   build: make morse   use: $ echo tie a. | ./morse beep -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 100 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -D 200 -n -D 400 -n -f 440 -l 100 -D 100 -n -f 440 ...
Give a code snippet in #C Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unk...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Inverse_video
Terminal control/Inverse video
Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
#TPP
TPP
--revon This is inverse --revoff This is normal
Give a code snippet in #TPP Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest ...
#PARI.2FGP
PARI/GP
v=pareval(vector(1000,i,()->factor(2^i+1)[1,1])); vecmin(v)
Give a code snippet in #PARI.2FGP Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and wan...
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 ...
#Julia
Julia
julia> A = [("UK", "London"), ("US", "New York"), ("US", "Birmingham"), ("UK", "Birmingham")]; julia> sort(A, by=x -> x[2]) 4-element Array{(ASCIIString,ASCIIString),1}: ("US","Birmingham") ("UK","Birmingham") ("UK","London") ("US","New York")
Give a code snippet in #Julia 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/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Golfscript
Golfscript
#Cooley-Tukey   {.,.({[\.2%fft\(;2%fft@-1?-1\?-2?:w;.,,{w\?}%[\]zip{{*}*}%]zip.{{+}*}%\{{-}*}%+}{;}if}:fft;   [1 1 1 1 0 0 0 0]fft n*  
Give a code snippet in #Golfscript Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Yabasic
Yabasic
print " n First Second Third" print " - ----- ------ -----" print for i = 0 to 15 print i using "###", catalan1(i) using "########", catalan2(i) using "########", catalan3(i) using "########" next i end   sub factorial(n) if n = 0 return 1 return n * factorial(n - 1) end sub   sub catalan1(n...
Give a code snippet in #Yabasic Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Java
Java
import java.util.Locale;   public class GaussianElimination { public static double solve(double[][] a, double[][] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { throw new IllegalArgumentException("Invalid dimensions"); }   int n = b.length, p = b[0].length; ...
Give a code snippet in #Java Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Wren
Wren
import "random" for Random import "/trait" for Stepped   var F = [ [1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0], [1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0], [1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1], [1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1] ]   va...
Give a code snippet in #Wren A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
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...
#MiniZinc
MiniZinc
int: n; array [1..n] of var 1..n: q; % queen in column i is in row q[i]   include "alldifferent.mzn";   constraint alldifferent(q);  % distinct rows constraint alldifferent([ q[i] + i | i in 1..n]); % distinct diagonals constraint alldifferent([ q[i] - i | i in 1..n]); % upwards+downwards   % searc...
Give a code snippet in #MiniZinc 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'...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#C.2B.2B
C++
#include <iterator> #include <algorithm> // for std::inplace_merge #include <functional> // for std::less   template<typename RandomAccessIterator, typename Order> void mergesort(RandomAccessIterator first, RandomAccessIterator last, Order order) { if (last - first > 1) { RandomAccessIterator middle = first + ...
Give a code snippet in #C.2B.2B 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/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Maple
Maple
Quibble := proc( los ) uses StringTools; Fence( proc() if los = [] then "" elif numelems( los ) = 1 then los[ 1 ] else cat( Join( los[ 1 .. -2 ], ", " ), " and ", los[ -1 ] ) end if end(), "{", "}" ) end proc:
Give a code snippet in #Maple Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An in...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#PHP
PHP
<?php echo gmdate('r', 0), "\n"; ?>
Give a code snippet in #PHP Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the sce...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Factor
Factor
USING: random ; 1000 [ 1.0 0.5 normal-random-float ] replicate
Give a code snippet in #Factor Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code code virtual machine in Ratfor 77. # # The implementation assumes your FORTRAN compiler supports 1-byte # INTEGER*1 and 4-byte INTEGER*4. Integer storage will be # native-endian, achieved via EQUIVALENCE. (GNU Fortran and f2c bo...
Give a code snippet in #RATFOR A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read in...
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...
#Rascal
Rascal
str s = ""; if (s=="") print("string s is empty"); if (s!="") print("string s is not empty");  
Give a code snippet in #Rascal 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. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#ALGOL_W
ALGOL W
begin  % find a, b, c, d, e such that a^5 + b^5 + c^5 + d^5 = e^5  %  % where 1 <= a <= b <= c <= d <= e <= 250  %  % we solve this using the equivalent equation a^5 + b^5 + c^5 = e^5 - d^5  %  % 250^5 is 976 562 500 000 -...
Give a code snippet in #ALGOL_W There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power...
christopher/rosetta-code
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Sidef
Sidef
func korasaju(Array g) { # 1. For each vertex u of the graph, mark u as unvisited. Let L be empty. var vis = g.len.of(false) var L = [] var x = g.end var t = g.len.of { [] }   # Recursive func visit(u) { if (!vis[u]) { vis[u] = true g[u].each {|v| ...
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosa...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Ela
Ela
x = 42   sum x y = x + y
Give a code snippet in #Ela Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) limit := integer(A[1]) | 20 every writes(niven(seq())\limit," ") writes("... ") write(niven(seq(1001))\1) end   procedure niven(n) n ? {s := 0; while s +:= move(1)} if (n%s) = 0 then return n end
Give a code snippet in #Icon_and_Unicon The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Qi
Qi
(define select-r Small [] Output -> [Small | (selection-sort Output)] Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small) Small [X|Xs] Output -> (select-r Small Xs [X|Output]))   (define selection-sort [] -> [] [First|Lst] -> (select-r First Lst []))   (selection-sort [8 7 4 3...
Give a code snippet in #Qi 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#HicEst
HicEst
SYSTEM(CoMmand='pause') SYSTEM(CoMmand='dir & pause')
Give a code snippet in #HicEst Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Frink
Frink
dog = "Benjamin" Dog = "Samba" DOG = "Bernie" println["There are three dogs named $dog, $Dog and $DOG"]
Give a code snippet in #Frink Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sa...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Wren
Wren
import "/fmt" for Fmt   var d2d = Fn.new { |d| d % 360 } var g2g = Fn.new { |g| g % 400 } var m2m = Fn.new { |m| m % 6400 } var r2r = Fn.new { |r| r % (2*Num.pi) } var d2g = Fn.new { |d| d2d.call(d) * 400 / 360 } var d2m = Fn.new { |d| d2d.call(d) * 6400 / 360 } var d2r = Fn.new { |d| d2d.call(d) * Num.pi / 180 } var g...
Give a code snippet in #Wren This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 36...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Elixir
Elixir
defmodule Random do defp generate_point(0, _, _, set), do: set defp generate_point(n, f, condition, set) do point = {x,y} = {f.(), f.()} if x*x + y*y in condition and not point in set, do: generate_point(n-1, f, condition, MapSet.put(set, point)), else: generate_point(n, f, condition, set) ...
Give a code snippet in #Elixir Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" ci...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Swift
Swift
public func convertToUnicodeScalars( str: String, minChar: UInt32, maxChar: UInt32 ) -> [UInt32] { var scalars = [UInt32]()   for scalar in str.unicodeScalars { let val = scalar.value   guard val >= minChar && val <= maxChar else { continue }   scalars.append(val) }   return scalars ...
Give a code snippet in #Swift Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#C
C
  #include<stdlib.h> #include<stdio.h> #include<math.h>   typedef struct{ int a,b,c; int perimeter; double area; }triangle;   typedef struct elem{ triangle t; struct elem* next; }cell;   typedef cell* list;   void addAndOrderList(list *a,triangle t){ list iter,temp; int flag = 0;   if(*a==NULL){ *a = (list)ma...
Give a code snippet in #C Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(insertionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end   procedure insertionsort(X,op) #: return sorted X local i,temp   op := sortop(op,X) # select how and what we sort   every i := 2 to ...
Give a code snippet in #Icon_and_Unicon 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/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Lua
Lua
local function recA(age, name) return { Age=age, Name=name } end local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") }   local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end local tabB = { recB("Jonah","Whales"), recB("Jonah","Spi...
Give a code snippet in #Lua An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" a...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#zkl
zkl
class Chao{ var [const private] lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; fcn encode(text){ code(text,encodeL); } fcn decode(text){ code(text,decodeL); } // reset alphabets each [en|de]code and maintain re-entrancy fcn code(text,f){ text.apply(f,Data(Voi...
Give a code snippet in #zkl Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there i...
christopher/rosetta-code
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size...
#Wren
Wren
import "/fmt" for Fmt   var pancake = Fn.new { |n| var gap = 2 var sum = 2 var adj = -1 while (sum < n) { adj = adj + 1 gap = gap*2 - 1 sum = sum + gap } return n + adj }   for (i in 0..3) { for (j in 1..5) { var n = i*5 + j Fmt.write("p($2d) = $2d ",...
Give a code snippet in #Wren Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stac...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Nim
Nim
import asyncnet, asyncdispatch   proc processClient(client: AsyncSocket) {.async.} = while true: let line = await client.recvLine() await client.send(line & "\c\L")   proc serve() {.async.} = var server = newAsyncSocket() server.bindAddr(Port(12321)) server.listen()   while true: let client = awai...
Give a code snippet in #Nim Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to s...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#JavaScript
JavaScript
var container = {myString: "Hello"}; var containerCopy = container; // Now both identifiers refer to the same object   containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"
Give a code snippet in #JavaScript This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Em...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#AppleScript
AppleScript
use framework "Foundation" -- for basic NSArray sort   on run unlines({"rings(true, enumFromTo(1, 7))\n", ¬ map(show, (rings(true, enumFromTo(1, 7)))), ¬ "\nrings(true, enumFromTo(3, 9))\n", ¬ map(show, (rings(true, enumFromTo(3, 9)))), ¬ "\nlength(rings(false, enumFromTo(0, 9)))\n",...
Give a code snippet in #AppleScript 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#REXX
REXX
/*REXX program multiplies two matrices together, displays the matrices and the result.*/ m= (1 2 3) (4 5 6) (7 8 9) w= words(m); do rows=1; if rows*rows>=w then leave end /*rows*/ cols= rows call showMat M, 'M matrix' answer= matAdd(m, 2 ); call showMat ...
Give a code snippet in #REXX This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   expone...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#XLISP
XLISP
(defmacro f10-at-compile-time () (* 2 3 4 5 6 7 8 9 10))
Give a code snippet in #XLISP Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#OCaml
OCaml
# let list1 = [1; 2; 3];; val list1 : int list = [1; 2; 3] # let list2 = [4; 5; 6];; val list2 : int list = [4; 5; 6] # let list1and2 = list1 @ list2;; val list1and2 : int list = [1; 2; 3; 4; 5; 6]
Give a code snippet in #OCaml Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Kotlin
Kotlin
// Version 1.2.70   import kotlin.math.abs   infix fun Int.pow(e: Int): Int { if (e == 0) return 1 var prod = this for (i in 2..e) { prod *= this } return prod }   fun main(args: Array<String>) { var prod = 1 var sum = 0 val x = 5 val y = -5 val z = -2 val one = 1 ...
Give a code snippet in #Kotlin Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED...
christopher/rosetta-code
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the...
#Perl
Perl
use strict; use warnings; use feature 'say';   my $seq; for my $x (0..99) { my $a = sprintf '%02d', $x; next if substr($a,1,1) < substr($a,0,1); $seq .= (substr($a,0,1) == substr($a,1,1)) ? substr($a,0,1) : $a; for ($a+1 .. 99) { next if substr(sprintf('%02d', $_), 1,1) <= substr($a,0,1); ...
Give a code snippet in #Perl The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#360_Assembly
360 Assembly
XS4 DC E'1.23456E-4' short floating-point   XDPI DC D'3.141592653589793' long floating-point XD1 DC D'0' long floating-point XD2 DC D'1' long floating-point XD3 DC D'-1' long floating-point XD4 DC D'1.2345E-4' long floating-...
Give a code snippet in #360_Assembly Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#R
R
  # vectorized approach based on scalar code from primeSieve and mersenne in CRAN package `numbers` require(gmp) n <- 4423 # note that the sieve below assumes n > 9   # sieve the set of primes up to n p <- seq(1, n, by = 2) q <- length(p) p[1] <- 2 for (k in seq(3, sqrt(n), by = 2)) if (p[(k + 1)/2] != 0) p[seq...
Give a code snippet in #R Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tree_from_nesting_levels
Tree from nesting levels
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than the previous then it appears in a sub-list o...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   type any = interface{}   func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: Every int appears, in order, at its depth of nesting. If the next level int is greater than t...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#8080_Assembly
8080 Assembly
;;; Show attractive numbers up to 120 MAX: equ 120 ; can be up to 255 (8 bit math is used) ;;; CP/M calls puts: equ 9 bdos: equ 5 org 100h ;;; -- Zero memory ------------------------------------------------ lxi b,fctrs ; page 2 mvi e,2 ; zero out two pages xra a mov d,a zloop: stax b inx b dcr d jnz zloop ...
Give a code snippet in #8080_Assembly A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. ...
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...
#Raku
Raku
my ( $min_sum, $hero_attr_min, $hero_count_min ) = 75, 15, 2; my @attr-names = <Str Int Wis Dex Con Cha>;   sub heroic { + @^a.grep: * >= $hero_attr_min }   my @attr; repeat until @attr.sum >= $min_sum and heroic(@attr) >= $hero_count_min {   @attr = @attr-names.map: { (1..6).roll(4).sort(+*).skip(1).s...
Give a code snippet in #Raku 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-sid...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Julia
Julia
nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ]
Give a code snippet in #Julia The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Wren
Wren
import "graphics" for Canvas, Color, ImageData import "dome" for Window   class PercentageDifference { construct new(width, height, image1, image2) { Window.title = "Perecentage difference between images" Window.resize(width, height) Canvas.resize(width, height) _img1 = ImageData.loa...
Give a code snippet in #Wren basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Pascal
Pascal
program NivenGaps; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$ELSE} {$APPTYPE DELPHI} {$ENDIF} uses sysutils, strutils; const base = 10; type tNum = Uint64; const cntbasedigits = ((trunc(ln(High(tNum))/ln(base))+1) DIV 8 +1) *8; type tSumDigit = record sdDigits : array[...
Give a code snippet in #Pascal Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#UNIX_Shell
UNIX Shell
# This while loop repeats for each line of the file. # This loop is inside a pipeline; many shells will # run this loop inside a subshell. cat input.txt | while IFS= read -r line ; do printf '%s\n' "$line" done
Give a code snippet in #UNIX_Shell Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#AutoHotkey
AutoHotkey
DllCall("AllocConsole") FileAppend, Goodbye`, World!, CONOUT$ ; No newline outputted MsgBox
Give a code snippet in #AutoHotkey Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Stata
Stata
program sleep_awake * pass duration in milliseconds display "Sleeping..." sleep `0' display "Awake!" end   sleep_awake 2000
Give a code snippet in #Stata Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detec...
#AutoHotkey
AutoHotkey
Sort_an_outline(data, reverse:=""){ ;----------------------- ; get Delim, Error Check for i, line in StrSplit(data, "`n", "`r") if !Delim RegExMatch(line, "^\h+", Delim) else if RegExMatch(RegExReplace(line, "^(" Delim ")*"), "^\h+") return "Error @ " line ;----------------------- ; ascending lexical so...
Give a code snippet in #AutoHotkey Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline struc...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Raku
Raku
constant $tenfact = [*] 2..10; say $tenfact;
Give a code snippet in #Raku Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
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
#BCPL
BCPL
GET "libhdr"   LET start() = VALOF { writef("Hello world!") RESULTIS 0 }
Give a code snippet in #BCPL 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/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Haskell
Haskell
import Data.Char (isSpace) import Data.List (dropWhileEnd)   trimLeft :: String -> String trimLeft = dropWhile isSpace   trimRight :: String -> String trimRight = dropWhileEnd isSpace   trim :: String -> String trim = trimLeft . trimRight
Give a code snippet in #Haskell Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Axiom
Axiom
get(obj) == convergents(obj).1000 -- utility to extract the 1000th value get continuedFraction(1, repeating [1], repeating [2]) :: Float get continuedFraction(2, cons(1,[i for i in 1..]), [i for i in 1..]) :: Float get continuedFraction(3, [i^2 for i in 1.. by 2], repeating [6]) :: Float
Give a code snippet in #Axiom continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
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.
#NGS
NGS
F even(x:Int) x % 2 == 0   evens = Arr(1...10).filter(even)
Give a code snippet in #NGS 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/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 ...
#Liberty_BASIC
Liberty BASIC
  dim h( 1000000)   for i =1 to 20 print hamming( i); " "; next i   print print "H( 1691)", hamming( 1691) print "H( 1000000)", hamming( 1000000)   end   function hamming( limit) h( 0) =1 x2 =2: x3 =3: x5 =5 i =0: j =0: k =0 for n =1 to limit h( n) = min( x2, min( x3, x5)) if x2 =...
Give a code snippet in #Liberty_BASIC 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 Hamm...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Stata
Stata
. clear . input x y 0 1 1 6 2 17 3 34 4 57 5 86 6 121 7 162 8 209 9 262 10 321 end   . regress y c.x##c.x   Source | SS df MS Number of obs = 11 -------------+---------------------------------- F(2, 8) = . Model | 120362 2 60181 Pro...
Give a code snippet in #Stata Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Phix
Phix
-- demo\rosetta\Chao_cipher.exw with javascript_semantics constant l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" enum ENCRYPT, DECRYPT function chao_cipher(string s, integer mode, bool show_steps) integer len = length(s) string out = repeat(' ',len), ...
Give a code snippet in #Phix Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there ...
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...
#JavaScript
JavaScript
function almostPrime (n, k) { var divisor = 2, count = 0 while(count < k + 1 && n != 1) { if (n % divisor == 0) { n = n / divisor count = count + 1 } else { divisor++ } } return count == k }   for (var k = 1; k <= 5; k++) { document.write("...
Give a code snippet in #JavaScript 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/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Icon_and_Unicon
Icon and Unicon
  class DoubleLink (value, prev_link, next_link) initially (value, prev_link, next_link) self.value := value self.prev_link := prev_link # links are 'null' if not given self.next_link := next_link end  
Give a code snippet in #Icon_and_Unicon Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Ring
Ring
give n flag = isPrime(n) if flag = 1 see n + " is a prime number" else see n + " is not a prime number" ok   func isPrime num if (num <= 1) return 0 ok if (num % 2 = 0 and num != 2) return 0 ok for i = 3 to floor(num / 2) -1 step 2 if (num % i = 0) return 0 ok next return 1
Give a code snippet in #Ring Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops ...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#AWK
AWK
  # syntax: GAWK -f FOUR_IS_MAGIC.AWK BEGIN { init_numtowords() n = split("-1 0 1 2 3 4 5 6 7 8 9 11 21 1995 1000000 1234567890 1100100100100",arr," ") for (i=1; i<=n; i++) { a = arr[i] printf("%s: ",a) do { if (a == 4) { break } a = numtowords(a) ...
Give a code snippet in #AWK Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of cha...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Nim
Nim
import random, strutils   type   Direction {.pure.} = enum None, Up, Left, Down, Right   Maze = object cells: seq[string] hwalls: seq[string] vwalls: seq[string]     #################################################################################################### # Maze creation.   func initMaze(rows...
Give a code snippet in #Nim Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#Perl
Perl
use ntheory qw/:all/; my @smith; forcomposites { push @smith, $_ if sumdigits($_) == sumdigits(join("",factor($_))); } 10000-1; say scalar(@smith), " Smith numbers below 10000."; say "@smith";
Give a code snippet in #Perl Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are a...
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 ...
#Liberty_BASIC
Liberty BASIC
  randomize 0.5 N=15 dim a(N,2)   for i = 0 to N-1 a(i,1)= int(i/5) a(i,2)= int(rnd(1)*5) next   print "Unsorted by column #2" print "by construction sorted by column #1" for i = 0 to N-1 print a(i,1), a(i,2) next   sort a(), 0, N-1, 2 print   print "After sorting by column #2" print "Notice wrong order by ...
Give a code snippet in #Liberty_BASIC 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/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...
#Whitespace
Whitespace
  ...
Give a code snippet in #Whitespace 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 r...
christopher/rosetta-code