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/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#Perl
Perl
#!/usr/bin/env perl   use strict; use warnings FATAL => 'all'; use autodie ':all'; use List::Util 'min'; use feature 'say';   sub pmin { my $array = shift; my $x = 1; my @pmin_array; my $n = scalar @$array; for (my $index = 0; $index < $n; $index++) { $pmin_array[$index] = min(@$array[$index], $x); } @pmin_arr...
Give a code snippet in #Perl Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#BCPL
BCPL
get "libhdr"   let fib(n) = n<=1 -> n, valof $( let a=0 and b=1 for i=2 to n $( let c=a a := b b := a+c $) resultis b $)   let start() be for i=0 to 10 do writef("F_%N*T= %N*N", i, fib(i))
Give a code snippet in #BCPL The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#SenseTalk
SenseTalk
put ("April", "Tam O'Shanter", "Emily") into names put ("Bubbly: I'm > Tam and <= Emily", <<Burns: "When chapman billies leave the street ...">>, "Short & shrift") into remarks put (_tag: "CharacterRemarks") as tree into document repeat for each item name in names insert (_tag: "Character", name: name, _children: item...
Give a code snippet in #SenseTalk Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks...
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...
#DBL
DBL
XCALL TIME (D6)  ;D6=hhmmss
Give a code snippet in #DBL 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   Da...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Go
Go
package main import "fmt"   func F(n int) int { if n == 0 { return 1 } return n - M(F(n-1)) }   func M(n int) int { if n == 0 { return 0 } return n - F(M(n-1)) }   func main() { for i := 0; i < 20; i++ { fmt.Printf("%2d ", F(i)) } fmt.Println() for i := 0; i < 20; i++ { fmt.Printf("%2d ", M(i)) ...
Give a code snippet in #Go Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) ...
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...
#Groovy
Groovy
def rFact rFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger }
Give a code snippet in #Groovy 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Erlang
Erlang
  %%% @author Tony Wallace <tony@tony.gen.nz> %%% @doc %%% For details of the algorithms used see %%% https://en.wikipedia.org/wiki/Modular_exponentiation %%% @end %%% Created : 21 Jul 2021 by Tony Wallace <tony@resurrection>   -module mod. -export [mod_mult/3,mod_exp/3,binary_exp/2,test/0].   mod_mult(I1,I2,Mod) when ...
Give a code snippet in #Erlang Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryptio...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Sidef
Sidef
func traverse(Block callback, Dir dir) { dir.open(\var dir_h) || return nil   for entry in (dir_h.entries) { if (entry.kind_of(Dir)) { traverse(callback, entry) } else { callback(entry) } } }   var dir = (ARGV ? Dir(ARGV[0]) : Dir.cwd)   var group = Hash() var...
Give a code snippet in #Sidef Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Forth
Forth
2 5 at-xy ." Hello"
Give a code snippet in #Forth Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Lambdatalk
Lambdatalk
  {def dotProduct {lambda {:a :b} {+ {* {A.get 0 :a} {A.get 0 :b}} {* {A.get 1 :a} {A.get 1 :b}} {* {A.get 2 :a} {A.get 2 :b}}}}} -> dotProduct   {def crossProduct {lambda {:a :b} {A.new {- {* {A.get 1 :a} {A.get 2 :b}} {* {A.get 2 :a} {A.get 1 :b}}} {- {* {A.get 2 :a} {A.get 0 :b}...
Give a code snippet in #Lambdatalk A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet ...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Julia
Julia
# http://en.wikipedia.org/wiki/Feigenbaum_constant   function feigenbaum_delta(imax=23, jmax=20) a1, a2, d1 = BigFloat(1.0), BigFloat(0.0), BigFloat(3.2) println("Feigenbaum's delta constant incremental calculation:\ni δ\n1 3.20") for i in 2:imax a = a1 + (a1 - a2) / d1 for j in 1:jmax ...
Give a code snippet in #Julia Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Ruby
Ruby
# create an array with one object in it a = ['foo']   # the Array#new method allows several additional ways to create arrays   # push objects into the array a << 1 # ["foo", 1] a.push(3,4,5) # ["foo", 1, 3, 4, 5]   # set the value at a specific index in the array a[0] = 2 # [2, 1, 3, 4, 5]   # a couple o...
Give a code snippet in #Ruby This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
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 ≤...
#Simula
Simula
BEGIN WHILE NOT LASTITEM DO BEGIN OUTINT(ININT + ININT, 0); OUTIMAGE; END; END.  
Give a code snippet in #Simula 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, separat...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Common_Lisp
Common Lisp
  (defun generate-board () (loop repeat 9 collect nil))   (defparameter *straights* '((1 2 3) (4 5 6) (7 8 9) (1 4 7) (2 5 8) (3 6 9) (1 5 9) (3 5 7))) (defparameter *current-player* 'x)   (defun get-board-elt (n board) (nth (1- n) board))   (defun legal-p (n board) (null (get-board-elt n board)))   (defun set-bo...
Give a code snippet in #Common_Lisp Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   Math...
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...
#AutoHotkey
AutoHotkey
MsgBox % number2base(200, 16) ; 12 MsgBox % parse(200, 16) ; 512   number2base(number, base) { While, base < digit := floor(number / base) { result := mod(number, base) . result number := digit } result := digit . result Return result }   parse(number, base) { result = 0 pos := StrLen(number) - 1...
Give a code snippet in #AutoHotkey 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Kotlin
Kotlin
data class Point(var x: Int, var y: Int)   fun main(args: Array<String>) { val p = Point(1, 2) println(p) p.x = 3 p.y = 4 println(p) }
Give a code snippet in #Kotlin 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#PureBasic
PureBasic
DeleteFile("input.txt") DeleteDirectory("docs","") ; needs to delete all included files DeleteFile("/input.txt") DeleteDirectory("/docs","*.*") ; deletes all files according to a pattern   DeleteDirectory("/docs","",#PB_FileSystem_Recursive) ; deletes all files and directories recursive
Give a code snippet in #PureBasic Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Icon_and_Unicon
Icon and Unicon
invocable all link strings # for csort, deletec, permutes   procedure main() static eL initial { eoP := [] # set-up expression and operator permutation patterns every ( e := !["a@b#c$d", "a@(b#c)$d", "a@b#(c$d)", "a@(b#c$d)", "a@(b#(c$d))"] ) & ( o := !(opers := "+-*/") || !opers || !opers ) do ...
Give a code snippet in #Icon_and_Unicon task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Perl
Perl
use strict; use warnings; use ntheory 'divisor_sum';   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub chowla { my($n) = @_; $n < 2 ? 0 : divisor_sum($n) - ($n + 1); }   sub prime_cnt { my($n) = @_; my $cnt = 1; for (3..$n) { $cnt++ if $_%2 and chowla($_) == 0 ...
Give a code snippet in #Perl Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n  ...
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 ≤...
#Ada
Ada
-- Standard I/O Streams   with Ada.Integer_Text_Io; procedure APlusB is A, B : Integer; begin Ada.Integer_Text_Io.Get (Item => A); Ada.Integer_Text_Io.Get (Item => B); Ada.Integer_Text_Io.Put (A+B); end APlusB;
Give a code snippet in #Ada 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/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Ring
Ring
# Project : Feigenbaum constant calculation   decimals(8) see "Feigenbaum constant calculation:" + nl maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 see "i " + "d" + nl for i = 2 to maxIt a = a1 + (a1 - a2) / d1 for j = 1 to maxItJ x = 0 y = 0 for k = 1 to pow(2,i) ...
Give a code snippet in #Ring Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Prolog
Prolog
:- module(plffi, [strdup/2]). :- use_foreign_library(plffi).
Give a code snippet in #Prolog Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Nim
Nim
import strutils, streams   let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite)   var lineNumber = 1   while true: if atEnd(csv): break var line = readLine(csv)   if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum ...
Give a code snippet in #Nim CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#SQL
SQL
  WITH KnapsackItems (item, [weight], VALUE) AS ( SELECT 'map',9, 150 UNION ALL SELECT 'compass',13, 35 UNION ALL SELECT 'water',153, 200 UNION ALL SELECT 'sandwich',50, 160 UNION ALL SELECT 'glucose',15, 60 UNION ALL SELECT 'tin',68, 45 UNION ALL SELECT 'banana',27, 60 ...
Give a code snippet in #SQL A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have t...
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 ...
#D
D
import std.stdio, std.algorithm, std.array, std.range;   T[] mergeSorted(T)(in T[] D) /*pure nothrow @safe*/ { if (D.length < 2) return D.dup; return [D[0 .. $ / 2].mergeSorted, D[$ / 2 .. $].mergeSorted] .nWayUnion.array; }   void main() { [3, 4, 2, 5, 1, 6].mergeSorted.writeln; }
Give a code snippet in #D 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/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Sidef
Sidef
func circles(a, b, r) {   if (a == b) { if (r == 0) { return ['Degenerate point'] } else { return ['Infinitely many share a point'] } }   var h = (b-a)/2   if (r**2 < h.norm) { return ['Too far apart'] }   var l = sqrt(r**2 - h.norm...
Give a code snippet in #Sidef Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_duplicate_files
Find duplicate files
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the dire...
#Python
Python
from __future__ import print_function import os import hashlib import datetime   def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {}   #Analyse files for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLin...
Give a code snippet in #Python In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with d...
christopher/rosetta-code
http://rosettacode.org/wiki/Untouchable_numbers
Untouchable numbers
Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known as   the   aliquot sum.   A...
#Delphi
Delphi
  program Untouchable_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function SumDivisors(n: Integer): Integer; begin Result := 1; var k := 2; if not odd(n) then k := 1; var i := 1 + k; while i * i <= n do begin if (n mod i) = 0 then begin inc(Result, i); var j := n div i;...
Give a code snippet in #Delphi Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also kn...
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...
#PureBasic
PureBasic
#SymbolCount = 12 ;0 based count DataSection denominations: Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12   denomValues: Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order EndDataSection   ;-setup Structure romanNumeral symbol.s value.i EndStruct...
Give a code snippet in #PureBasic 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...
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
#Slate
Slate
Platform run: 'ls'.
Give a code snippet in #Slate 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/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Haskell
Haskell
import Data.List (delete) import Data.Char (toUpper)   -- returns list of all solutions, each solution being a list of blocks abc :: (Eq a) => [[a]] -> [a] -> [[[a]]] abc _ [] = [[]] abc blocks (c:cs) = [b:ans | b <- blocks, c `elem` b, ans <- abc (delete b blocks) cs]   blocks = ["BO", "XK...
Give a code snippet in #Haskell ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alpha...
christopher/rosetta-code
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext...
#Wren
Wren
import "timer" for Timer import "io" for Stdout   var metronome = Fn.new { |bpm, bpb, maxBeats| var delay = (60000/bpm).floor var beats = 0 while (true) { Timer.sleep(delay) System.write((beats % bpb == 0) ? "\n\aTICK " : "\atick ") Stdout.flush() beats = beats + 1 if...
Give a code snippet in #Wren The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production...
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
#Apricot
Apricot
(puts "Hello world!")
Give a code snippet in #Apricot 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/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh"; include "malloc.coh";   const MAXDEPTH := 256; # Maximum depth (used for stack sizes) const MAXSTR := 256; # Maximum string length   # Type markers const T_ATOM := 1; const T_STRING := 2; const T_NUMBER := 3; const T_LIST := 4;   # Value union record SVal is number @at...
Give a code snippet in #Cowgol S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable dat...
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.
#D
D
void main() { import std.algorithm.searching : maxElement; import std.stdio : writeln;   [9, 4, 3, 8, 5].maxElement.writeln; }
Give a code snippet in #D 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/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...
#Elixir
Elixir
dog = "Benjamin" doG = "Samba" dOG = "Bernie" IO.puts "The three dogs are named #{dog}, #{doG} and #{dOG}."
Give a code snippet in #Elixir 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, S...
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
#DeviousYarn
DeviousYarn
o:"Hello world!
Give a code snippet in #DeviousYarn 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Burlesque
Burlesque
  blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[ 112  
Give a code snippet in #Burlesque The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#CoffeeScript
CoffeeScript
a = [ 1..10 ] arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length)) harmonic_mean = (a) -> a.length / a.reduce(((s, x) -> s + 1 / x), 0)   A = arithmetic_mean a G = geometic_mean a H = harmonic_mean a   console.log "A = ", A, "...
Give a code snippet in #CoffeeScript Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Sather
Sather
class MAIN is -- we cannot have "functions" (methods) outside classes mult(a, b:FLT):FLT is return a*b; end;   main is #OUT + mult(5.2, 3.4) + "\n"; end; end;
Give a code snippet in #Sather A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Wren
Wren
var main = Fn.new { System.print("Hello from the main function.") }   main.call()
Give a code snippet in #Wren Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: i is 0; begin for i range 1 to 33 do writeln(i lpad 6 <& i radix 8 lpad 6 <& i radix 16 lpad 6); end for; end func;
Give a code snippet in #Seed7 Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard rou...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
First[RealDigits[N[Exp[Pi Sqrt[163]], 200]]] Table[ c = N[Exp[Pi Sqrt[h]], 40]; Log10[1 - FractionalPart[c]] , {h, {19, 43, 67, 163}} ]
Give a code snippet in #Mathematica.2FWolfram_Language Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an int...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Scala
Scala
def ack(m: BigInt, n: BigInt): BigInt = { if (m==0) n+1 else if (n==0) ack(m-1, 1) else ack(m-1, ack(m, n-1)) }
Give a code snippet in #Scala The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Terraform
Terraform
locals { today = timestamp() }   output "iso" { value = formatdate("YYYY-MM-DD", local.today) }   output "us-long" { value = formatdate("EEEE, MMMM D, YYYY", local.today) }
Give a code snippet in #Terraform This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#C.2B.2B
C++
  #include <iostream> #include <algorithm> #include <vector> #include <numeric>   void partitions(std::vector<size_t> args) { size_t sum = std::accumulate(std::begin(args), std::end(args), 0); std::vector<size_t> nums(sum); std::iota(std::begin(nums), std::end(nums), 1); do { size_t total_index = 0; std...
Give a code snippet in #C.2B.2B In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 loop b...
#11l
11l
L(i) (1..9).step(2) print(i)
Give a code snippet in #11l Task Demonstrate a   for-loop   where the step-value is greater than one. 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/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Sidef
Sidef
# set up triangle var rows = 5 var tri = rows.of {|i| (i+1).of { Hash(x => 0, z => 0, v => 0, rhs => nil) } } tri[0][0]{:rhs} = 151 tri[2][0]{:rhs} = 40 tri[4][0]{:x} = 1 tri[4][1]{:v} = 11 tri[4][2]{:x} = 1 tri[4][2]{:z} = 1 tri[4][3]{:v} = 4 tri[4][4]{:z} = 1   # aggregate from bottom to top for row in (tri.len ^.. 1...
Give a code snippet in #Sidef This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#PicoLisp
PicoLisp
(de bubbleSort (Lst) (use Chg (loop (off Chg) (for (L Lst (cdr L) (cdr L)) (when (> (car L) (cadr L)) (xchg L (cdr L)) (on Chg) ) ) (NIL Chg Lst) ) ) )
Give a code snippet in #PicoLisp 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/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....
#XLISP
XLISP
; The computer will evaluate expressions written in -- possibly nested -- parentheses, where the first symbol gives the operation and any subsequent symbols or numbers give the operands.   ; For instance, (+ (+ 2 2) (- 7 5)) evaluates to 6.   ; We define our problem as a function:   (define (try n)   ; We are looking f...
Give a code snippet in #XLISP 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 Comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Haskell
Haskell
import Data.List   main = putStrLn $ showTable True '|' '-' '+' table   table = [["start","stop","increment","Comment","Code","Result/Analysis"] ,["-2","2","1","Normal","[-2,-1..2] or [-2..2]",show [-2,-1..2]] ,["-2","2","0","Zero increment","[-2,-2..2]","Infinite loop of -2 <=> repeat -2"] ,["-...
Give a code snippet in #Haskell Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Fantom
Fantom
  using concurrent using fwt using gfx   const class RotateString : Actor { new make (Label label) : super (ActorPool ()) { Actor.locals["rotate-label"] = label Actor.locals["rotate-string"] = label.text Actor.locals["direction"] = "forward" sendLater (1sec, "update") }   // responsible for call...
Give a code snippet in #Fantom Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task d...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 loop b...
#Haskell
Haskell
import Control.Monad (forM_) main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", ")) putStrLn "who do we appreciate?"
Give a code snippet in #Haskell Task Demonstrate a   for-loop   where the step-value is greater than one. 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/I...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Vlang
Vlang
import os import rand import rand.seed import math   fn main() { rand.seed(seed.time_seed_array(2)) mut n := []int{len: 4} for i in 0.. n.len { n[i] = rand.intn(9) or {0} } println("Your numbers: $n") expr := os.input("Enter RPN: ") if expr.len != 7 { println("invalid. expres...
Give a code snippet in #Vlang The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four di...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Nim
Nim
var a {.noInit.}: array[1_000_000, int]   # For a proc, {.noInit.} means that the result is not initialized. proc p(): array[1000, int] {.noInit.} = for i in 0..999: result[i] = i
Give a code snippet in #Nim
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Kotlin
Kotlin
fun isHumble(i: Int): Boolean { if (i <= 1) return true if (i % 2 == 0) return isHumble(i / 2) if (i % 3 == 0) return isHumble(i / 3) if (i % 5 == 0) return isHumble(i / 5) if (i % 7 == 0) return isHumble(i / 7) return false }   fun main() { val limit: Int = Short.MAX_VALUE.toInt() val h...
Give a code snippet in #Kotlin Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the abov...
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...
#Perl
Perl
sub factorial { my $f = 1; $f *= $_ for 2 .. $_[0]; $f; } sub catalan { my $n = shift; factorial(2*$n) / factorial($n+1) / factorial($n); }   print "$_\t@{[ catalan($_) ]}\n" for 0 .. 20;
Give a code snippet in #Perl 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 !  f...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Icon_and_Unicon
Icon and Unicon
$define EPSILON 1.0e-15   procedure main() local e0 local e := 2.0 local fact := 1 local n := 2   repeat { e0 := e fact *:= n n +:= 1 e +:= (1.0 / fact) if abs(e - e0) < EPSILON then break } write("computed e ", e) write("keyword &e ", &e) end
Give a code snippet in #Icon_and_Unicon Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
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 ...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cit...
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#HicEst
HicEst
REAL :: n = 3, Astat(n), Bdyn(1, 1)   Astat(2) = 2.22222222 WRITE(Messagebox, Name) Astat(2)   ALLOCATE(Bdyn, 2*n, 3*n) Bdyn(n-1, n) = -123 WRITE(Row=27) Bdyn(n-1, n)   ALIAS(Astat, n-1, last2ofAstat, 2) WRITE(ClipBoard) last2ofAstat ! 2.22222222 0
Give a code snippet in #HicEst This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retr...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#Ruby
Ruby
module Camera # define methods here end class MobilePhone # define methods here end class CameraPhone < MobilePhone include Camera # define methods here end
Give a code snippet in #Ruby Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePho...
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
#Haskell
Haskell
module Main (main) where   import System.Posix.IO (stdInput) import System.Posix.Terminal (queryTerminal)   main :: IO () main = do isTTY <- queryTerminal stdInput putStrLn $ if isTTY then "stdin is TTY" else "stdin is not TTY"
Give a code snippet in #Haskell 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/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#AutoHotkey
AutoHotkey
 
Give a code snippet in #AutoHotkey Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Julia
Julia
julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2 2x2 Array{Int64,2}: 22 28 49 64   julia> [1 2 3] * [1,2,3] # product of a row vector by a column vector 1-element Array{Int64,1}: 14  
Give a code snippet in #Julia Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Ksh
Ksh
  #!/bin/ksh   # Symmetric difference - enumerate the items that are in A or B but not both.   # # Variables: # typeset -a A=( John Bob Mary Serena ) typeset -a B=( Jim Mary John Bob )   # # Functions: # # # Function _flattenarr(arr, sep) - flatten arr into string by separator sep # function _flattenarr { typeset _arr...
Give a code snippet in #Ksh Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Emacs_Lisp
Emacs Lisp
(make-temp-file "prefix") ;; => "/tmp/prefix25452LPe"
Give a code snippet in #Emacs_Lisp Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race condi...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#C.23
C#
using System;   namespace FindIntersection { class Vector3D { private double x, y, z;   public Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }   public static Vector3D operator +(Vector3D lhs, Vector3D rhs) { ...
Give a code snippet in #C.23 Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PARI.2FGP
PARI/GP
gnomeSort(v)={ my(i=2,j=3,n=#v,t); while(i<=n, if(v[i-1]>v[i], t=v[i]; v[i]=v[i-1]; v[i--]=t; if(i==1, i=j; j++); , i=j; j++ ) ); v };
Give a code snippet in #PARI.2FGP Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Ioke
Ioke
for( x <- 1..20, y <- x..20, z <- y..20, x * x + y * y == z * z, [x, y, z] )
Give a code snippet in #Ioke A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#JavaScript
JavaScript
function mandelIter(cx, cy, maxIter) { var x = 0.0; var y = 0.0; var xx = 0; var yy = 0; var xy = 0;   var i = maxIter; while (i-- && xx + yy <= 4) { xy = x * y; xx = x * x; yy = y * y; x = xx - yy + cx; y = xy + xy + cy; } return maxIter - i; }   function mandelbrot(canvas, xmin, ...
Give a code snippet in #JavaScript Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program pancakeSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a fi...
Give a code snippet in #ARM_Assembly Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#Nim
Nim
import strformat   const Eps = 0.001 Eps2 = Eps * Eps   type Point = tuple[x, y: float] Triangle = object p1, p2, p3: Point     func initTriangle(p1, p2, p3: Point): Triangle = Triangle(p1: p1, p2: p2, p3: p3)   func side(p1, p2, p: Point): float = (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - ...
Give a code snippet in #Nim Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the al...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#11l
11l
F chowla(n) V sum = 0 V i = 2 L i * i <= n I n % i == 0 sum += i V j = n I/ i I i != j sum += j i++ R sum   L(n) 1..37 print(‘chowla(’n‘) = ’chowla(n))   V count = 0 V power = 100 L(n) 2..10'000'000 I chowla(n) == 0 count++ I n % power == 0 ...
Give a code snippet in #11l Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Standard_ML
Standard ML
fun hanoi(0, a, b, c) = [] | hanoi(n, a, b, c) = hanoi(n-1, a, c, b) @ [(a,b)] @ hanoi(n-1, c, b, a);
Give a code snippet in #Standard_ML Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#BaCon
BaCon
  DATA "January", "February", "March", "April", "May", "June", "July" DATA "August", "September", "October", "November", "December"   LOCAL dat$[11] FOR i = 0 TO 11 READ dat$[i] PRINT dat$[i] NEXT  
Give a code snippet in #BaCon This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retri...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Groovy
Groovy
  class Runge_Kutta{ static void main(String[] args){ def y=1.0,t=0.0,counter=0; def dy1,dy2,dy3,dy4; def real; while(t<=10) {if(counter%10==0) {real=(t*t+4)*(t*t+4)/16; println("y("+t+")="+ y+ " Error:"+ (real-y)); }   dy1=dy(dery(y,t)); dy2=dy(dery(y+dy1/2,t+0.05)); dy3=dy(dery(y+dy2/2,t+0.05)); dy4=dy(dery(y+dy3,t+0...
Give a code snippet in #Groovy Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This e...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#ERRE
ERRE
PROGRAM QUADRATIC   PROCEDURE SOLVE_QUADRATIC D=B*B-4*A*C IF ABS(D)<1D-6 THEN D=0 END IF CASE SGN(D) OF 0-> PRINT("the single root is ";-B/2/A) END -> 1-> F=(1+SQR(1-4*A*C/(B*B)))/2 PRINT("the real roots are ";-F*B/A;"and ";-C/B/F) END -> -1-> PRINT("the complex roo...
Give a code snippet in #ERRE This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your p...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Picat
Picat
go => S1 = "The quick brown fox jumps over the lazy dog", S2 = "The slow brown fox jumps over the lazy dog", println([S1, is_pangram(S1)]), println([S2, is_pangram(S2)]), nl, println("With missing chars:"), println([S1, is_pangram2(S1)]), println([S2, is_pangram2(S2)]), nl.   % Check if S ...
Give a code snippet in #Picat Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Wri...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#R
R
stringval <- readline("String: ") intval <- as.integer(readline("Integer: "))
Give a code snippet in #R User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Icon
Icon
# # The Rosetta Code Tiny-Language Parser, in Icon. # # This implementation is based closely on the pseudocode and the C # reference implementation. #   # ximage from the IPL is useful for debugging. Use "xdump(x)" to # pretty-print x. #link ximage   record token_record (line_no, column_no, tok, tokval) record token_ge...
Give a code snippet in #Icon A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened forma...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#uBasic.2F4tH
uBasic/4tH
s := "[" : Push 5, 4, 3   Do While Used () y = Set (x, Pop ()) + 1 s = Join (s, Str (Set (z, y * 2)), ", " ) Loop   Print Show (Set (s, Join (Clip (s, 2), "]")))  
Give a code snippet in #uBasic.2F4tH A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathemati...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinformatics/base count Count occurren...
#Haskell
Haskell
import System.Random (getStdRandom, randomR) import Control.Monad (forever)   answers :: [String] answers = [ "It is certain" , "It is decidedly so" , "Without a doubt" , "Yes, definitely" , "You may rely on it" , "As I see it, yes" , "Most likely" , "Outlook good" , "Signs point t...
Give a code snippet in #Haskell Task Create Magic 8-Ball. See details at:   Magic 8-Ball. 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 before E except after C Bioinfor...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#ATS
ATS
(* Find Knight’s Tours.   Using Warnsdorff’s heuristic, find multiple solutions. Optionally accept only closed tours.   Compile with: patscc -O3 -DATS_MEMALLOC_GCBDW -o knights_tour knights_tour.dats -lgc   Usage: ./knights_tour [START_POSITION [MAX_TOURS [closed]]] Examples: ./knights_tour ...
Give a code snippet in #ATS Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; t...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#JavaScript
JavaScript
<html><head><title>Table maker</title><script type="application/javascript">   // normally, don't do this: at least name it something other than "a" Node.prototype.a = function (e) { this.appendChild(e); return this }   function ce(tag, txt) { var x = document.createElement(tag); x.textContent = (txt === undefined) ?...
Give a code snippet in #JavaScript Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is fille...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT,{} s1=* DATA "string" s2=* DATA + "double" quotes s3=* DATA + 'single' quotes s4=* DATA + "double" + 'single' quotes show=JOIN(s1," ",s2,s3,s4) show=JOIN(show) PRINT show  
Give a code snippet in #TUSCRIPT Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Modula-2
Modula-2
MODULE Erato; FROM InOut IMPORT WriteCard, WriteLn; FROM MathLib IMPORT sqrt;   CONST Max = 100;   VAR prime: ARRAY [2..Max] OF BOOLEAN; i: CARDINAL;   PROCEDURE Sieve; VAR i, j, sqmax: CARDINAL; BEGIN sqmax := TRUNC(sqrt(FLOAT(Max)));   FOR i := 2 TO Max DO prime[i] := TRUE; END; FOR i := 2 TO sqm...
Give a code snippet in #Modula-2 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/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#PHL
PHL
var numbers = 1..10;   numbers each # (number) [ printf("%i\n", number); ];
Give a code snippet in #PHL Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/D...
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.
#Haskell
Haskell
import Control.Concurrent (threadDelay) import Control.Monad (when) import System.IO (hFlush, stdout) import System.Posix   -- If the file descriptor is associated with a terminal, then flush its input, -- otherwise do nothing. termFlush :: Fd -> IO () termFlush fd = do isTerm <- queryTerminal fd when isTerm $ disc...
Give a code snippet in #Haskell 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/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Oforth
Oforth
6 -> a : Push 6 on the stack and set the top of the stack as value of local variable a (top of the stack is consumed) 6 := a : Push 6 on the stack and set the top of the satck as value of attribute a (top of the stack is consumed). raining ifTrue: [ true ->needumbrella ]
Give a code snippet in #Oforth Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the st...
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ using read only variablles Print "Platform: ";Platform$ Print "Computer Os: "; Os$ Print "Type of OS: ";OsBit;" bit" Print "Computer Name:"; Computer$ Print "User Name: "; User.Name$ \\ using WScript.Shell Declare objShell "WScript.Shell" With...
Give a code snippet in #M2000_Interpreter 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/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Logo
Logo
to small? :list output or [empty? :list] [empty? bf :list] end to every.other :list if small? :list [output :list] output fput first :list every.other bf bf :list end to wordtolist :word output map.se [?] :word end   to double.digit :digit output item :digit {0 2 4 6 8 1 3 5 7 9}@0  ; output ifelse :digit < ...
Give a code snippet in #Logo The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Elena
Elena
  c:\Alex\ELENA\bin>elt ELENA command line VM terminal 5.1.13 (C)2011-2020 by Alexei Rakov ELENA VM 5.1.17 (C)2005-2020 by Alex Rakov Initializing... Done...   >f(s1,s2,sep){^ s1 + sep + sep + s2 };   >f("Rosetta","Code",":") Rosetta::Code >  
Give a code snippet in #Elena Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Sidef
Sidef
func point (index) { var ix = (index % 32); if (ix & 1) { "#{point((ix + 1) & 28)} by #{point(((2 - (ix & 2)) * 4) + ix & 24)}" } elsif (ix & 2) { "#{point((ix + 2) & 24)}-#{point((ix | 4) & 28)}" } elsif (ix & 4) { "#{point((ix + 8) & 16)}#{point((ix | 8) & 24)}" } else { <north east s...
Give a code snippet in #Sidef There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and di...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Maple
Maple
#Displays terms in Farey_sequence of order n farey_sequence := proc(n) local a,b,c,d,k; a,b,c,d := 0,1,1,n; printf("%d/%d", a,b); while c <= n do k := iquo(n+b,d); a,b,c,d := c,d,c*k-a,d*k-b; printf(", %d/%d", a,b) end do; printf("\n"); end proc:   #Returns the length of a Farey sequence farey_l...
Give a code snippet in #Maple The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Julia
Julia
using Printf   function multifact(n::Integer, k::Integer) n > 0 && k > 0 || throw(DomainError()) k > 1 || factorial(n) return prod(n:-k:2) end   const khi = 5 const nhi = 10 println("Showing multifactorial for n in [1, $nhi] and k in [1, $khi].") for k = 1:khi a = multifact.(1:nhi, k) lab = "n" * "!...
Give a code snippet in #Julia The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Julia
Julia
using Dates   function main() dtstr = "March 7 2009 7:30pm" # Base.Dates doesn't handle "EST" cleandtstr = replace(dtstr, r"(am|pm)"i, "") dtformat = dateformat"U dd yyyy HH:MM" dtime = parse(DateTime, cleandtstr, dtformat) + Hour(12 * contains(dtstr, r"pm"i)) # add 12h for the pm println(Da...
Give a code snippet in #Julia Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Wren
Wren
import "/matrix" for Matrix import "/fmt" for Fmt   var m = Matrix.new([ [ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12] ])   System.print("Original:\n") Fmt.mprint(m, 2, 0) System.print("\nTransposed:\n") Fmt.mprint(m.transpose, 2, 0)
Give a code snippet in #Wren Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Scala
Scala
import java.awt._ import java.awt.geom.Path2D import java.util   import javax.swing._ import javax.swing.event.{ChangeEvent, ChangeListener}   object SuperEllipse extends App {   SwingUtilities.invokeLater(() => { new JFrame("Super Ellipse") {   class SuperEllipse extends JPanel with ChangeListener { ...
Give a code snippet in #Scala A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Delphi
Delphi
  program Long_year;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   function p(const Year: Integer): Integer; begin Result := (Year + (Year div 4) - (Year div 100) + (Year div 400)) mod 7; end;   function IsLongYear(const Year: Integer): Boolean; begin Result := (p(Year) = 4) or (p(Year - 1) = 3); en...
Give a code snippet in #Delphi Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Racket
Racket
#lang racket/base   (require racket/system (only-in racket/port with-output-to-string) tests/eli-tester)   (test  ;; system runs command and outputs to current output port (which is stdout unless we catch it) (system "ls /etc/motd") => #t  ;; it throws an error on non-zero exit code (so I need to cat...
Give a code snippet in #Racket Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code