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/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Common_Lisp
Common Lisp
;; Given a date, get the day of the week. Adapted from ;; http://lispcookbook.github.io/cl-cookbook/dates_and_times.html   (defun day-of-week (day month year) (nth-value 6 (decode-universal-time (encode-universal-time 0 0 0 day month year 0) 0)))   (defparameter *long-months* '(1 3 5 7 8 10 12))   (defun sun...
Give a code snippet in #Common_Lisp The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   say say 'Loops/For'   loop i_ = 1 to 5 loop for i_ say '*\-' end say end i_  
Give a code snippet in #NetRexx “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract struc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#Python
Python
from numpy import array, tril, sum   A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]   print(sum(tril(A, -1))) # 69
Give a code snippet in #Python Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Common_Lisp
Common Lisp
  (defun empty-directory-p (path) (and (null (directory (concatenate 'string path "/*"))) (null (directory (concatenate 'string path "/*/")))))  
Give a code snippet in #Common_Lisp Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory);...
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 ...
#TXR
TXR
@(next :args) @(coll :gap 0)@(choose :shortest tok)@\ @tok@{sep /==/}@\ @(or)@\ @tok@{sep /!=/}@\ @(or)@\ @tok@{sep /=/}@\ @(end)@(end)@tail @(output) @(rep)"@tok" {@sep} @(end)"@tail" @(end)
Give a code snippet in #TXR 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#BASIC256
BASIC256
  global radioTierra # radio de la tierra en km radioTierra = 6372.8   function Haversine(lat1, long1, lat2, long2 , radio) d_long = radians(long1 - long2) theta1 = radians(lat1) theta2 = radians(lat2) dx = cos(d_long) * cos(theta1) - cos(theta2) dy = sin(d_long) * cos(theta1) dz = sin(theta1) - sin(theta2) r...
Give a code snippet in #BASIC256 This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an e...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Rust
Rust
[package] name = "lychrel" version = "0.1.0" authors = ["monsieursquirrel"] [dependencies] num = "0.1.27"
Give a code snippet in #Rust   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most s...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#BCPL
BCPL
get "libhdr"   // Add a character to the end of a string let addch(s, ch) be $( s%0 := s%0 + 1 s%(s%0) := ch $) // Add s2 to the end of s1 and adds(s1, s2) be for i = 1 to s2%0 do addch(s1, s2%i)   // Comma quibbling on strs, which should be a 0-terminated // vector of string pointers. let quibble(strs...
Give a code snippet in #BCPL Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inp...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Swift
Swift
var n = 1   func recurse() { print(n) n += 1 recurse() }   recurse()
Give a code snippet in #Swift Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#CMake
CMake
function(eratosthenes var limit) # Check for integer overflow. With CMake using 32-bit signed integer, # this check fails when limit > 46340. if(NOT limit EQUAL 0) # Avoid division by zero. math(EXPR i "(${limit} * ${limit}) / ${limit}") if(NOT limit EQUAL ${i}) message(FATAL_ERROR "limit is...
Give a code snippet in #CMake This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#360_Assembly
360 Assembly
* Dot product 03/05/2016 DOTPROD CSECT USING DOTPROD,R15 SR R7,R7 p=0 LA R6,1 i=1 LOOPI CH R6,=AL2((B-A)/4) do i=1 to hbound(a) BH ELOOPI LR R1,R6 i SLA R1,2 *4 ...
Give a code snippet in #360_Assembly Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#J
J
load 'dates' NB. provides verb 'weekday' xmasSunday=: #~ 0 = [: weekday 12 25 ,~"1 0 ] NB. returns years where 25 Dec is a Sunday xmasSunday 2008 + i.114 NB. check years from 2008 to 2121 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 20...
Give a code snippet in #J A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#ooRexx
ooRexx
sub=.fork~new sub~sub Call syssleep 1 Do 3 Say 'program ' time() Call syssleep 1 End   ::class fork :: method sub Reply Do 6 Say 'subroutine' time() Call syssleep 1 End
Give a code snippet in #ooRexx Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#VBScript
VBScript
  Set objNetwork = CreateObject("WScript.Network") WScript.Echo objNetwork.ComputerName  
Give a code snippet in #VBScript Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Common_Lisp
Common Lisp
(defun factorial (n) (if (zerop n) 1 (* n (factorial (1- n)))))
Give a code snippet in #Common_Lisp Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Dao
Dao
syntax{Q $EXP}as{io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\')}Q io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\')
Give a code snippet in #Dao A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   s...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#Smalltalk
Smalltalk
|n|   n := 0. UserInterrupt catch:[ [true] whileTrue:[ n := n + 1. n printCR. Delay waitForSeconds: 0.5. ] ]
Give a code snippet in #Smalltalk Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#PicoLisp
PicoLisp
# *Morse *Dit *Dah   (balance '*Morse (mapcar '((L) (def (car L) (mapcar = (chop (cadr L)) '("." .)) ) ) (quote ("!" "---.") ("\"" ".-..-.") ("$" "...-..-") ("'" ".----.") ("(" "-.--.") (")" "-.--.-") ("+" ".-.-.") ("," "--..--") ("-" "-...
Give a code snippet in #PicoLisp Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ign...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Java
Java
import java.util.Arrays;   public class SpecialVariables {   public static void main(String[] args) {   //String-Array args contains the command line parameters passed to the program //Note that the "Arrays.toString()"-call is just used for pretty-printing System.out.println(Arrays.toString(...
Give a code snippet in #Java Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   #define TRUE 1 #define FALSE 0 #define STACK_SIZE 80 #define BUFFER_SIZE 100   typedef int bool;   typedef struct { char name; bool val; } var;   typedef struct { int top; bool els[STACK_SIZE]; } stack_of_bool;   char expr[BUFFER_SIZE]; int ex...
Give a code snippet in #C A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a form...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Erlang
Erlang
-module(cc).   -export([start/0]).   start() -> My_pid = erlang:self(), Pid = erlang:spawn( fun() -> reader(My_pid, 0) end ), {ok, IO } = file:open( "input.txt", [read] ), process( io:get_line(IO, ""), IO, Pid ), file:close( IO ).   process( eof, _IO, Pid ) -> Pid ! count, receive I -> io:fw...
Give a code snippet in #Erlang The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with differ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Ruby
Ruby
m=[[1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], [5, 25,125, 625]] puts m.transpose
Give a code snippet in #Ruby Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Zig
Zig
const std = @import("std");   pub fn main() !void { var in = try std.fs.cwd().openFile("input.txt", .{}); defer in.close(); var out = try std.fs.cwd().openFile("output.txt", .{ .mode = .write_only }); defer out.close(); var file_reader = in.reader(); var file_writer = out.writer(); var buf: ...
Give a code snippet in #Zig File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file int...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#M4
M4
# The macros which return a pair of values x,y expand to an unquoted 123,456 # which is suitable as arguments to a further macro. The quoting is slack # because the values are always integers and so won't suffer unwanted macro # expansion.   # 0,1 Vertex and segment x,y numbering. # ...
Give a code snippet in #M4 Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#C.23
C#
using System; using System.Text;   namespace prog { class MainClass { public static void Main (string[] args) { StringBuilder s = new StringBuilder(); Random rnd = new Random();   s.AppendLine("<table>"); s.AppendLine("<thead align = \"right\">"); s.Append("<tr><th></th>"); for(int i=0; i<3; i...
Give a code snippet in #C.23 Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with...
christopher/rosetta-code
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#Lua
Lua
local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end local f, limit = 5, math.sqrt(n) for f = 5, limit, 6 do if n % f == 0 then return false end if n % (f+2) == 0 then return false end end return true end   local function s3...
Give a code snippet in #Lua A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the fi...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Swift
Swift
import Foundation   print("Input max number: ", terminator: "")   guard let maxN = Int(readLine() ?? "0"), maxN > 0 else { fatalError("Please input a number greater than 0") }   func getFactor() -> (Int, String) { print("Enter a factor and phrase: ", terminator: "")   guard let factor1Input = readLine() else { ...
Give a code snippet in #Swift Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Stata
Stata
program define maprange version 15.1 syntax varname(numeric) [if] [in], /// from(numlist min=2 max=2) to(numlist min=2 max=2) /// GENerate(name) [REPLACE] tempname a b c d h sca `a'=`:word 1 of `from'' sca `b'=`:word 2 of `from'' sca `c'=`:word 1 of `to'' sca `d'=`:word 2 of `to'' sca `h'=(`d'-`c')/(`b'-`a'...
Give a code snippet in #Stata Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#m4
m4
divert(-1)   define(`loop', `ifelse(eval(0 < ($1)),1,`$1` 'loop(eval(($1) / 2))')')   divert`'dnl loop(1024)dnl
Give a code snippet in #m4 Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward f...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Swift
Swift
var deficients = 0 // sumPd < n var perfects = 0 // sumPd = n var abundants = 0 // sumPd > n   // 1 is deficient (no proper divisor) deficients++     for i in 2...20000 {   var sumPd = 1 // 1 is a proper divisor of all integer above 1   var maxPdToTest = i/2 // the max divisor to test   for var j = 2; j < m...
Give a code snippet in #Swift These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#MAXScript
MAXScript
inclusiveRange = [1,100] lowRange = inclusiveRange.x maxRange = inclusiveRange.y guesses = 1 inf = "Think of a number between % and % and I will try to guess it.\n" +\ "Type -1 if the guess is less than your number,\n"+\ "0 if the guess is correct, " +\ "or 1 if it's too high.\nPress esc to exit.\n" clearListene...
Give a code snippet in #MAXScript Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. 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 Implement the Drossel and Schwabl definition of the fores...
#Erlang
Erlang
  -module( forest_fire ).   -export( [task/0] ).   -record( state, {neighbours=[], position, probability_burn, probability_grow, tree} ).   task() -> erlang:spawn( fun() -> Pid_positions = forest_create( 5, 5, 0.5, 0.3, 0.2 ), Pids = [X || {X, _} <- Pid_positions], [X ! {tr...
Give a code snippet in #Erlang This page uses content from Wikipedia. The original article was at Forest-fire model. 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 Implement the Drossel and...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#TI-83_BASIC
TI-83 BASIC
ClrDraw Input "ITERS:",M [[0,0,1]]→[A] [[0,0,0][0,.16,0][0,0,1]]→[B] [[.85,-.04,0][.04,.85,0][0,1.6,1]]→[C] [[.2,.23,0][-.26,.22,0][0,1.6,1]]→[D] [[-.15,.26,0][.28,.24,0][0,.44,1]]→[E] 0→I While I<M randInt(1,100)→R   If R=1 Then [A][B]→[A] 101→R End   If R<86 Then [A][C]→[A] 101→R End   If R<93 Then [A][D]→[A] 101→R E...
Give a code snippet in #TI-83_BASIC A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.1...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Scheme
Scheme
(define pi (* 4 (atan 1)))   (do ((n 2 (+ n 1))) ((> n 10)) (display n) (do ((k 0 (+ k 1))) ((>= k n)) (display " ") (display (make-polar 1 (* 2 pi (/ k n))))) (newline))
Give a code snippet in #Scheme The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PicoLisp
PicoLisp
(let (X 77444 Y -12 Z 0) (println X Y Z) (mapc set '(X Y Z) (sort (list X Y Z))) (println X Y Z) )
Give a code snippet in #PicoLisp Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#ACL2
ACL2
(floor 15 2) ;; This is the floor of 15/2 (ceiling 15 2) (expt 15 2) ;; 15 squared
Give a code snippet in #ACL2 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. "ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#C.23
C#
  (defvar ♥♦♣♠ "♥♦♣♠") (defun ✈ () "a plane unicode function")  
Give a code snippet in #C.23 As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#x86-64_Assembly
x86-64 Assembly
 ; Puzzle15 by grosged (march 2019)  ; How to play ?.. Just press one of the arrow keys then [enter] to valid  ; ( press [Ctrl+C] to escape )   segment .data check: db "1 2 3 4",10," 5 6 7 8",10," 9 10 11 12",10," 13 14 1" puzzle: db 27,"c",10," 1 2 3 4",10," 5 ...
Give a code snippet in #x86-64_Assembly Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
leftRect[f_, a_Real, b_Real, N_Integer] := Module[{sum = 0, dx = (b - a)/N, x = a, n = N} , For[n = N, n > 0, n--, x += dx; sum += f[x];]; Return [ sum*dx ]]   rightRect[f_, a_Real, b_Real, N_Integer] := Module[{sum = 0, dx = (b - a)/N, x = a + (b - a)/N, n = N} , For[n = N, n > 0, n--, x += dx; sum += f[x];]...
Give a code snippet in #Mathematica.2FWolfram_Language 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 numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Raku
Raku
print "Goodbye, World!"; printf "%s", "Goodbye, World!";
Give a code snippet in #Raku Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Bracmat
Bracmat
( put$"Enter a variable name: " & get$:?name & whl ' ( put$"Enter a numeric value: " & get$:?numeric:~# ) & !numeric:?!name & put$(str$("Variable " !name " now has the value " !!name \n)) );
Give a code snippet in #Bracmat Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#C
C
#include <math.h> #include <stdio.h>   int main() { double pi = 4 * atan(1); /*Pi / 4 is 45 degrees. All answers should be the same.*/ double radians = pi / 4; double degrees = 45.0; double temp; /*sine*/ printf("%f %f\n", sin(radians), sin(degrees * pi / 180)); /*cosine*/ printf("%f %f\n", cos(radian...
Give a code snippet in #C Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate ...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Quackery
Quackery
' [ 2 3 5 7 ] smoothwith [ -1 peek [ 10 12 ** ] constant = ] -1 split drop dup 50 split drop echo cr cr 12 times [ dup 0 over size rot 10 i^ 1+ ** searchwith < drop split swap size echo sp i^ 1+ echo say "-digit humble numbers" cr ] drop  
Give a code snippet in #Quackery Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the ab...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Tcl
Tcl
package require Tcl 8.5 proc wordsInString str { # We define "words" to be "maximal sequences of 'word' characters". # The other possible definition is to use 'non-space' characters. regexp -all -inline {\w+} $str }   # Adds a document to the index. The index is a map from words to a map # from filenames to...
Give a code snippet in #Tcl An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / term...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Positional_read
Terminal control/Positional read
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, r...
#TXR
TXR
;;; Type definitions and constants   (typedef BOOL (enum BOOL FALSE TRUE)) (typedef HANDLE cptr) (typedef WCHAR wchar) (typedef DWORD uint32) (typedef WORD uint16) (typedef SHORT short)   (typedef COORD (struct COORD (X SHORT) (Y SHORT)))   (typedef SMALL_RECT (struct SMALL_RECT ...
Give a code snippet in #TXR Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display re...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#BASIC256
BASIC256
function mobius(n) if n = 1 then return 1 for d = 2 to int(sqr(n)) if n mod d = 0 then if n mod (d*d) = 0 then return 0 return -mobius(n/d) end if next d return -1 end function   outstr$ = " . " for i = 1 to 200 if mobius(i) >= 0 then outstr$ += " " outstr$ += string(mobius(i)) + " " if i mod 10 = ...
Give a code snippet in #BASIC256 The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Lasso
Lasso
local(server) = net_tcp handle => { #server->close } #server->bind(8080) & listen & forEachAccept => { local(con) = #1   split_thread => { handle => { #con->close } local(request) = '' // Read in the request in chunks until you have it all { #request->append(#con->readSomeBytes(80...
Give a code snippet in #Lasso The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note...
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 ...
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('.....$'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = ....
Give a code snippet in #PL.2FM 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 ar...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Emacs_Lisp
Emacs Lisp
(defvar input (with-temp-buffer (insert-file-contents "input.txt") (buffer-string)))   (with-temp-file "output.txt" (insert input))  
Give a code snippet in #Emacs_Lisp File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#zkl
zkl
s:=T("Cat","apple","Adam","zero","Xmas","quit","Level","add","Actor","base","butter"); r:=s.sort(fcn(a,b){ an,bn := a.len(),b.len(); if(an==bn)(a.toLower() < b.toLower()) else (an > bn) }); r.pump(Console.println);
Give a code snippet in #zkl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#MAXScript
MAXScript
m = bigMatrix 5 4 for i in 1 to 5 do for j in 1 to 4 do m[i][j] = pow i j m = transpose m
Give a code snippet in #MAXScript Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#ALGOL_W
ALGOL W
begin % compare lists (rows) of integers %  % returns TRUE if there is an element in a that is < the corresponding %  % element in b and all previous elements are equal, FALSE otherwise  %  % the bounds of a and b should aLb :: aUb and bLb :: bUb  % logical procedure iLT ( integer array a ( ...
Give a code snippet in #ALGOL_W sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort ...
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...
#Rascal
Rascal
import IO; import util::Math; import List;   public void make_maze(int w, int h){ vis = [[0 | _ <- [1..w]] | _ <- [1..h]]; ver = [["| "| _ <- [1..w]] + ["|"] | _ <- [1..h]] + [[]]; hor = [["+--"| _ <- [1..w]] + ["+"] | _ <- [1..h + 1]];   void walk(int x, int y){ vis[y][x] = 1;   d = [<x - 1, y>, <x, y + 1>, <...
Give a code snippet in #Rascal 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 sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Modula-3
Modula-3
PROCEDURE FactIter(n: CARDINAL): CARDINAL = VAR result := n; counter := n - 1;   BEGIN FOR i := counter TO 1 BY -1 DO result := result * i; END; RETURN result; END FactIter;
Give a code snippet in #Modula-3 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Untouchable_numbers
Untouchable numbers
Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known as   the   aliquot sum.   A...
#Perl
Perl
use strict; use warnings; use enum qw(False True); use ntheory qw/divisor_sum is_prime/;   sub sieve { my($n) = @_; my %s; for my $k (0 .. $n+1) { my $sum = divisor_sum($k) - $k; $s{$sum} = True if $sum <= $n+1; } %s }   my(%s,%c); my($max, $limit, $cnt) = (2000, 1e5, 0);   %s = siev...
Give a code snippet in #Perl Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also know...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Julia
Julia
using BenchmarkTools, Combinatorics   function missingperm(arr::Vector) allperms = String.(permutations(arr[1])) # revised for type safety for perm in allperms if perm ∉ arr return perm end end end   arr = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB...
Give a code snippet in #Julia ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Zig
Zig
const std = @import("std");   const debug = std.debug; const mem = std.mem;   test "copy a string" { const source = "A string.";   // Variable `dest1` will have the same type as `source`, which is // `*const [9:0]u8`. const dest1 = source;   // Variable `dest2`'s type is [9]u8. // // The dif...
Give a code snippet in #Zig This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty str...
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...
#PHP
PHP
<?php   $str = ''; // assign an empty string to a variable   // check that a string is empty if (empty($str)) { ... }   // check that a string is not empty if (! empty($str)) { ... }   // we could also use the following if ($str == '') { ... } if ($str != '') { ... }   if (strlen($str) == 0) { ... } if (strlen($str) !=...
Give a code snippet in #PHP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Quackery
Quackery
[ stack ] is operators ( --> s )   0 $ "*/+-" witheach [ bit | ] operators put   [ stack ] is numbers ( --> s )   [ 0 swap witheach [ bit | ] numbers put ] is putnumbers (...
Give a code snippet in #Quackery The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four...
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
#Swift
Swift
print("Hello world!")
Give a code snippet in #Swift 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/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 ...
#Delphi
Delphi
if (input.Field == "Hello World") { sVar = "good"; } else if (input.Field == "Bye World") { sVar = "bad"; } else { sVar = "neutral"; }
Give a code snippet in #Delphi 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/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Quackery
Quackery
[ 2dup = iff [ 2drop drop ] done dip over swap over = iff [ 2drop drop ] done rot echo sp swap echo sp echo cr ] is fire ( pol san fir --> )   [ 2dup = iff 2drop done 12 over - dip over swap - dup 1 < iff [ 2drop drop ] done dup 7 > iff ...
Give a code snippet in #Quackery There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#C.2B.2B
C++
#include <vector> #include <string> #include <sstream> #include <iostream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib>   double rpn(const std::string &expr){ std::istringstream iss(expr); std::vector<double> stack; std::cout << "Input\tOperation\tStack after" << std::endl; std::...
Give a code snippet in #C.2B.2B Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#D
D
void main() { import std.array, std.range;   immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray; }
Give a code snippet in #D Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Tcl
Tcl
% clock format 0 -gmt 1 Thu Jan 01 00:00:00 GMT 1970
Give a code snippet in #Tcl Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the sce...
christopher/rosetta-code
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Lua
Lua
-- History variables in Lua 6/12/2020 db local HistoryVariable = { new = function(self) return setmetatable({history={}},self) end, get = function(self) return self.history[#self.history] end, set = function(self, value) self.history[#self.history+1] = value end, undo = function(self) self...
Give a code snippet in #Lua Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  distance[{theta1_, phi1_}, {theta2_, phi2_}] := 2*6378.14 ArcSin@ Sqrt[Haversine[(theta2 - theta1) Degree] + Cos[theta1*Degree] Cos[theta2*Degree] Haversine[(phi2 - phi1) Degree]]  
Give a code snippet in #Mathematica_.2F_Wolfram_Language This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The h...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Wren
Wren
/* check_output_device_is_terminal.wren */   class C { foreign static isOutputDeviceTerminal }   System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)")
Give a code snippet in #Wren Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#UBASIC
UBASIC
  10 Point 7 'Sets decimal display to 32 places (0+.1^56) 20 Rf=#pi/180 'Degree -> Radian Conversion 100 ?Using(,7),.DxH(36+7.2/60,-(86+40.2/60),33+56.4/60,-(118+24/60));" km" 999 End 1000 '*** Haversine Distance Function *** 1010 .DxH(Lat_s,Long_s,Lat_f,Long_f) 1020 L_s=Lat_s*rf:L_f=Lat_f*rf:LD=L_f...
Give a code snippet in #UBASIC This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_turtle_graphics
Simple turtle graphics
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. See imag...
#Action.21
Action!
INCLUDE "D2:TURTLE.ACT" ;from the Action! Tool Kit   PROC Rectangle(INT w,h) BYTE i   FOR i=1 TO 2 DO Forward(h) Left(90) Forward(w) Left(90) OD RETURN   PROC Square(INT w) Rectangle(w,w) RETURN   PROC Triangle(INT w) BYTE i   FOR i=1 TO 3 DO Forward(w) Right(120) OD RETURN   P...
Give a code snippet in #Action.21 The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics migh...
christopher/rosetta-code
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Pascal
Pascal
program nSmoothNumbers(output);   const primeCount = 538; {$ifDef __GPC__} {$setLimit=3889} {$endIf} cardinalMax = 3888;   type cardinal = 0..cardinalMax; cardinals = set of cardinal; cardinalPositive = 1..cardinalMax;   natural = 1..maxInt;   primeIndex = 1..primeCount; list = array[primeIndex] of cardinal;  ...
Give a code snippet in #Pascal n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Tcl
Tcl
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc}   proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i ...
Give a code snippet in #Tcl Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Objeck
Objeck
  bundle Default { class Roman { nums: static : Int[]; rum : static : String[];   function : Init() ~ Nil { nums := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; rum := ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; }   function : native : ToRoman(nu...
Give a code snippet in #Objeck Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Slate
Slate
(File newNamed: 'input.txt') delete. (File newNamed: '/input.txt') delete. (Directory newNamed: 'docs') delete. (Directory newNamed: '/docs') delete.
Give a code snippet in #Slate Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Verhoeff_algorithm
Verhoeff algorithm
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t...
#Python
Python
MULTIPLICATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8,...
Give a code snippet in #Python Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Brat
Brat
mean = { list | true? list.empty?, 0, { list.reduce(0, :+) / list.length } }   p mean 1.to 10 #Prints 5.5
Give a code snippet in #Brat Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
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 ...
#BASIC
BASIC
FUNCTION checkNoSpaces (s$) FOR i = 1 TO LEN(s$) - 1 IF MID$(s$, i, 1) = CHR$(32) OR MID$(s$, i, 1) = CHR$(9) THEN checkNoSpaces = 0 NEXT i checkNoSpaces = 1 END FUNCTION   OPEN "input.fasta" FOR INPUT AS #1   first = 1   DO WHILE NOT EOF(1) LINE INPUT #1, ln$ IF LEFT$(ln$, 1) = ">" THEN ...
Give a code snippet in #BASIC 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: >Roset...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Quackery
Quackery
[ table ] is crctable ( n --> n )   256 times [ i^ 8 times [ dup 1 >> swap 1 & if [ hex EDB88320 ^ ] ] ' crctable put ]   [ hex FFFFFFFF swap witheach [ over ^ hex FF & crctable swap 8 >> ^ ] hex FFFFFFFF ^ ] is cr...
Give a code snippet in #Quackery Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Emacs_Lisp
Emacs Lisp
(set (intern (read-string "Enter variable name: ")) 123)
Give a code snippet in #Emacs_Lisp Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
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...
#Logo
Logo
to compute_means :count local "sum make "sum 0 local "product make "product 1 local "reciprocal_sum make "reciprocal_sum 0   repeat :count [ make "sum sum :sum repcount make "product product :product repcount make "reciprocal_sum sum :reciprocal_sum (quotient repcount) ]   output (sen...
Give a code snippet in #Logo 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/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Clojure
Clojure
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address)   (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
Give a code snippet in #Clojure DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Go
Go
package main   import ( "fmt" "math" "math/rand" "time" )   // "given" func dice5() int { return rand.Intn(5) + 1 }   // function specified by task "Seven-sided dice from five-sided dice" func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break }...
Give a code snippet in #Go Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the fu...
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...
#Maple
Maple
path := "file.txt": specificLine := proc(path, num) local i, input: for i to num do input := readline(path): if input = 0 then break; end if: end do: if i = num+1 then printf("Line %d, %s", num, input): elif i <= num then printf ("Line number %d is not reached",num): end if: end proc:
Give a code snippet in #Maple 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Common_Lisp
Common Lisp
(defun special-variables () (flet ((special-var-p (s) (and (char= (aref s 0) #\*) (find-if-not (lambda (x) (char= x #\*)) s) (char= (aref s (1- (length s))) #\*)))) (let ((lst '())) (do-symbols (s (find-package 'cl)) (when (special-var-p (symbol-name s)) ...
Give a code snippet in #Common_Lisp Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#AWK
AWK
# # countsubstring(string, pattern) # Returns number of occurrences of pattern in string # Pattern treated as a literal string (regex characters not expanded) # function countsubstring(str, pat, len, i, c) { c = 0 if( ! (len = length(pat) ) ) return 0 while(i = index(str, pat)) { str = substr(str,...
Give a code snippet in #AWK Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#C
C
#include <stdio.h> #include <stdlib.h>   int main() { int i; printf("<table style=\"text-align:center; border: 1px solid\"><th></th>" "<th>X</th><th>Y</th><th>Z</th>"); for (i = 0; i < 4; i++) { printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i, rand() % 10000, rand() % 10000, rand() % 10000);...
Give a code snippet in #C Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with se...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#PureBasic
PureBasic
IncludeFile "Filename"
Give a code snippet in #PureBasic Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
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...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
EMPTYSTR  ; Demonstrate how to assign an empty string to a variable. set x = ""    ; Demonstrate how to check that a string is empty.  ; Length 0 is empty; equality/pattern check are 1=T, 0=F write !,"Assigned x to null value. Tests: " write !,"String length: "_$length(x)_", Equals null: "...
Give a code snippet in #Cach.C3.A9_ObjectScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Java
Java
String src = "Hello"; String newAlias = src; String strCopy = new String(src);   //"newAlias == src" is true //"strCopy == src" is false //"strCopy.equals(src)" is true
Give a code snippet in #Java This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty st...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double Dim temp = 0.0 For ni = n To 1 Step -1 Dim p = f(ni) temp = p(1) / (p(0) + temp) Next Return f(0)(0) + temp End Function   Sub Main() Dim fList = { ...
Give a code snippet in #Visual_Basic_.NET continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#jq
jq
# Input: an array of strings def max_licenses_in_use: # state: [in_use = 0, max_in_use = -1, max_in_use_at = [] ] reduce .[] as $line ([0, -1, [] ]; ($line|split(" ")) as $line | if $line[1] == "OUT" then .[0] += 1 # in_use++; | if .[0] > .[1] ...
Give a code snippet in #jq A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checko...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Ksh
Ksh
  #!/bin/ksh   # Split a character string based on change of character   # # Variables: # str='gHHH5YY++///\' delim=', '   # # Functions: # # # Function _splitonchg(str, delim) - return str split by delim at char change # function _splitonchg { typeset _str ; _str="$1" typeset _delim ; _delim="$2" typeset _i _splits...
Give a code snippet in #Ksh Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#XPL0
XPL0
include c:\cxpl\codes; int N; real R; [Text(8, "123_456"); N:= IntIn(8); IntOut(0, N); CrLf(0); Text(8, "ABcd12"); N:= HexIn(8); HexOut(0, N); CrLf(0); Text(8, "-3.14159e3"); R:= RlIn(8); RlOut(0, R); CrLf(0); ]
Give a code snippet in #XPL0 It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of s...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#PL.2FI
PL/I
short_circuit_evaluation: procedure options (main); declare (true initial ('1'b), false initial ('0'b) ) bit (1); declare (i, j, x, y) bit (1);   a: procedure (bv) returns (bit(1)); declare bv bit(1); put ('Procedure ' || procedurename() || ' called.'); return (bv); end a; b: procedure (bv) returns (b...
Give a code snippet in #PL.2FI Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable re...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Maxima
Maxima
callee(n) := (print(sconcat("called with ", n)), n + 1)$ caller(f, n) := sum(f(i), i, 1, n)$ caller(callee, 3); "called with 1" "called with 2" "called with 3"
Give a code snippet in #Maxima Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#ALGOL_W
ALGOL W
begin % find members of the Harshad/Niven series - numbers divisible by the sum of their digits %  % returns the next member of the series above n  % integer procedure nextHarshad ( integer value n ) ; begin integer h, s; h := n; while begin ...
Give a code snippet in #ALGOL_W The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#BBC_BASIC
BBC BASIC
MazeWidth% = 11 MazeHeight% = 9 MazeCell% = 50   VDU 23,22,MazeWidth%*MazeCell%/2+3;MazeHeight%*MazeCell%/2+3;8,16,16,128 VDU 23,23,3;0;0;0; : REM Line thickness OFF PROCgeneratemaze(Maze&(), MazeWidth%, MazeHeight%, MazeCell%) PROCsolvemaze(Path{()}, Maze&(), 0, MazeHeig...
Give a code snippet in #BBC_BASIC Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Euphoria
Euphoria
sequence s1,s2,s3 s1 = {1,2,3} s2 = {4,5,6} s3 = s1 & s2 ? s3
Give a code snippet in #Euphoria Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Racket
Racket
  #lang racket ;print column of width w (define (display-col w s) (let* ([n-spaces (- w (string-length s))] [spaces (make-string n-spaces #\space)]) (display (string-append s spaces)))) ;print columns given widths (idea borrowed from PicoLisp) (define (tab ws . ss) (for-each display-col ws ss) (newline))...
Give a code snippet in #Racket Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represe...
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...
#PL.2FM
PL/M
100H: /* LONG MULTIPLICATION OF LARGE INTEGERS */ /* LARGE INTEGERS ARE REPRESENTED BY ARRAYS OF BYTES WHOSE VALUES ARE */ /* A SINGLE DECIMAL DIGIT OF THE NUMBER */ /* THE LEAST SIGNIFICANT DIGIT OF THE LARGE INTEGER IS IN ELEMENT 1 */ ...
Give a code snippet in #PL.2FM 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