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
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#C.2B.2B
C++
#include <algorithm> // for std::swap #include <cstddef> #include <cassert>   // Matrix traits: This describes how a matrix is accessed. By // externalizing this information into a traits class, the same code // can be used both with native arrays and matrix classes. To use the // default implementation of the traits c...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#C.23
C#
using System;   class Program { static void Main(string[] args) { Console.WriteLine(Math.E); //E Console.WriteLine(Math.PI); //PI Console.WriteLine(Math.Sqrt(10)); //Square Root Console.WriteLine(Math.Log(10)); // Logarithm Console.WriteLine(Math.Log10(10)); // Base 1...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Go
Go
package main   import ( "bytes" "errors" "fmt" "io/ioutil" "os" )   func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } }   func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. lin...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Crystal
Crystal
content = File.read("input.txt") puts content
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#D
D
import std.file: read, readText;   void main() { // To read a whole file into a dynamic array of unsigned bytes: auto data = cast(ubyte[])read("unixdict.txt");   // To read a whole file into a validated UTF-8 string: string txt = readText("unixdict.txt"); }
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#jq
jq
def is_rep_string: # if self is a rep-string then return [n, prefix] # where n is the number of full occurrences of prefix def _check(prefix; n; sofar): length as $length | if length <= (sofar|length) then [n, prefix] else (sofar+prefix) as $sofar | if startswith($sofar) then _check(prefix; n...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Julia
Julia
function repstring(r::AbstractString) n = length(r) replst = String[] for m in 1:n÷2 s = r[1:chr2ind(r, m)] if (s ^ cld(n, m))[1:chr2ind(r, n)] != r continue end push!(replst, s) end return replst end   tests = ["1001110011", "1110111011", "0010010010", "1010101010", "1111111...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { val s1 = "I am the original string" val r1 = Regex("^.*string$") if (s1.matches(r1)) println("`$s1` matches `$r1`") val r2 = Regex("original") val s3 = "replacement" val s2 = s1.replace(r2, s3) if (s2 != s1) println("`$s2` replaces `$r2` wit...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Brat
Brat
p "olleh".reverse #Prints "hello"
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#PureBasic
PureBasic
Prototype.i fun(x.i)   Procedure.i quark(z.i) Debug "Quark "+Str(z) : ProcedureReturn z-1 EndProcedure   Procedure rep(q.fun,n.i) Repeat : n=q(n) : Until n=0 EndProcedure   rep(@quark(),3)
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Python
Python
#!/usr/bin/python def repeat(f,n): for i in range(n): f();   def procedure(): print("Example");   repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#MAXScript
MAXScript
-- Here renameFile "input.txt" "output.txt" -- Root renameFile "/input.txt" "/output.txt"
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Mercury
Mercury
:- module rename_file. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module dir.   main(!IO) :- rename_file("input.txt", "output.txt", !IO), rename_file("docs", "mydocs", !IO), rename_file("/input.txt", "/output.txt", !IO), rename_file("/docs"...
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Logo
Logo
do.until [ make "line readlist print reverse :line ] [word? :line] bye
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Lua
Lua
  local lines = {} for line in (s .. "\n"):gmatch("(.-)\n") do local this = {} for word in line:gmatch("%S+") do table.insert(this, 1, word) end lines[#lines + 1] = table.concat(this, " ") end print(table.concat(lines, "\n"))  
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...
#Rust
Rust
fn rot13(string: &str) -> String { string.chars().map(|c| { match c { 'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char, 'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char, _ => c } }).collect() }   fn main () { assert_eq!(rot13("abc"), "nop"); }
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#REXX
REXX
roman: procedure arg number   /* handle only 1 to 3999, else return ? */ if number >= 4000 | number <= 0 then return "?"   romans = " M CM D CD C XC L XL X IX V IV I" arabic = "1000 900 500 400 100 90 50 40 10 9 5 4 1"   result = "" do i = 1 to words(romans) do while number >= word(arabic,i) r...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#True_BASIC
True BASIC
FUNCTION romtodec(roman$) LET num = 0 LET prenum = 0 FOR i = LEN(roman$) TO 1 STEP -1 LET x$ = (roman$)[i:i+1-1] LET n = 0 IF x$ = "M" THEN LET n = 1000 IF x$ = "D" THEN LET n = 500 IF x$ = "C" THEN LET n = 100 IF x$ = "L" THEN LET n = 50 IF x$ = "X" T...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   public program() { var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter()) }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#MATLAB_.2F_Octave
MATLAB / Octave
function [a,b,c]=foo(d) a = 1-d; b = 2+d; c = a+b; end; [x,y,z] = foo(5)
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Maxima
Maxima
f(a, b) := [a * b, a + b]$   [u, v]: f(5, 6); [30, 11]
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(remove-duplicates '(1 3 2 9 1 2 3 8 8 1 0 2)) > (9 3 8 1 0 2)
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#JavaScript
JavaScript
(() => { const main = () => {   console.log( 'First 15 Recaman:\n' + recamanUpto(i => 15 === i) );   console.log( '\n\nFirst duplicated Recaman:\n' + last(recamanUpto( (_, set, rs) => set.size !== rs.length )) ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Common_Lisp
Common Lisp
(defun convert-to-row-echelon-form (matrix) (let* ((dimensions (array-dimensions matrix)) (row-count (first dimensions)) (column-count (second dimensions)) (lead 0)) (labels ((find-pivot (start lead) (let ((i start)) (loop :while (zerop (aref matrix i lead)) :do (progn (incf i)...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#C.2B.2B
C++
#include <iostream> #include <cmath>   #ifdef M_E static double euler_e = M_E; #else static double euler_e = std::exp(1); // standard fallback #endif   #ifdef M_PI static double pi = M_PI; #else static double pi = std::acos(-1); #endif   int main() { std::cout << "e = " << euler_e << "\npi = " << pi ...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Groovy
Groovy
static def removeLines(String filename, int startingLine, int lineCount) { def sourceFile = new File(filename).getAbsoluteFile() def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())   outputFile.withPrintWriter { outputWriter -> sourceFile.eachLine { line, lineNumber ->...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Delphi
Delphi
program ReadAll;   {$APPTYPE CONSOLE}   uses Classes;   var i: Integer; lList: TStringList; begin lList := TStringList.Create; try lList.LoadFromFile('c:\input.txt'); // Write everything at once Writeln(lList.Text); // Write one line at a time for i := 0 to lList.Count - 1 do Writeln(l...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :filecontents !decode!utf-8 !read "file.txt"
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Kotlin
Kotlin
// version 1.0.6   fun repString(s: String): MutableList<String> { val reps = mutableListOf<String>() if (s.length < 2) return reps for (c in s) if (c != '0' && c != '1') throw IllegalArgumentException("Not a binary string") for (len in 1..s.length / 2) { val t = s.take(len) val n = s.le...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#langur
langur
if matching(re/abc/, "somestring") { ... }
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Lasso
Lasso
local(mytext = 'My name is: Stone, Rosetta My name is: Hippo, Campus ')   local(regexp = regexp( -find = `(?m)^My name is: (.*?), (.*?)$`, -input = #mytext, -replace = `Hello! I am $2 $1`, -ignorecase ))     while(#regexp -> find) => {^ #regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim&) + '<br />...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Burlesque
Burlesque
  "Hello, world!"<-  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Quackery
Quackery
[ stack ] is times.start ( --> s ) protect times.start   [ stack ] is times.count ( --> s ) protect times.count   [ stack ] is times.action ( --> s ) protect times.action   [ ]'[ times.action put dup times.start put [ ...
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#MUMPS
MUMPS
 ;Local S X=$ZF(-1,"rename input.txt output.txt") S X=$ZF(-1,"rename docs.dir mydocs.dir")  ;Root of current device S X=$ZF(-1,"rename [000000]input.txt [000000]output.txt") S X=$ZF(-1,"rename [000000]docs.dir [000000]mydocs.dir")
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   runSample(arg) return   -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method isFileRenamed(oldFile, newFile) public static returns boolean fo = File(oldFile) fn = File(newFile) fRenamed = fo.renameTo(fn...
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Maple
Maple
while (true) do input := readline("input.txt"): if input = 0 then break: fi: input := StringTools:-Trim(input): # remove leading/trailing space input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "): printf("%s\n", input): od:
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
poem = "---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------"; lines = StringSplit[poem, "\n"]; wordArray = Stri...
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...
#S-BASIC
S-BASIC
  comment Return the rot13 transformation of s, preserving case and passing non-alphabetic characters without change end   function rot13(s = string) = string var i, k = integer var ch = char var normal, rotated = string normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" rotated = "NOPQRSTUV...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Ring
Ring
  arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roman = ["M", "CM", "D", "CD", "C" ,"XC", "L", "XL" ,"X", "IX", "V", "IV", "I"]   see "2009 = " + toRoman(2009) + nl see "1666 = " + toRoman(1666) + nl see "3888 = " + toRoman(3888) + nl   func toRoman val result = "" for i = 1 to 13 ...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT LOOP roman_number="MCMXC'MMVIII'MDCLXVI" arab_number=DECODE (roman_number,ROMAN) PRINT "Roman number ",roman_number," equals ", arab_number ENDLOOP
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Elixir
Elixir
  String.duplicate("ha", 5)  
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Emacs_Lisp
Emacs Lisp
(apply 'concat (make-list 5 "ha"))
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Mercury
Mercury
:- module addsub.   :- interface. :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list, string.   main(!IO) :- command_line_arguments(Args, !IO), filter_map(to_int, Args, CleanArgs), (length(CleanArgs, 2) -> X = det_index1(CleanArgs,1), Y ...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#min
min
(over over / '* dip) :muldiv
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Crystal
Crystal
ary = [1, 1, 2, 2, "a", [1, 2, 3], [1, 2, 3], "a"] p ary.uniq
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#jq
jq
  # Let R[n] be the Recaman sequence, n >= 0, so R[0]=0. # Input: a number, $required, specifying the required range of integers, [1 .. $required] # to be covered by R[0] ... R[.n] # $capture: the number of elements of the sequence to retain. # Output: an object as described below. # Note that .a|length will be ...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Julia
Julia
function recaman() a = Vector{Int}([0]) used = Dict{Int, Bool}(0 => true) used1000 = Set(0) founddup = false termcount = 1 while length(used1000) <= 1000 nextterm = a[termcount] - termcount if nextterm < 1 || haskey(used, nextterm) nextterm += termcount + termcount ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#D
D
import std.stdio, std.algorithm, std.array, std.conv;   void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc { if (M.empty) return; immutable nrows = M.length; immutable ncols = M[0].length;   size_t lead; foreach (immutable r; 0 .. nrows) { if (ncols <= lead) retu...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Chef
Chef
(Math/E); //e (Math/PI); //pi (Math/sqrt x); //square root--cube root also available (cbrt) (Math/log x); //natural logarithm--log base 10 also available (log10) (Math/exp x); //exponential (Math/abs x); //absolute value (Math/floor x); //floor (Math/ceil x); //ceiling (Math/pow x y); //power
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Clojure
Clojure
(Math/E); //e (Math/PI); //pi (Math/sqrt x); //square root--cube root also available (cbrt) (Math/log x); //natural logarithm--log base 10 also available (log10) (Math/exp x); //exponential (Math/abs x); //absolute value (Math/floor x); //floor (Math/ceil x); //ceiling (Math/pow x y); //power
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Haskell
Haskell
import System.Environment (getArgs)   main = getArgs >>= (\[a, b, c] -> do contents <- fmap lines $ readFile a let b1 = read b :: Int c1 = read c :: Int putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents] )
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#E
E
<file:foo.txt>.getText()
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Elixir
Elixir
  defmodule FileReader do # Read in the file def read(path) do case File.read(path) do {:ok, body} -> IO.inspect body {:error,reason} ->  :file.format_error(reason) end end   # Open the file path, then read in the file def bit_read(path) do case File.open(path) do ...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#LFE
LFE
  (defun get-reps (text) (lists:filtermap (lambda (x) (case (get-rep text (lists:split x text)) ('() 'false) (x `#(true ,x)))) (lists:seq 1 (div (length text) 2))))   (defun get-rep ((text `#(,head ,tail)) (case (string:str text tail) (1 head) (_ '()))))  
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Lua
Lua
test = "My name is Lua." pattern = ".*name is (%a*).*"   if test:match(pattern) then print("Name found.") end   sub, num_matches = test:gsub(pattern, "Hello, %1!") print(sub)
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { declare global ObjRegEx "VBscript.RegExp" Function RegEx.Replace$(from$, what$) { Method ObjRegEx, "Replace", from$, what$ as response$ =response$ } Function RegEx.Test(what$) { Method ObjRegEx, "Test", what$ as response =respons...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <wchar.h>   const char *sa = "abcdef"; const char *su = "as⃝df̅"; /* Should be in your native locale encoding. Mine is UTF-8 */   int is_comb(wchar_t c) { if (c >= 0x300 && c <= 0x36f) return 1; if (c >= 0x1dc0 && c <= 0x1dff) return 1; if (c >= 0x2...
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#R
R
  f1 <- function(...){print("coucou")}   f2 <-function(f,n){ lapply(seq_len(n),eval(f)) }   f2(f1,4)  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Racket
Racket
#lang racket/base (define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket (for ((_ n)) (f)))   (define (repeat2 f n) ; This is a bit more "functional programmingy" (when (positive? n) (f) (repeat2 f (sub1 n))))   (display "...") (repeat (λ () (display " and over")) 5) (display "...") ...
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#NewLISP
NewLISP
(rename-file "./input.txt" "./output.txt") (rename-file "./docs" "./mydocs") (rename-file "/input.txt" "/output.txt") (rename-file "/docs" "/mydocs")
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Nim
Nim
import os   moveFile("input.txt", "output.txt") moveFile("docs", "mydocs")   moveFile(DirSep & "input.txt", DirSep & "output.txt") moveFile(DirSep & "docs", DirSep & "mydocs")
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#MATLAB_.2F_Octave
MATLAB / Octave
function testReverseWords testStr = {'---------- Ice and Fire ------------' ; ... ''  ; ... 'fire, in end will world the say Some'  ; ... 'ice. in say Some'  ; ... 'desire of tasted I''ve what From'  ...
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...
#S-lang
S-lang
variable old = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; variable new = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";   define rot13(s) { s = strtrans(s, old, new); return s; }   define rot13_stream(s) { variable ln; while (-1 != fgets(&ln, s)) fputs(rot13(ln), stdout); }   if (__arg...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Ruby
Ruby
Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' } Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]   def roman(num) return Symbols[num] if Symbols.has_key?(num) Subtractors.each do |cutPoint, subtractor| return roman(cutPoint) + roman(num - cu...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#UNIX_Shell
UNIX Shell
  #!/bin/bash   roman_to_dec() { local rnum=$1 local n=0 local prev=0   for ((i=${#rnum}-1;i>=0;i--)) do case "${rnum:$i:1}" in M) a=1000 ;; D) a=500 ;; C) a=100 ;; L) a=50 ;; X) a=10 ;; V) a=5 ;; I) a=1 ;; esac   if [[ $a -lt $prev ]] then let n-=a ...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Erlang
Erlang
repeat(X,N) -> lists:flatten(lists:duplicate(N,X)).
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Assertions;   module MultReturn { MinMax[T] (ls : list[T]) : T * T where T : IComparable requires ls.Length > 0 otherwise throw ArgumentException("An empty list has no extreme values.") { def greaterOf(a, b) { if (a.CompareTo(b) > 0) a else b...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RReturnMultipleVals public properties constant L = 'L' R = 'R' K_lipsum = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do ...
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
void main() { import std.stdio, std.algorithm;   [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2] .sort() .uniq .writeln; }
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Kotlin
Kotlin
// Version 1.2.60   fun main(args: Array<String>) { val a = mutableListOf(0) val used = mutableSetOf(0) val used1000 = mutableSetOf(0) var foundDup = false var n = 1 while (n <= 15 || !foundDup || used1000.size < 1001) { var next = a[n - 1] - n if (next < 1 || used.contains(next)...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Euphoria
Euphoria
function ToReducedRowEchelonForm(sequence M) integer lead,rowCount,columnCount,i sequence temp lead = 1 rowCount = length(M) columnCount = length(M[1]) for r = 1 to rowCount do if columnCount <= lead then exit end if i = r while M[i][lead] = 0 do ...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#COBOL
COBOL
E *> e PI *> Pi SQRT(n) *> Sqaure root LOG(n) *> Natural logarithm LOG10(n) *> Logarithm (base 10) EXP(n) *> e to the nth power ABS(n) *> Absolute value INTEGER(n) *> While not a proper floor function, it is implemented in the same way. *> There is no ceiling function. However, it coul...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Icon_and_Unicon
Icon and Unicon
procedure main() # remove lines removelines("foo.bar",3,2) | stop("Failed to remove lines.") end   procedure removelines(fn,start,skip)   f := open(fn,"r") | fail # open to read every put(F := [],|read(f)) # file to list close(f)   if *F < start-1+skip then fail every F[...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Emacs_Lisp
Emacs Lisp
(setq my-variable (with-temp-buffer (insert-file-contents "foo.txt") (buffer-string)))
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Erlang
Erlang
{ok, B} = file:read_file("myfile.txt").
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Maple
Maple
repstr? := proc( s :: string ) local per := StringTools:-Period( s ); if 2 * per <= length( s ) then true, s[ 1 .. per ] else false, "" end if end proc:
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RepStringQ[strin_String]:=StringCases[strin,StartOfString~~Repeated[x__,{2,\[Infinity]}]~~y___~~EndOfString/;StringMatchQ[x,StartOfString~~y~~___]:>x, Overlaps -> All]
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#M4
M4
regexp(`GNUs not Unix', `\<[a-z]\w+') regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Maple
Maple
#Examples from Maple Help StringTools:-RegMatch("^ab+bc$", "abbbbc"); StringTools:-RegMatch("^ab+bc$", "abbbbcx"); StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2"); StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#C.23
C#
static string ReverseString(string input) { char[] inputChars = input.ToCharArray(); Array.Reverse(inputChars); return new string(inputChars); }
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Raku
Raku
sub repeat (&f, $n) { f() xx $n };   sub example { say rand }   repeat(&example, 3);
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Objeck
Objeck
  use IO; bundle Default { class FileExample { function : Main(args : String[]) ~ Nil { File->Rename("input.txt", "output.txt"); File->Rename("docs", "mydocs"); File->Rename("/input.txt", "/output.txt"); File->Rename("/docs", "/mydocs"); } } }  
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#MAXScript
MAXScript
  -- MAXScript : Reverse words in a string : N.H. 2019 -- ( text = stringstream "---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------\n" ...
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...
#Scala
Scala
scala> def rot13(s: String) = s map { | case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar | case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar | case c => c | } rot13: (s: String)String   scala> rot13("7 Cities of Gold.") res61: String = 7 Pvgvrf bs Tbyq.   scala> ro...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Run_BASIC
Run BASIC
[loop] input "Input value:";val$ print roman$(val$) goto [loop]   ' ------------------------------ ' Roman numerals ' ------------------------------ FUNCTION roman$(val$) a2r$ = "M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1" v = val(val$) for i = 1 to 13 r$ = word$(a2r$,i,",") a = val...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#VBA
VBA
  Option Explicit   Sub Main_Romans_Decode() Dim Arr(), i&   Arr = Array("III", "XXX", "CCC", "MMM", "VII", "LXVI", "CL", "MCC", "IV", "IX", "XC", "ICM", "DCCCXCIX", "CMI", "CIM", "MDCLXVI", "MCMXC", "MMXVII") For i = 0 To UBound(Arr) Debug.Print Arr(i) & " >>> " & lngConvert(CStr(Arr(i))) Next En...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#ERRE
ERRE
  PROCEDURE REPEAT_STRING(S$,N%->REP$) LOCAL I% REP$="" FOR I%=1 TO N% DO REP$=REP$+S$ END FOR END PROCEDURE  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Nim
Nim
proc addsub(x, y: int): (int, int) = (x + y, x - y)   var (a, b) = addsub(12, 15)
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Objeck
Objeck
class Program { function : Main(args : String[]) ~ Nil { a := IntHolder->New(3); b := IntHolder->New(7); Addon(a,b); a->Get()->PrintLine(); b->Get()->PrintLine(); }   function : Addon(a : IntHolder, b : IntHolder) ~ Nil { a->Set(a->Get() + 2); b->Set(b->Get() + 13); } }
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Delphi
Delphi
program RemoveDuplicateElements;   {$APPTYPE CONSOLE}   uses Generics.Collections;   var i: Integer; lIntegerList: TList<Integer>; const INT_ARRAY: array[1..7] of Integer = (1, 2, 2, 3, 4, 5, 5); begin lIntegerList := TList<Integer>.Create; try for i in INT_ARRAY do if not lIntegerList.Contains(i) then ...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Lua
Lua
local a = {[0]=0} local used = {[0]=true} local used1000 = {[0]=true} local foundDup = false local n = 1   while n<=15 or not foundDup or #used1000<1001 do local nxt = a[n - 1] - n if nxt<1 or used[nxt] ~= nil then nxt = nxt + 2 * n end local alreadyUsed = used[nxt] ~= nil table.insert(a, nx...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Factor
Factor
USE: math.matrices.elimination { { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Common_Lisp
Common Lisp
  (exp 1) ; e (Euler's number) pi ; pi constant (sqrt x) ; square root: works for negative reals and complex (log x) ; natural logarithm: works for negative reals and complex (log x 10) ; logarithm base 10 (exp x) ; exponential (abs x) ; absolute value: result exact if input exact: (abs -1/...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#J
J
removeLines=: 4 :0 'count start'=. x file=. boxxopen y lines=. <;.2 fread file (;lines {~ <<< (start-1)+i.count) fwrite file )
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Euphoria
Euphoria
  function load_file(sequence filename) integer fn,c sequence data fn = open(filename,"r") -- "r" for text files, "rb" for binary files if (fn = -1) then return {} end if -- failed to open the file   data = {} -- init to empty sequence c = getc(fn) -- prime the char buffer while (c != -1) do -- ...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Modula-2
Modula-2
MODULE RepStrings; FROM InOut IMPORT Write, WriteString, WriteLn, WriteCard; FROM Strings IMPORT Copy, Length;   (* Find the length of the longest rep-string given a string. If there is no rep-string, the result is 0. *) PROCEDURE repLength(s: ARRAY OF CHAR): CARDINAL; VAR strlen, replen, i, j: CARDINAL; ...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]] StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#MAXScript
MAXScript
  samples = #("Some string 123","Example text 123","string",\ "ThisString Will Not Match","A123,333,string","123451") samples2 = #("I am a string","Me too.")   regex = dotnetobject "System.Text.RegularExpressions.Regex" ".*\bstring*" regex2 = dotnetobject "System.Text.RegularExpressions.Regex" "\ba\b"   clearliste...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#C.2B.2B
C++
#include <iostream> #include <string> #include <algorithm>   int main() { std::string s; std::getline(std::cin, s); std::reverse(s.begin(), s.end()); // modifies s std::cout << s << std::endl; return 0; }
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Red
Red
Red[]   myrepeat: function [fn n] [loop n [do fn]]   myrepeat [print "hello"] 3