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/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program variable64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly 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/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#APL
APL
((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳500
Give a code snippet in #APL Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:  ...
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...
#Vala
Vala
  double arithmetic(int[] list){ double mean; double sum = 0; foreach(int number in list){ sum += number; } // foreach   mean = sum / list.length;   return mean; } // end arithmetic mean   double geometric(int[] list){ double mean; double product = 1; foreach(int number in list){ product *= number; } // f...
Give a code snippet in #Vala 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},\ldot...
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...
#Icon_and_Unicon
Icon and Unicon
  |(x := seq(), x^2 > 3, x*2)  
Give a code snippet in #Icon_and_Unicon 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 lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Smalltalk
Smalltalk
isEmirp := [:p | |e| (e := p asString reversed asNumber) isPrime and:[ e ~= p ] ].
Give a code snippet in #Smalltalk An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000t...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#REXX
REXX
step_up: do while \step(); call step_up end return
Give a code snippet in #REXX From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function dete...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "os" "regexp" "strings" )   type header struct { start, end int lang string }   type data struct { count int names *[]string }   func newData(count int, name string) *data { return &data{count, &[]string{name}} }   var bma...
Give a code snippet in #Go Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display ...
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#AutoHotkey
AutoHotkey
Gui, font, S16 Gui, add, Radio, vRadioC , Cake Gui, add, Radio, vRadioE x+0 Checked, Easy Gui, add, Radio, vRadioH x+0, Hard Gui, add, text, xs vT, Total : 00 Gui, add, text, xs vComputer, Computer Dealt 00 Gui, add, text, xs Section, Player 1 loop, 3 Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index Gui, ad...
Give a code snippet in #AutoHotkey 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#Go
Go
package main   import "fmt"   func sieve(limit uint64) []bool { limit++ // True denotes composite, false denotes prime. c := make([]bool, limit) // all false by default c[0] = true c[1] = true // apart from 2 all even numbers are of course composite for i := uint64(4); i < limit; i += 2 { ...
Give a code snippet in #Go Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't  ...
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...
#LFE
LFE
  > (os:timestamp) #(1423 786308 145798)  
Give a code snippet in #LFE 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/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...
#Swift
Swift
func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]? { var width = 0 var height = 0 var pixelValues: [UInt8]?   if let imageRef = imageRef { width = imageRef.width height = imageRef.height let bitsPerComponent = imageRef.bitsPerComponent let bytesPerRow = imageRef...
Give a code snippet in #Swift 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 ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Haskell
Haskell
isInteger s = case reads s :: [(Integer, String)] of [(_, "")] -> True _ -> False   isDouble s = case reads s :: [(Double, String)] of [(_, "")] -> True _ -> False   isNumeric :: String -> Bool isNumeric s = isInteger s || isDouble s
Give a code snippet in #Haskell Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Klingphix
Klingphix
include ..\Utilitys.tlhy     :fib %f !f  %fr [ %n !n $n 2 < ( [$n] [$n 1 - $fr eval $n 2 - $fr eval +] ) if ] !fr   $f 0 < ( ["Error: number is negative"] [$f true $fr if] ) if ;     25 fib ? msec ? "End " input
Give a code snippet in #Klingphix While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing un...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function checkNoSpaces(s As String) As Boolean For i As UInteger = 0 To Len(s) - 1 If s[i] = 32 OrElse s[i] = 9 Then Return False '' check for spaces or tabs Next Return True End Function   Open "input.fasta" For Input As # 1   Dim As String ln, seq Dim first As Boolean = True   While Not...
Give a code snippet in #FreeBASIC In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >R...
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....
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Set Fast ! Form 80, 40 Refresh Function Smith(max=10000) { Function SumDigit(a$) { def long sum For i=1 to len(a$) {sum+=val(mid$(a$,i, 1)) } =sum } x=max \\...
Give a code snippet in #M2000_Interpreter 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Ruby_with_RSpec
Ruby with RSpec
  require 'fizzbuzz'   describe 'FizzBuzz' do context 'knows that a number is divisible by' do it '3' do expect(is_divisible_by_three?(3)).to be_true end it '5' do expect(is_divisible_by_five?(5)).to be_true end it '15' do expect(is_divisible_by_fifteen?(15)).to be_true end ...
Give a code snippet in #Ruby_with_RSpec Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print ...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Scala
Scala
import io.Source.fromFile   def letterFrequencies(filename: String) = fromFile(filename).mkString groupBy (c => c) mapValues (_.length)
Give a code snippet in #Scala Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (ass...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Picat
Picat
import util.   go => S = "rosetta code phrase reversal", println(S), println(reverse(S)), println([reverse(W) : W in S.split()].join(' ')), println(reverse(S.split()).join(' ')), nl.
Give a code snippet in #Picat Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of eac...
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
#VBScript
VBScript
  'YYYY-MM-DD format WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2)   'Weekday_Name, Month_Name DD, YYYY format WScript.StdOut.WriteLine FormatDateTime(Now,1)  
Give a code snippet in #VBScript 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/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Picat
Picat
go =>  % _ # # # _ # # _ # _ # _ # _ # _ _ # _ _ S = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0], println(init=S), run_ca(S), nl,   println("Some random inits:"), _ = random2(), foreach(N in [5,10,20,50]) S2 = [random() mod 2 : _I in 1..N], run_ca(S2), nl end.   % % Run a CA a...
Give a code snippet in #Picat Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current...
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
#Ada
Ada
with POSIX.Unsafe_Process_Primitives;   procedure Execute_A_System_Command is Arguments : POSIX.POSIX_String_List; begin POSIX.Append (Arguments, "ls"); POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments); end Execute_A_System_Command;
Give a code snippet in #Ada 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/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Logtalk
Logtalk
  :- object(iban).   :- info([ version is 0.1, author is 'Paulo Moura', date is 2015/10/11, comment is 'IBAN validation example using DCG rules.' ]).   :- public(valid/1).   valid(IBAN) :- phrase(iban, IBAN), !.   iban --> country_code(Code), check_digits(Check), bban(BBAN), {(BBAN*1000000 + Code*100...
Give a code snippet in #Logtalk This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IB...
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...
#ObjectIcon
ObjectIcon
# # Find Knight’s Tours. # # Using Warnsdorff’s heuristic, find multiple solutions. # # Based on my ATS/Postiats program. # # The main difference from the ATS is this program uses a # co-expression pair to make a generator of solutions, whereas the ATS # simply prints solutions where they are found. # # Usage: ./knigh...
Give a code snippet in #ObjectIcon 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 "clo...
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...
#JavaScript
JavaScript
function hailstone (n) { var seq = [n]; while (n > 1) { n = n % 2 ? 3 * n + 1 : n / 2; seq.push(n); } return seq; }   // task 2: verify the sequence for n = 27 var h = hailstone(27), hLen = h.length; print("sequence 27 is (" + h.slice(0, 4).join(", ") + " ... " + h.slice(hLen - 4, hL...
Give a code snippet in #JavaScript 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/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <string>   const char *text = { "In olden times when wishing still helped one, there lived a king " "whose daughters were all beautiful, but the youngest was so beautiful " "that the sun itself, which has seen so much, was astonished whenever " "it shone i...
Give a code snippet in #C.2B.2B Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#Comal
Comal
  1000 PRINT "F(X)";" FROM";" TO";" L-Rect";" M-Rect";" R-Rect ";" Trapez";" Simpson" 1010 fromval:=0 1020 toval:=1 1030 PRINT "X^3 "; 1040 PRINT USING "#####": fromval; 1050 PRINT USING "#####": toval; 1060 PRINT USING "###.#########": numint(f1, "L", fr...
Give a code snippet in #Comal Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Wren
Wren
import "/queue" for Queue   var q = Queue.new() var item = q.pop() if (item == null) { System.print("ERROR: attempted to pop from an empty queue") } else { System.print("'%(item)' was popped") }
Give a code snippet in #Wren Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the or...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Delphi
Delphi
program OneInstance;   {$APPTYPE CONSOLE}   uses SysUtils, Windows;   var FMutex: THandle; begin FMutex := CreateMutex(nil, True, 'OneInstanceMutex'); if FMutex = 0 then RaiseLastOSError else begin try if GetLastError = ERROR_ALREADY_EXISTS then Writeln('Program already running. Closing...
Give a code snippet in #Delphi This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Julia
Julia
import Base.show   @enum Move Left=1 Stay Right   mutable struct MachineState state::String tape::Dict{Int, String} headpos::Int end   struct Rule instate::String s1::String s2::String move::Move outstate::String end   struct Program title::String initial::String final::Strin...
Give a code snippet in #Julia One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Pascal
Pascal
Program WriteNumbers;   const x: array [1..4] of double = (1, 2, 3, 1e11); xprecision = 3; yprecision = 5; baseDigits = 7;   var i: integer; filename: text;   begin assign (filename, 'filename'); rewrite (filename); for i := 1 to 4 do writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseD...
Give a code snippet in #Pascal Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2,...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Scheme
Scheme
(define *max-doors* 100)   (define (show-doors doors) (let door ((i 0) (l (vector-length doors))) (cond ((= i l) (newline)) (else (printf "~nDoor ~a is ~a" (+ i 1) (if (vector-ref doors i) "open" "closed")) (door (+ ...
Give a code snippet in #Scheme There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#PowerShell
PowerShell
$Env:COMPUTERNAME
Give a code snippet in #PowerShell Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Tcl
Tcl
namespace import tcl::mathop::*   proc ast str { # produce abstract syntax tree for an expression regsub -all {[-+*/()]} $str { & } str ;# "tokenizer" s $str } proc s {args} { # parse "(a + b) * c + d" to "+ [* [+ a b] c] d" if {[llength $args] == 1} {set args [lindex $args 0]} if [regexp {[()]}...
Give a code snippet in #Tcl Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a simi...
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,...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: charArray is array [char] string; # Define an array type for arrays with char index. const type: twoDim is array array char; # Define an array type for a two dimensional array.   const proc: main is func local var array integer: array1 is 10 times 0; # A...
Give a code snippet in #Seed7 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/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#Perl
Perl
use feature 'say';   sub leftrect { my($func, $a, $b, $n) = @_; my $h = ($b - $a) / $n; my $sum = 0; for ($_ = $a; $_ < $b; $_ += $h) { $sum += $func->($_) } $h * $sum }   sub rightrect { my($func, $a, $b, $n) = @_; my $h = ($b - $a) / $n; my $sum = 0; for ($_ = $a+$h; $_ < $b+$h; $_...
Give a code snippet in #Perl Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to mak...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#EGL
EGL
program MazeGen   // First and last columns/rows are "dead" cells. Makes generating // a maze with border walls much easier. Therefore, a visible // 20x20 maze has a maze size of 22. mazeSize int = 22;   south boolean[][]; west boolean[][]; visited boolean[][];   function main() ...
Give a code snippet in #EGL This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#FreeBASIC
FreeBASIC
Dim As Integer size = 12345 Dim As Integer mem = size-1 Print size; " bytes of heap allocated at " ; mem Clear (mem, , 10) Print size; " bytes of heap allocated at " ; mem
Give a code snippet in #FreeBASIC Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nim
Nim
import strutils   var str = "little" echo "Mary had a $# lamb".format(str) echo "Mary had a $# lamb" % [str] # Note: doesn't need an array for a single substitution, but uses an array for multiple substitutions.
Give a code snippet in #Nim Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Processing
Processing
PVector v1 = new PVector(5, 7); PVector v2 = new PVector(2, 3);   println(v1.x, v1.y, v1.mag(), v1.heading(),'\n');   // static methods println(PVector.add(v1, v2)); println(PVector.sub(v1, v2)); println(PVector.mult(v1, 11)); println(PVector.div(v1, 2), '\n');   // object methods println(v1.sub(v1)); println(v1.add(v2...
Give a code snippet in #Processing Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and val...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Phix
Phix
with javascript_semantics constant infinity = 1e300*1e300 ? infinity
Give a code snippet in #Phix Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Nemerle
Nemerle
using System; using System.Console;   namespace NestedExceptions { public class U0 : Exception { public this() {base()} }   public class U1 : Exception { public this() {base()} }   module NestedExceptions { Foo () : void { mutable call = 0;   ...
Give a code snippet in #Nemerle Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arr...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Go
Go
package main   import "fmt"   const ( // state: m = iota // missing: all elements missing so far c // continuous: all elements included so far are continuous cm // one or more continuous followed by one or more missing cmc // non-continuous subsequence )   func ncs(s []int) [...
Give a code snippet in #Go Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and l...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Scheme
Scheme
(let ((x 42)) (assert (and (integer? x) (= x 42))))
Give a code snippet in #Scheme Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π ...
#Rust
Rust
/// calculate pi with algebraic/geometric mean pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n {   let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; ...
Give a code snippet in #Rust Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#AutoHotkey
AutoHotkey
Bucket := [], Buckets := 10, Originaltotal = 0 loop, %Buckets% { Random, rnd, 0,50 Bucket[A_Index] := rnd, Originaltotal += rnd }   loop 100 { total := 0 Randomize(B1, B2, Buckets) temp := (Bucket[B1] + Bucket[B2]) /2 Bucket[B1] := floor(temp), Bucket[B2] := Ceil(temp) ; values closer to equal   Randomize(B1, B...
Give a code snippet in #AutoHotkey Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of a...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function TimeToDegrees(time As TimeSpan) As Double Return 360 * time.Hours / 24.0 + 360 * time.Minutes / (24 * 60.0) + 360 * time.Seconds / (24 * 3600.0) End Function   Function DegreesToTime(angle As Double) As TimeSpan Return New TimeSpan((24 * 60 * 60 * angle \ 360) \ 360...
Give a code snippet in #Visual_Basic_.NET Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and usin...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#REXX
REXX
/*REXX program determines the LCSUBSTR (Longest Common Substring) via a function. */ parse arg a b . /*obtain optional arguments from the CL*/ if a=='' then a= "thisisatest" /*Not specified? Then use the default.*/ if b=='' then b= "testing123testing" ...
Give a code snippet in #REXX Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecuti...
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...
#Nemerle
Nemerle
System.Console.Write(System.DateTime.Now);
Give a code snippet in #Nemerle 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 ...
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,...
#Transd
Transd
module1 : { v1: Vector<Int>(), v2: Vector<String>(), v3: Vector<Int>([1,2,3,4]), v4: Vector<String>(["one","two","three"]), // the type of vector values can automaticaly deduced v5: [1.0, 2.5, 8.6], // Vector<Double> v6: ["one","two","three"] // Vector<String> }
Give a code snippet in #Transd 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/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Perl
Perl
while (<>) { chomp; my $r = reverse; $seen{$r}++ and $c++ < 5 and print "$_ $r\n" or $seen{$_}++; }   print "$c\n"
Give a code snippet in #Perl A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total...
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....
#Factor
Factor
USING: formatting grouping io kernel math.primes.factors math.ranges math.text.utils sequences sequences.deep ;   : (smith?) ( n factors -- ? ) [ 1 digit-groups sum ] [ [ 1 digit-groups ] map flatten sum = ] bi* ; inline   : smith? ( n -- ? ) dup factors dup length 1 = [ 2drop f ] [ (smith?) ] if ;   10,000...
Give a code snippet in #Factor 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nanoquery
Nanoquery
def logic(a, b) println "a and b: " + (a && b) println "a or b: " + (a && b) println "not a: " + !a end
Give a code snippet in #Nanoquery Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Tcl
Tcl
proc temps {k} { set c [expr {$k - 273.15}] set r [expr {$k / 5.0 * 9.0}] set f [expr {$r - 459.67}] list $k $c $f $r }
Give a code snippet in #Tcl There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ke...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Aime
Aime
void read_line(text &line, text path, integer n) { file f;   f.affix(path);   call_n(n, f_slip, f);   f.line(line); }     integer main(void) { if (1 < argc()) { text line;   read_line(line, argv(1), 6);   o_("7th line is:\n", line, "\n"); }   0; }
Give a code snippet in #Aime Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#6502_Assembly
6502 Assembly
sta $1900 stx $1901 sty $1902
Give a code snippet in #6502_Assembly Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Ope...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Java
Java
public class Prob{ static long TRIALS= 1000000;   private static class Expv{ public String name; public int probcount; public double expect; public double mapping;   public Expv(String name, int probcount, double expect, double mapping){ this.name= name; this.probcount= probcount; this.expect= expe...
Give a code snippet in #Java Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floa...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Asymptote
Asymptote
int i = 0; do { ++i; write(" ", i, suffix=none); } while (i % 6 != 0);
Give a code snippet in #Asymptote Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loo...
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 ...
#Draco
Draco
/* Bubble sort an array of integers */ proc nonrec bubblesort([*] int a) void: bool sorted; int i, temp; sorted := false; while not sorted do sorted := true; for i from 1 upto dim(a,1)-1 do if a[i-1] > a[i] then sorted := false; temp := a[i-1];...
Give a code snippet in #Draco 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/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...
#Sidef
Sidef
func is_k_almost_prime(n, k) { for (var (p, f) = (2, 0); (f < k) && (p*p <= n); ++p) { (n /= p; ++f) while (p `divides` n) } n > 1 ? (f.inc == k) : (f == k) }   { |k| var x = 10 say gather { { |i| if (is_k_almost_prime(i, k)) { take(i) --x ...
Give a code snippet in #Sidef 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,   wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Phix
Phix
type mi(object m) return sequence(m) and length(m)=2 and integer(m[1]) and integer(m[2]) end type type mii(object m) return mi(m) or atom(m) end type function mi_one(mii a) if atom(a) then a=1 else a = {1,a[2]} end if return a end function function mi_add(mii a, mii b) if atom(a) then ...
Give a code snippet in #Phix Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Delphi
Delphi
  program FractranTest;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.RegularExpressions;   type TFractan = class private limit: Integer; num, den: TArray<Integer>; procedure compile(prog: string); procedure exec(val: Integer); function step(val: Integer): integer; procedure dump()...
Give a code snippet in #Delphi FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initi...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Factor
Factor
USING: kernel ; 42 assert=
Give a code snippet in #Factor Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Emacs_Lisp
Emacs Lisp
ELISP> (directory-files-recursively "/tmp/el" "\\.el$") ("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el")
Give a code snippet in #Emacs_Lisp Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#EGL
EGL
handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}   ui Div { };   const KEY_N int = 78; const KEY_Y int = 89;   function start() document.onKeyDown = d_onKeyDown; end   function d_onKeyDown(e Event in)   case (e.ch) when (KEY_N) ui.inne...
Give a code snippet in #EGL Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#BASIC
BASIC
PRINT "Given a jumbled list of the numbers 1 to 9," PRINT "you must select how many digits from the left to reverse." PRINT "Your goal is to get the digits in order with 1 on the left and 9 on the right."   RANDOMIZE TIMER   DIM nums(1 TO 9) AS INTEGER DIM L0 AS INTEGER, n AS INTEGER, flp AS INTEGER, tries AS INTEGER, ...
Give a code snippet in #BASIC Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#M4
M4
define(`notfound',`-1')dnl define(`midsearch',`ifelse(defn($1[$4]),$2,$4, `ifelse(eval(defn($1[$4])>$2),1,`binarysearch($1,$2,$3,decr($4))',`binarysearch($1,$2,incr($4),$5)')')')dnl define(`binarysearch',`ifelse(eval($4<$3),1,notfound,`midsearch($1,$2,$3,eval(($3+$4)/2),$4)')')dnl dnl define(`setrange',`ifelse(`$3',`',...
Give a code snippet in #M4 A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret numb...
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...
#BASIC256
BASIC256
  function twoCircles(x1, y1, x2, y2, radio) if x1 = x2 and y1 = y2 then #Si los puntos coinciden if radio = 0 then #a no ser que radio=0 print "Los puntos son los mismos " return "" else print "Hay cualquier número de círculos a través de un solo punto ("; x1; ", "; y1; ") de radio "; int(radio) ...
Give a code snippet in #BASIC256 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...
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...
#Kotlin
Kotlin
fun Int.k_prime(x: Int): Boolean { var n = x var f = 0 var p = 2 while (f < this && p * p <= n) { while (0 == n % p) { n /= p; f++ } p++ } return f + (if (n > 1) 1 else 0) == this }   fun Int.primes(n : Int) : List<Int> { var i = 2 var list = mutableListOf<Int>() whil...
Give a code snippet in #Kotlin 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,   w...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Asymptote
Asymptote
string A, B, t = '\t';   void comp(string A, string B) { if (length(A) >= length(B)) { write(A+t, length(A)); write(B+t, length(B)); } else { write(B+t, length(B)); write(A+t, length(A)); } }   comp("abcd", "123456789");
Give a code snippet in #Asymptote Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Java
Java
import java.math.BigInteger; import java.util.PriorityQueue;   final class Hamming { private static BigInteger THREE = BigInteger.valueOf(3); private static BigInteger FIVE = BigInteger.valueOf(5);   private static void updateFrontier(BigInteger x, PriorityQueue<BigInt...
Give a code snippet in #Java 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 numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#C.2B.2B
C++
#include <string> #include <numeric>   int main() { std::string lower(26,' ');   std::iota(lower.begin(), lower.end(), 'a'); }
Give a code snippet in #C.2B.2B Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use ...
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 ...
#Chapel
Chapel
proc is_prime(n) { if n == 2 then return true; if n <= 1 || n % 2 == 0 then return false; for i in 3..floor(sqrt(n)):int by 2 do if n % i == 0 then return false; return true; }
Give a code snippet in #Chapel 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 loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Burlesque
Burlesque
  1 22r@{?s0.5?+av?+}[m  
Give a code snippet in #Burlesque Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A0...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#jq
jq
# In case your jq does not have "until" defined: def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # Zeller's Congruence from [[Day_of_the_week#jq]]   # Use Zeller's Congruence to determine the day of the week, given # year, month and day as integers in the conventional way. # ...
Give a code snippet in #jq Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-0...
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 ...
#DWScript
DWScript
function fib(N : Integer) : Integer; begin if N < 2 then Result := 1 else Result := fib(N-2) + fib(N-1); End;
Give a code snippet in #DWScript 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Bracmat
Bracmat
(lc= counts c . fil$(!arg,r) {open file for reading} & 0:?counts & whl ' ( fil$:?c {read a byte} & ( !c:(~<A:~>Z|~<a:~>z) | 0 ) + !counts  : ?counts {simply add any fou...
Give a code snippet in #Bracmat Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (a...
christopher/rosetta-code
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Sidef
Sidef
func calkin_wilf(n) is cached { return 1 if (n == 1) 1/(2*floor(__FUNC__(n-1)) + 1 - __FUNC__(n-1)) }   func r2cw(r) {   var cfrac = r.as_cfrac cfrac.len.is_odd || return nil   Num(cfrac.flip.map_kv {|k,v| (k.is_odd ? '0' : '1') * v }.join, 2) }   with (20) {|n| say "First #{n} terms of the Calk...
Give a code snippet in #Sidef The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floatin...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Raku
Raku
use NativeCall;   class Window is repr('CPointer') {} class Monitor is repr('CPointer') {}   # GLFW   constant $lib = ('glfw', v3);   sub glfwInit(--> int32) is native($lib) {*} sub glfwCreateWindow(int32, int32, Str, Monitor, Window --> Window) is native($lib) {*} sub glfwTerminate() is native($lib) {*} sub glfwMakeCo...
Give a code snippet in #Raku Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
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...
#Perl
Perl
use 5.10.0; use List::Util 'max';   my @sum; while (<>) { my @x = split; @sum = ($x[0] + $sum[0], map($x[$_] + max(@sum[$_-1, $_]), 1 .. @x-2), $x[-1] + $sum[-1]); }   say max(@sum);
Give a code snippet in #Perl 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 w...
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
#gecho
gecho
'Hello, <> 'World! print
Give a code snippet in #gecho 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/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Ruby
Ruby
include Math DtoR = PI/180   print 'Enter latitude: ' lat = Float( gets ) print 'Enter longitude: ' lng = Float( gets ) print 'Enter legal meridian: ' ref = Float( gets ) puts   slat = sin( lat * DtoR )   puts " sine of latitude:  %.3f"% slat puts " diff longitude:  %.3f"% (lng-ref) puts puts 'Hour, sun hour an...
Give a code snippet in #Ruby Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island,...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Sidef
Sidef
var ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']; say ary.uniq.dump; say ary.last_uniq.dump;
Give a code snippet in #Sidef 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/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Quackery
Quackery
[ witheach peek ] is {peek} ( { p --> x )   [ dip dup witheach [ peek dup ] drop ] is depack ( { p --> * )   [ reverse witheach [ dip swap poke ] ] is repack ( * p --> { )   [ dup dip [ rot dip [ depack drop ] ] ...
Give a code snippet in #Quackery Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those n...
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.
#Arturo
Arturo
longYear?: function [year][ date: to :date .format: "dd/MM/yyyy" ~"01/01/|year|"   or? date\Day = "Thursday" and? leap? year date\Day = "Wednesday" ]   print "Years with 53 weeks between 2000 and 2100:" print select 2000..2100 => longYear?
Give a code snippet in #Arturo 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/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#C.23
C#
using System; using static System.Console; using BI = System.Numerics.BigInteger;   class Program {   static decimal mx = 1E28M, hm = 1E14M, a;   // allows for 56 digit representation, using 28 decimal digits from each decimal struct bi { public decimal hi, lo; }   // sets up for squaring process static bi se...
Give a code snippet in #C.23 Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Modula-3
Modula-3
PROCEDURE Multiply(a, b: INTEGER): INTEGER = BEGIN RETURN a * b; END Multiply;
Give a code snippet in #Modula-3 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 distra...
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 ...
#Jinja
Jinja
  print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %} {{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %} {%- endfor %}""").render())  
Give a code snippet in #Jinja 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#Julia
Julia
  const k8 = [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3] const k7 = [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9] const k6 = [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11] const k5 = [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3] const k4 = [ 6...
Give a code snippet in #Julia GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р an...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#App_Inventor
App Inventor
a: to :complex [1 1] b: to :complex @[pi 1.2]   print ["a:" a] print ["b:" b]   print ["a + b:" a + b] print ["a * b:" a * b] print ["1 / a:" 1 / a] print ["neg a:" neg a] print ["conj a:" conj a]
Give a code snippet in #App_Inventor A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\di...
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...
#VBScript
VBScript
Dim s As String   ' Assign empty string: s = "" ' or s = String.Empty   ' Check for empty string only (false if s is null): If s IsNot Nothing AndAlso s.Length = 0 Then End If   ' Check for null or empty (more idiomatic in .NET): If String.IsNullOrEmpty(s) Then End If
Give a code snippet in #VBScript 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#REXX
REXX
/* REXX *************************************************************** * 28.02.2013 Walter Pachl * 12.03.2013 Walter Pachl typo in log corrected. thanx for testing * 22.05.2013 -"- extended the logic to accept other strings * 25.05.2013 -"- 'my' log routine is apparently incorrect * 25.05.2013 -"- problem identified ...
Give a code snippet in #REXX Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), t...
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Prolog
Prolog
multisplit(_LSep, '') --> {!}, [].   multisplit(LSep, T) --> {next_sep(LSep, T, [], Token, Sep, T1)}, ( {Token \= '' },[Token], {!}; []), ( {Sep \= '' },[Sep], {!}; []), multisplit(LSep, T1).   next_sep([], T, Lst, Token, Sep, T1) :- % if we can't find any separator, the game is over ( Lst = [] -> Token ...
Give a code snippet in #Prolog It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#C
C
void insert_append (struct link *anchor, struct link *newlink) { newlink->next = anchor->next; anchor->next = newlink; }
Give a code snippet in #C Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, E...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Java
Java
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Coll...
Give a code snippet in #Java Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should displa...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#JavaScript
JavaScript
// No built-in prepend var s=", World" s = "Hello" + s print(s);
Give a code snippet in #JavaScript Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
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...
#Hoon
Hoon
now
Give a code snippet in #Hoon 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   D...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#N.2Ft.2Froff
N/t/roff
Goodbye, World!
Give a code snippet in #N.2Ft.2Froff Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
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 ...
#6502_Assembly
6502 Assembly
GetAbs: ;assumes value we want to abs() is loaded into accumulator eor #$ff clc adc #1 rts
Give a code snippet in #6502_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#PureBasic
PureBasic
  EnableExplicit   Procedure.i SumBinaryDigits(Number) If Number < 0 : number = -number : EndIf; convert negative numbers to positive Protected sum = 0 While Number > 0 sum + Number % 2 Number / 2 Wend ProcedureReturn sum EndProcedure   Procedure.i IsPrime(Number) If Number <= 1 ProcedureReturn...
Give a code snippet in #PureBasic A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is p...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#OCaml
OCaml
Printf.printf "%d\n" (int_of_char 'a'); (* prints "97" *) Printf.printf "%c\n" (char_of_int 97); (* prints "a" *)
Give a code snippet in #OCaml Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code