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/Keyboard_input/Flush_the_keyboard_buffer | Keyboard input/Flush the keyboard buffer | Flush the keyboard buffer.
This reads characters from the keyboard input and
discards them until there are no more currently buffered,
and then allows the program to continue.
The program must not wait for users to type anything.
| #PowerShell | PowerShell | while ($Host.UI.RawUI.KeyAvailable) {
$Host.UI.RawUI.ReadKey() | Out-Null
} | Give a code snippet in #PowerShell
Flush the keyboard buffer.
This reads characters from the keyboard input and
discards them until there are no more currently buffered,
and then allows the program to continue.
The program must not wait for users to type anything.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #Wren | Wren | import "/seq" for Lst
var find = Fn.new { |haystack, needle|
var res = Lst.indicesOf(haystack, needle)
if (!res[0]) Fiber.abort("Needle not found in haystack.")
System.print("The needle occurs %(res[1]) time(s) in the haystack.")
if (res[1] == 1) {
System.print("It occurs at index %(res[2][0])... | Give a code snippet in #Wren
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle tha... | 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 ... | #Lua | Lua | #!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
local sample_size = arg[2] or 5;
-- read dictionary
local f = assert(io.open(dictfile, "r"))
local dict = {}
for line in f:lines() do
dict[line] = line:reverse()
end
f:close()
-- f... | Give a code snippet in #Lua
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/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... | #Picat | Picat | import util.
go =>
text(1,Text),
foreach(LineWidth in [60,80])
println(lineWidth=LineWidth),
println(wrap(Text,LineWidth)),
nl
end,
nl.
wrap(Text,LineWidth) = Wrapped =>
Words = Text.split(),
Wrapped = Words[1],
SpaceLeft = LineWidth - Wrapped.len,
foreach(Word in Words.tail)
... | Give a code snippet in #Picat
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 prov... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to... | #Common_Lisp | Common Lisp | (defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
((<= ua c (char-code #\Z)) ua)
(nil))))
(if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))
(defun caes... | Give a code snippet in #Common_Lisp
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrappin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Ursala | Ursala | #import cli
hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>! | Give a code snippet in #Ursala
Task
Find the name of the host on which the routine is running.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are n... | #Kotlin | Kotlin | import kotlin.math.abs
fun isEsthetic(n: Long, b: Long): Boolean {
if (n == 0L) {
return false
}
var i = n % b
var n2 = n / b
while (n2 > 0) {
val j = n2 % b
if (abs(i - j) != 1L) {
return false
}
n2 /= b
i = j
}
return true
}
f... | Give a code snippet in #Kotlin
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero dif... | 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 |... | #Icon_and_Unicon | Icon and Unicon | s := "world!"
s := "Hello, " || s | Give a code snippet in #Icon_and_Unicon
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 O... | 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... | #TI-83_BASIC | TI-83 BASIC | 1024→I
While I>0
Disp I
I/2→I
End
| Give a code snippet in #TI-83_BASIC
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/D... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey se... | #PureBasic | PureBasic | EnableExplicit
Structure farey_struc
complex.POINT
quotient.d
EndStructure
#MAXORDER=1000
Global NewList fareylist.farey_struc()
Define v_start.i,
v_end.i,
v_step.i,
order.i,
fractions.i,
check.b,
t$
Procedure farey(order)
NewList sequence.farey_struc()
Define q... | Give a code snippet in #PureBasic
The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Vim_Script | Vim Script | echo map([10, 20, 30], 'v:val * v:val')
echo map([10, 20, 30], '"Element " . v:key . " = " . v:val')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:val)')
echo map({"a": "foo", "b": "Bar", "c": "BaZ"}, 'toupper(v:key)') | Give a code snippet in #Vim_Script
Task
Take a combined set of elements and apply a function to each element.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Efene | Efene | square = fn (N) {
N * N
}
# list comprehension
squares1 = fn (Numbers) {
[square(N) for N in Numbers]
}
# functional form
squares2a = fn (Numbers) {
lists.map(fn square:1, Numbers)
}
# functional form with lambda
squares2b = fn (Numbers) {
lists.map(fn (N) { N * N }, Numbers)
}
# no need for a f... | Give a code snippet in #Efene
Task
Take a combined set of elements and apply a function to each element.
| 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... | #Julia | Julia | function makedoubleindex(files)
idx = Dict{String, Dict}()
for file in files
str = lowercase(read(file, String))
words = split(str, r"\s+")
for word in words
if !haskey(idx, word)
idx[word] = Dict{String, Int}()
elseif !haskey(idx[word], file)
... | Give a code snippet in #Julia
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 / te... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Crystal | Crystal | loop do
puts "SPAM"
end | Give a code snippet in #Crystal
Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Lo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abbreviations,_easy | Abbreviations, easy | This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
... | #Haskell | Haskell |
import Data.Maybe (fromMaybe)
import Data.List (find, isPrefixOf)
import Data.Char (toUpper, isUpper)
isAbbreviationOf :: String -> String -> Bool
isAbbreviationOf abbreviation command =
minimumPrefix `isPrefixOf` normalizedAbbreviation
&& normalizedAbbreviation `isPrefixOf` normalizedCommand
where
normal... | Give a code snippet in #Haskell
This task is an easier (to code) variant of the Rosetta Code task: Abbreviations, simple.
For this task, the following command table will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUP... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th... | #Julia | Julia | function longer(a, b)
try
b[endof(a)]
catch
return true
end
return false
end
function printlongest(io::IO)
lines = longest = ""
while !eof(io)
line = readline(io)
if longer(line, longest)
longest = lines = line
elseif !longer(longest, line)
... | Give a code snippet in #Julia
Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #MATLAB_.2F_Octave | MATLAB / Octave |
fid = fopen('foobar.txt','r');
if (fid < 0)
printf('Error:could not open file\n')
else
while ~feof(fid),
line = fgetl(fid);
%% process line %%
end;
fclose(fid)
end; | Give a code snippet in #MATLAB_.2F_Octave
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #6502_Assembly | 6502 Assembly | ;Init Routine
*=$0801
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00
*=$0810 ;Start at $0810
LDA #$A9 ;opcode for LDA immediate
STA smc_test
LDA #'A'
STA smc_test+1
lda #$20 ;opcode for JSR
STA smc_test+2
lda #<CHROUT
STA smc_test+3
lda #>CHROUT
STA smc_test+4
smc_test:
n... | Give a code snippet in #6502_Assembly
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if... | 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 ... | #Factor | Factor | USING: io kernel math.matrices math.parser prettyprint
sequences ;
IN: rosettacode.runtime2darray
: set-Mi,j ( elt {i,j} matrix -- )
[ first2 swap ] dip nth set-nth ;
: Mi,j ( {i,j} matrix -- elt )
[ first2 swap ] dip nth nth ;
: example ( -- )
readln readln [ string>number ] bi@ zero-matrix ! create the array
[ ... | Give a code snippet in #Factor
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 num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #PowerBASIC | PowerBASIC |
#COMPILE EXE
#COMPILER PBWIN 9.05
#DIM ALL
FUNCTION ROT13(BYVAL a AS STRING) AS STRING
LOCAL p AS BYTE PTR
LOCAL n AS BYTE, e AS BYTE
LOCAL res AS STRING
res = a
p = STRPTR(res)
n = @p
DO WHILE n
SELECT CASE n
CASE 65 TO 90
e = 90
n += 13
CASE 97 TO 122
e = 12... | Give a code snippet in #PowerBASIC
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line r... | christopher/rosetta-code | |
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... | #Java | Java | public class SystemTime{
public static void main(String[] args){
System.out.format("%tc%n", System.currentTimeMillis());
}
} | Give a code snippet in #Java
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/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
/size 400 def
realtime srand
/rand1 { rand 2147483647 div } def
/m { moveto } bind def
/l { rlineto} bind def
/drawboard {
0 1 n 1 sub { /y exch def
0 1 n 1 sub { /x exch def
board x get y get 1 eq {
x c mul y c mul ... | Give a code snippet in #PostScript
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Tcl | Tcl | package require Tcl 8.6
package require Thread
# Pooled computation engine; runs event loop internally
namespace eval pooled {
variable poolSize 3; # Needs to be tuned to system size
proc computation {computationDefinition entryPoint values} {
variable result
variable poolSize
# Add communication shim
a... | Give a code snippet in #Tcl
Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass... | #F.23 | F# | let box = [|
"North"; "North by east"; "North-northeast"; "Northeast by north";
"Northeast"; "Northeast by east"; "East-northeast"; "East by north";
"East"; "East by south"; "East-southeast"; "Southeast by east";
"Southeast"; "Southeast by south"; "South-southeast"; "South by east";
"South"; "South ... | Give a code snippet in #F.23
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and dis... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Neko | Neko | /**
<doc>
<h2>bitwise operations</h2>
<p>Tectonics:
<br> nekoc bitwise.neko
<br> neko bitwise</p>
</doc>
*/
// Neko is a signed 31 bit integer VM, full 32 bit requires builtins
var int32_new = $loader.loadprim("std@int32_new", 1);
var int32_and = $loader.loadprim("std@int32_and", 2);
var int32_or ... | Give a code snippet in #Neko
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Haskell | Haskell | import Data.List (elemIndex, tails)
import Data.Maybe (fromJust)
doLZW :: Eq a => [a] -> [a] -> [Int]
doLZW _ [] = []
doLZW as (x:xs) = lzw (return <$> as) [x] xs
where
lzw a w [] = [fromJust $ elemIndex w a]
lzw a w (x:xs)
| w_ `elem` a = lzw a w_ xs
| otherwise = fromJust (elemIndex w a) : lzw... | Give a code snippet in #Haskell
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
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
... | #COBOL | COBOL | PROGRAM-ID. sort-ints.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 array-area VALUE "54321".
03 array PIC 9 OCCURS 5 TIMES.
01 i PIC 9.
PROCEDURE DIVISION.
main-line.
PERFORM display-array
... | Give a code snippet in #COBOL
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/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #bc | bc | define t(n, f) {
auto m
m = (n - 1) / f
return(f * m * (m + 1) / 2)
}
define s(l) {
return(t(l, 3) + t(l, 5) - t(l, 15))
}
s(1000)
s(10 ^ 20) | Give a code snippet in #bc
Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #LaTeX | LaTeX | \documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
\pgfdeclarelindenmayersystem{Dragon curve}{
\symbol{S}{\pgflsystemdrawforward}
\rule{F -> -F++S-}
\rule{S -> +F--S+}
}
\foreach \i in {1,...,8} {
\hbox{
order=\i
\hspace{.5em}
\begin{tikzpicture}[baseli... | Give a code snippet in #LaTeX
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... | 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... | #jq | jq | # Denoting the input by $n, which is assumed to be a positive integer,
# eratosthenes/0 produces an array of primes less than or equal to $n:
def eratosthenes:
# erase(i) sets .[i*j] to false for integral j > 1
def erase(i):
if .[i] then reduce range(2; (1 + length) / i) as $j (.; .[i * $j] = false)
else ... | Give a code snippet in #jq
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 algo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #REXX | REXX | /*REXX program to solve Pell's equation for the smallest solution of positive integers. */
numeric digits 2200 /*ensure enough decimal digs for answer*/
parse arg $ /*obtain optional arguments from the CL*/
if $=='' | $=="," then $= 61 109 181 277 ... | Give a code snippet in #REXX
Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
t... | #FreeBASIC | FreeBASIC | ' version 18-03-2017
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Sub four_rings(low As Long, high As Long, unique As Long, show As Long)
Dim As Long a, b, c... | Give a code snippet in #FreeBASIC
4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of... | 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
| #Java | Java | public class Class1 extends Class2
{
//code here
} | Give a code snippet in #Java
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/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such ... | Give a code snippet in #LLVM
Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Scala | Scala | object SpinningRod extends App {
val start = System.currentTimeMillis
def a = "|/-\\"
print("\033[2J") // hide the cursor
while (System.currentTimeMillis - start < 20000) {
for (i <- 0 until 4) {
print("\033[2J\033[0;0H") // clear terminal, place cursor at top left corner
for (j <- 0 until... | Give a code snippet in #Scala
Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the ... | 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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main(args)
write(fib(integer(!args) | 1000)
end
procedure fib(n)
static fCache
initial {
fCache := table()
fCache[0] := 0
fCache[1] := 1
}
/fCache[n] := fib(n-1) + fib(n-2)
return fCache[n]
end | Give a code snippet in #Icon_and_Unicon
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 sol... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #JavaScript | JavaScript | for (var n = 0; n < 1e14; n++) { // arbitrary limit that's not too big
document.writeln(n.toString(8)); // not sure what's the best way to output it in JavaScript
} | Give a code snippet in #JavaScript
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reach... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"|
"B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030"))
end
procedure sedol(x) #: return the completed sedol with check digit
static w,c
initial {
every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 # map chars
... | Give a code snippet in #Icon_and_Unicon
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBK... | 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 ... | #PicoLisp | PicoLisp | (de multiply (A B)
(* A B) ) | Give a code snippet in #PicoLisp
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/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... | #Maple | Maple | EmirpPrime := proc(n)
local eprime;
eprime := parse(StringTools:-Reverse(convert(n,string)));
if n <> eprime and isprime(n) and isprime(eprime) then
return n;
end if;
end proc:
EmirpsList := proc( n )
local i, values;
values := Array([]):
i := 0:
do
i := i + 1;
if... | Give a code snippet in #Maple
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Tcl | Tcl | proc m {n} {
if { $n == 0 } { expr 0; } else {
expr {$n - [f [m [expr {$n-1}] ]]};
}
}
proc f {n} {
if { $n == 0 } { expr 1; } else {
expr {$n - [m [f [expr {$n-1}] ]]};
}
}
for {set i 0} {$i < 20} {incr i} {
puts -nonewline [f $i];
puts -nonewline " ";
}
puts ""
for {set i 0} {$i < 20} {inc... | Give a code snippet in #Tcl
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #SPL | SPL | > i, 10..0,-1
#.output(i)
< | Give a code snippet in #SPL
Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Incremen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #QBasic | QBasic |
PRINT "First line."
GOSUB sub1
PRINT "Fifth line."
GOTO Ending
sub1:
PRINT "Second line."
GOSUB sub2
PRINT "Fourth line."
RETURN
Ending:
PRINT "We're just about done..."
GOTO Finished
sub2:
PRINT "Third line."
RETURN
Finished:
PRINT "... with goto and gosub, thankfully."
END | Give a code snippet in #QBasic
Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
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
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: pair is new struct
var string: name is "";
var string: value is "";
end struct;
const func integer: compare (in pair: pair1, in pair: pair2) is
return compare(pair1.name, pair2.name);
const func string: str (in pair: aPair) is
return "(" <& aPair.name <& ", " <&... | Give a code snippet in #Seed7
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/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Sidef | Sidef | var t = true;
var f = false; | Give a code snippet in #Sidef
Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #REXX | REXX | /*REXX pgm uses the Lucas─Lehmer primality test for prime powers of 2 (Mersenne primes)*/
@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1 /*a partial list of some low primes. */
!.=@.; !.0=1; !.2=1; !.4=1; !.5=1; !.6=1; !.8=1 /*#'s with these last digs aren't prime*/
parse arg limit . ... | Give a code snippet in #REXX
Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,... | #uBasic.2F4tH | uBasic/4tH | Print "A factor of M929 is "; FUNC(_FNmersenne_factor(929))
Print "A factor of M937 is "; FUNC(_FNmersenne_factor(937))
End
_FNmersenne_factor Param(1)
Local(2)
If (FUNC(_FNisprime(a@)) = 0) Then Return (-1)
For b@ = 1 TO 99999
c@ = (2*a@*b@) + 1
If (FUNC(_FNisprime(c@))) Then
If (AND (c@, 7... | Give a code snippet in #uBasic.2F4tH
A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_length | String length | Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.
F... | #SQL | SQL |
VALUES LENGTH('møøse', CODEUNITS16);
VALUES LENGTH('møøse', CODEUNITS32);
VALUES CHARACTER_LENGTH('møøse', CODEUNITS32);
VALUES LENGTH2('møøse');
VALUES LENGTH4('møøse');
VALUES LENGTH('𝔘𝔫𝔦𝔠𝔬𝔡𝔢', CODEUNITS16);
VALUES LENGTH('𝔘𝔫𝔦𝔠𝔬𝔡𝔢', CODEUNITS32);
VALUES CHARACTER_LENGTH('𝔘𝔫𝔦𝔠𝔬𝔡𝔢', CODEUNITS32);... | Give a code snippet in #SQL
Task
Find the character and byte length of a string.
This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
By character, we mean an individual Unicode code point, not a user-visible grapheme contai... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #Transd | Transd |
#lang transd
mainModule: {
_start: (lambda (textout "Hello, World!"))
}
| Give a code snippet in #Transd
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the languag... | christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #PicoLisp | PicoLisp | (load "@lib/xm.l")
(let Sections (body (in "file.xml" (xml)))
(pretty (car (body (car Sections))))
(prinl)
(for S Sections
(for L (body S)
(prinl (car (body L 'price))) ) )
(make
(for S Sections
(for L (body S)
(link (car (body L 'name))) ) ) ) ) | Give a code snippet in #PicoLisp
Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Stor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
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 |... | #Arturo | Arturo | x: 2
xInfo: info.get 'x
print [
"address of x:" xInfo\address
"->" from.hex xInfo\address
] | Give a code snippet in #Arturo
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Ring | Ring |
# Project : Digital root/Multiplicative digital root
load "stdlib.ring"
root = newlist(10, 5)
for r = 1 to 10
for x = 1 to 5
root[r][x] = 0
next
next
root2 = list(10)
for y = 1 to 10
root2[y] = 0
next
see "Number MDR MP" + nl
num = [123321, 7739, 893, 899998]
digroot(num)
see nl
num = 0:... | Give a code snippet in #Ring
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pi... | #J | J | load'viewmat'
NB. size=. 2{.".wd'qm' NB. J6
NB. size=. getscreenwh_jgtk_ '' NB. J7
size=. 3{".wd'qscreen' NB. J8
'rgb'viewmat- (4<.@%~{:size)# ({.size) $&> 1 2 3 4#&.> <0 1 | Give a code snippet in #J
Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #LabVIEW | LabVIEW | define gcd(a,b) => {
while(#b != 0) => {
local(t = #b)
#b = #a % #b
#a = #t
}
return #a
}
define lcm(m,n) => {
#m == 0 || #n == 0 ? return 0
local(r = (#m * #n) / decimal(gcd(#m, #n)))
return integer(#r)->abs
}
lcm(-6, 14)
lcm(2, 0)
lcm(12, 18)
lcm(12, 22)
lcm(7, 31) | Give a code snippet in #LabVIEW
Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that h... | 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... | #Phix | Phix | with javascript_semantics
function arithmetic_mean(sequence s)
return sum(s)/length(s)
end function
function geometric_mean(sequence s)
return power(product(s),1/length(s))
end function
function harmonic_mean(sequence s)
return length(s)/sum(sq_div(1,s))
end function
constant s = {1,2,3,4,5,6,7,8,9,10... | Give a code snippet in #Phix
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/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET D$="Benjamin"
20 PRINT "There is just one dog named ";d$ | Give a code snippet in #ZX_Spectrum_Basic
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Aime | Aime | void
__swap(&, &,,)
{
set(0, $3);
set(1, $2);
}
void
swap(&, &)
{
xcall(xcall, __swap);
} | Give a code snippet in #Aime
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity... | 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.
| #Delphi | Delphi |
program Sequence_of_non_squares;
uses
System.SysUtils, System.Math;
function nonsqr(i: Integer): Integer;
begin
Result := Trunc(i + Floor(0.5 + Sqrt(i)));
end;
var
i: Integer;
j: Double;
begin
for i := 1 to 22 do
write(nonsqr(i), ' ');
Writeln;
for i := 1 to 999999 do
begin
j := Sq... | Give a code snippet in #Delphi
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 A0000... | christopher/rosetta-code | |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one dow... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Bottle[n_] := ToString[n] <> If[n==1," bottle"," bottles"] <> " of beer"
BottleSong[n_] := Speak[
Bottle[n] <> " on the wall," <>
Bottle[n] <>
", take one down, pass it around," <>
Bottle[n-1] <> " on the wall."
]
BottleSong /@ Range[99,1,-1] | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/MAC_Vendor_Lookup | MAC Vendor Lookup | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or numerous) APIs that exist on the i... | #Arturo | Arturo | loop ["FC-A1-3E" "FC:FB:FB:01:FA:21" "BC:5F:F4"] 'mac [
print [mac "=>" read ~"http://api.macvendors.com/|mac|"]
pause 1500
] | Give a code snippet in #Arturo
Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
Task
Interface with one (or nu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Axe | Axe | While 1
Disp "SPAM",i
End | Give a code snippet in #Axe
Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Brace_expansion | Brace expansion | Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified.
Task[edit]
W... | #Nim | Nim | proc expandBraces(str: string) =
var
escaped = false
depth = 0
bracePoints: seq[int]
bracesToParse: seq[int]
for idx, ch in str:
case ch
of '\\':
escaped = not escaped
of '{':
inc depth
if not escaped and depth == 1:
bracePoints = @[idx]
of ',':
if... | Give a code snippet in #Nim
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #Smalltalk | Smalltalk | "We use one variable, called n. Let it initially be equal to 1. Then keep increasing it by 1 for only as long as the remainder after dividing by a million is not equal to 269,696; finally, show the value of n."
| n |
n := 1.
[ n squared \\ 1000000 = 269696 ] whileFalse: [ n := n + 1 ].
n | Give a code snippet in #Smalltalk
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic ... | 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... | #Zig | Zig | const std = @import("std");
pub fn main() !void {
const cnt_lower = 26;
var lower: [cnt_lower]u8 = undefined;
comptime var i = 0;
inline while (i < cnt_lower) : (i += 1)
lower[i] = i + 'a';
const stdout_wr = std.io.getStdOut().writer();
for (lower) |l|
try stdout_wr.print("{c... | Give a code snippet in #Zig
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 re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
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
... | #Nim | Nim | import algorithm
var a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]
a.sort(Ascending)
for x in a:
echo x | Give a code snippet in #Nim
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/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "First 20 Cullen numbers:" + nl
for n = 1 to 20
num = n*pow(2,n)+1
see "" + num + " "
next
see nl + nl + "First 20 Woodall numbers:" + nl
for n = 1 to 20
num = n*pow(2,n)-1
see "" + num + " "
next
see nl + "done..." + nl
| Give a code snippet in #Ring
A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Tailspin | Tailspin |
templates palindrome
[$...] -> #
when <=$(last..first:-1)> do '$...;' !
end palindrome
test 'palindrome filter'
assert 'rotor' -> palindrome <='rotor'> 'rotor is a palindrome'
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
end 'palindrome filter'
| Give a code snippet in #Tailspin
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #BBC_BASIC | BBC BASIC | REM >oldlady
DIM swallowings$(6, 1)
swallowings$() = "fly", "+why", "spider", "That wriggled and wiggled and tickled inside her", "bird", ":How absurd", "cat", ":Fancy that", "dog", ":What a hog", "cow", "+how", "horse", "She's dead, of course"
FOR i% = 0 TO 6
PRINT "There was an old lady who swallowed a "; swallowin... | Give a code snippet in #BBC_BASIC
Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical ou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Globally_replace_text_in_several_files | Globally replace text in several files | Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| #C.23 | C# |
using System.Collections.Generic;
using System.IO;
class Program {
static void Main() {
var files = new List<string> {
"test1.txt",
"test2.txt"
};
foreach (string file in files) {
File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!"... | Give a code snippet in #C.23
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| 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
| #Scala | Scala | (load "filename") | Give a code snippet in #Scala
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/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Sidef | Sidef | const rps = %w(r p s)
const msg = [
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
]
say <<"EOT"
\n>> Rock Paper Scissors <<\n
** Enter 'r', 'p', or 's' as your play.
** Enter 'q' to exit the game.
** Running score shown as <your wins>:<my wins>
EOT
var plays = 0
var aScore = 0
... | Give a code snippet in #Sidef
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #C.2B.2B | C++ | #include <iostream>
#include <gmpxx.h>
static bool is_mersenne_prime(mpz_class p)
{
if( 2 == p )
return true;
else
{
mpz_class s(4);
mpz_class div( (mpz_class(1) << p.get_ui()) - 1 );
for( mpz_class i(3); i <= p; ++i )
... | Give a code snippet in #C.2B.2B
Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
Th... | #ABAP | ABAP | REPORT Z_DECODE_URL.
DATA: lv_encoded_url TYPE string VALUE 'http%3A%2F%2Ffoo%20bar%2F',
lv_decoded_url TYPE string.
CALL METHOD CL_HTTP_UTILITY=>UNESCAPE_URL
EXPORTING
ESCAPED = lv_encoded_url
RECEIVING
UNESCAPED = lv_decoded_url.
WRITE: 'Encoded URL: ', lv_encoded_url, /, 'Decoded URL: ', lv... | Give a code snippet in #ABAP
This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #Java | Java |
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
public class PythTrip{
public static void main(String[] args){
long tripCount = 0, primCount = 0;
//change this to whatever perimeter limit you want;the RAM's the limit
BigInteger periLimit = BigInteger.valueOf(100)... | Give a code snippet in #Java
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displ... | 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... | #ALGOL_W | ALGOL W | begin
% long multiplication of large integers %
% large integers are represented by arrays of integers whose absolute %
% values are in 0 .. ELEMENT_MAX - 1 %
% negative large integers should have negative values in all non-zero %
... | Give a code snippet in #ALGOL_W
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/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Quackery | Quackery |
[ dup char A char [ within
swap char a char { within
or ] is letter ( c --> b )
[ 0 26 of swap witheach
[ dup letter iff
[ 1 unrot lower
char a - poke ]
else drop ]
0 swap find 26 = ] is pangram ( $ --> b )
$ "This is a sentenc... | Give a code snippet in #Quackery
Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Phix | Phix | with javascript_semantics
atom t0 = time()
include mpfr.e
procedure cullen(mpz r, integer n)
mpz_ui_pow_ui(r,2,n)
mpz_mul_si(r,r,n)
mpz_add_si(r,r,1)
end procedure
procedure woodall(mpz r, integer n)
cullen(r,n)
mpz_sub_si(r,r,2)
end procedure
sequence c = {}, w = {}
mpz z = mpz_init()
for i=1 ... | Give a code snippet in #Phix
A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Maple | Maple | 5^3^2;
(5^3)^2;
5^(3^2); | Give a code snippet in #Maple
This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #QBasic | QBasic | w = 254
SCREEN 13
VIEW (0, 0)-(w / 2, w / 2), , 0
FOR x = 0 TO w
FOR y = 0 TO w
COLOR ((x XOR y) AND 255)
PSET (x, y)
NEXT y
NEXT x | Give a code snippet in #QBasic
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/syntax_analyzer | Compiler/syntax analyzer | A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened format.
The program should read in... | #Scala | Scala |
package xyz.hyperreal.rosettacodeCompiler
import scala.io.Source
object SyntaxAnalyzer {
val symbols =
Map[String, (PrefixOperator, InfixOperator)](
"Op_or" -> (null, InfixOperator(10, LeftAssoc, BranchNode("Or", _, _))),
"Op_and" -> (null, InfixOperator(20, LeftAssoc, Branc... | Give a code snippet in #Scala
A Syntax analyzer transforms a token stream (from the Lexical analyzer)
into a Syntax tree, based on a grammar.
Task[edit]
Take the output from the Lexical analyzer task,
and convert it to an Abstract Syntax Tree (AST),
based on the grammar below. The output should be in a flattened form... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #Common_Lisp | Common Lisp | (defmacro toggle (gv) `(setf ,gv (not ,gv)))
(defun langtons-ant (width height start-x start-y start-dir)
(let ( (grid (make-array (list width height)))
(x start-x)
(y start-y)
(dir start-dir) )
(loop while (and (< -1 x width) (< -1 y height)) do
(if (toggle (aref grid x y))
... | Give a code snippet in #Common_Lisp
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, wi... | 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... | #Lambdatalk | Lambdatalk |
1) FUNCTIONS
{def left_rect {lambda {:f :x :h} {:f :x}}}
-> left_rect
{def mid_rect {lambda {:f :x :h} {:f {+ :x {/ :h 2}}}}}
-> mid_rect
{def right_rect {lambda {:f :x :h} {:f {+ :x :h}}}}
-> right_rect
{def trapezium {lambda {:f :x :h} {/ {+ {:f :x} {:f {+ :x :h}}} 2}}}
-> trapezium
{def simpson
{lamb... | Give a code snippet in #Lambdatalk
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 ... | 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... | #Ruby | Ruby | require 'raster_graphics'
class RGBColour
# the difference between two colours
def -(a_colour)
(@red - a_colour.red).abs +
(@green - a_colour.green).abs +
(@blue - a_colour.blue).abs
end
end
class Pixmap
# the difference between two images
def -(a_pixmap)
if @width != a_pixmap.width or @he... | Give a code snippet in #Ruby
basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The exp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Raku | Raku | subset SqMat of Array where { .elems == all(.[]».elems) }
multi infix:<*>(SqMat $a, SqMat $b) {[
for ^$a -> $r {[
for ^$b[0] -> $c {
[+] ($a[$r][] Z* $b[].map: *[$c])
}
]}
]}
multi infix:<**> (SqMat $m, Int $n is copy where { $_ >= 0 }) {
my $tmp = $m;
my $out = [for ^$m ... | Give a code snippet in #Raku
Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Standard_ML | Standard ML | structure Operator = struct
datatype associativity = LEFT | RIGHT
type operator = { symbol : char, assoc : associativity, precedence : int }
val operators : operator list = [
{ symbol = #"^", precedence = 4, assoc = RIGHT },
{ symbol = #"*", precedence = 3, assoc = LEFT },
{ symbol = #"/", precedenc... | Give a code snippet in #Standard_ML
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 re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th... | #Nim | Nim | import strutils
const
# Define int constants instead of an enum to use only ints and strings.
Shorter = -1
SameLength = 0
Longer = 1
type LengthComparison = range[Shorter..Longer]
func cmpLength(a, b: string): LengthComparison =
let a = repeat(' ', a.len)
let b = repeat(' ', b.len)
result = if a i... | Give a code snippet in #Nim
Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim s As String = "123456789"
Dim As Integer n = 3, m = 4
Print Mid(s, n, m)
Print Mid(s, n)
Print Left(s, Len(s) - 1)
'start from "5" say
Print Mid(s, Instr(s, "5"), m)
' start from "12" say
Print Mid(s, Instr(s, "12"), m)
Sleep | Give a code snippet in #FreeBASIC
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/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
... | #Fantom | Fantom |
using concurrent
class Main
{
public static Void main ()
{
echo ("Enter a time to sleep: ")
input := Env.cur.in.readLine
try
{
time := Duration.fromStr (input)
echo ("sleeping ...")
Actor.sleep (time)
echo ("awake!")
}
catch
{
echo ("Invalid time entered... | Give a code snippet in #Fantom
Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main threa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #JavaScript | JavaScript | setrand(3)
random(6)+1
\\ chosen by fair dice roll.
\\ guaranteed to the random. | Give a code snippet in #JavaScript
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the alg... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #Common_Lisp | Common Lisp | (ql:quickload 'ironclad)
(defun sha-256 (str)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :sha256
(ironclad:ascii-string-to-byte-array str))))
(sha-256 "Rosetta code") | Give a code snippet in #Common_Lisp
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the foll... | #Oz | Oz | declare
fun {CommonPrefix Sep Paths}
fun {GetParts P} {String.tokens P Sep} end
Parts = {ZipN {Map Paths GetParts}}
EqualParts = {List.takeWhile Parts fun {$ X|Xr} {All Xr {Equals X}} end}
in
{Join Sep {Map EqualParts Head}}
end
fun {ZipN Xs}
if {Some Xs {Equals nil}} then nil
el... | Give a code snippet in #Oz
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the dire... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Julia | Julia | function B10(n)
for i in Int128(1):typemax(Int128)
q, b10, place = i, zero(Int128), one(Int128)
while q > 0
q, r = divrem(q, 2)
if r != 0
b10 += place
end
place *= 10
end
if b10 % n == 0
return b10
en... | Give a code snippet in #Julia
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #PARI.2FGP | PARI/GP | VdC(n)=n=binary(n);sum(i=1,#n,if(n[i],1.>>(#n+1-i)));
VdC(n)=sum(i=1,#binary(n),if(bittest(n,i-1),1.>>i)); \\ Alternate approach
vector(10,n,VdC(n)) | Give a code snippet in #PARI.2FGP
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
$ include "getf.s7i";
$ include "time.s7i";
const string: noteFileName is "NOTES.TXT";
const proc: main is func
local
var file: note is STD_NULL;
begin
if length(argv(PROGRAM)) = 0 then
# write NOTES.TXT
write(getf(noteFileName));
else
# Write date & time ... | Give a code snippet in #Seed7
Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Java | Java | public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static void main(String[] args) {
long fact = 1;
double e = 2.0;
int n = 2;
double e0;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.abs... | Give a code snippet in #Java
Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-... | #Rust | Rust |
#[derive(Debug, Clone)]
struct Point {
x: f32,
y: f32
}
fn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> {
//There must be at least 3 points
if points.len() < 3 { return points.clone(); }
let mut hull = vec![];
//Find the left most point in the polygon
let (left_most_idx, ... | Give a code snippet in #Rust
Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | perms[0] = {{{}, 1}};
perms[n_] :=
Flatten[If[#2 == 1, Reverse, # &]@
Table[{Insert[#1, n, i], (-1)^(n + i) #2}, {i, n}] & @@@
perms[n - 1], 1]; | Give a code snippet in #Mathematica.2FWolfram_Language
Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Perl | Perl | #!perl
use strict;
use warnings qw(FATAL all);
my @initial = split /\n/, <<'';
#############
# # #
# $$$$$$$ @#
#....... #
#############
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
=for
space is an empty square
# is a wall
@ is the player
$ is a box
. is a goal
+ is the player on a g... | Give a code snippet in #Perl
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #Scala | Scala | import scala.annotation.tailrec
import scala.collection.mutable
object PrimeConspiracy extends App {
val limit = 1000000
val sieveTop = 15485863/*one millionth prime*/ + 1
val buckets = Array.ofDim[Int](10, 10)
var prevPrime = 2
def sieve(limit: Int) = {
val composite = new mutable.BitSet(sieveTop)
... | Give a code snippet in #Scala
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferen... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem | Primality by Wilson's theorem | Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
| #Swift | Swift | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...... | Give a code snippet in #Swift
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.