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/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...
#Standard_ML
Standard ML
OS.FileSys.rename {old = "input.txt", new = "output.txt"}; OS.FileSys.rename {old = "docs", new = "mydocs"}; OS.FileSys.rename {old = "/input.txt", new = "/output.txt"}; OS.FileSys.rename {old = "/docs", new = "/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...
#Ring
Ring
  aList = str2list(" ---------- 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 ----------------------- ") aList = str2list(cStr) for x in aList x2 = substr(x," ",nl) ali...
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...
#Ruby
Ruby
puts <<EOS ---------- 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 ----------------------- EOS .each_line.map {|line| line.split.reverse.join(' ')}
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...
#Ursala
Ursala
#import std   #executable (<'parameterized','default-to-stdin'>,<>)   rot = ~command.files; * contents:= ~contents; * * -:~& -- ^p(~&,rep13~&zyC)~~ ~=`A-~ letters
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...
#True_BASIC
True BASIC
OPTION BASE 0 DIM arabic(12), roman$(12)   FOR i = 0 TO 12 READ arabic(i), roman$(i) NEXT i   DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC" DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"   FUNCTION toRoman$(value) LET result$ = "" FOR i = 0 TO 12 DO WHILE val...
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...
#Julia
Julia
@show "ha" ^ 5   # The ^ operator is really just call to the `repeat` function @show repeat("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...
#K
K
  ,/5#,"ha" "hahahahaha"   5#"*" "*****"  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func begin sum := x + y; diff := x - y; end func;   const proc: main is func local var integer: sum is 0; var integer: diff is 0; begin sumAndDiff(5, 3, sum, diff); ...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#SenseTalk
SenseTalk
set [quotient,remainder] to quotientAndRemainder(13,4)   put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"   to handle quotientAndRemainder of num, divisor return [num div divisor, num rem divisor] end quotientAndRemainder
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 ...
#GW-BASIC
GW-BASIC
10 ' Remove Duplicates 20 OPTION BASE 1 30 LET MAXI% = 7 40 DIM D(7), R(7): ' data, result 50 ' Set the data. 60 FOR I% = 1 TO 7 70 READ D(I%) 80 NEXT I% 90 ' Remove duplicates. 100 LET R(1) = D(1) 110 LET LRI% = 1: ' last index of result 120 LET P% = 1: ' position 130 WHILE P% < MAXI% 140 ...
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...
#uBasic.2F4tH
uBasic/4tH
a = 0 ' the first one is free ;-) Print "First 15 numbers:"   For i = 1 Step 1 ' start loop If i<16 Then Print a, ' print first 15 numbers b = Iif ((a-i<1) + (Func(_Peek(Max(0, a-i)))), a+i, a-i) If Func(_Peek(b)) Then Print "\nFirst repetition...
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...
#VBScript
VBScript
' Recaman's sequence - vbscript - 04/08/2015 nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman's sequence for the first " & nx & " numbers:" Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to c...
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...
#Nim
Nim
import rationals, strutils   type Fraction = Rational[int]   const Zero: Fraction = 0 // 1   type Matrix[M, N: static Positive] = array[M, array[N, Fraction]]     func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = ## Convert a matrix of integers to a matrix of integer fractions.   for ...
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 ...
#Julia
Julia
e π, pi sqrt(x) log(x) exp(x) abs(x) floor(x) ceil(x) x^y
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 ...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { println(Math.E) // e println(Math.PI) // pi println(Math.sqrt(2.0)) // square root println(Math.log(Math.E)) // log to base e println(Math.log10(10.0)) // log to base 10 println(Math.exp(1.0)) ...
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...
#Scala
Scala
object RemoveLinesFromAFile extends App { args match { case Array(filename, start, num) =>   import java.nio.file.{Files,Paths} val lines = scala.io.Source.fromFile(filename).getLines val keep = start.toInt - 1 val top = lines.take(keep).toList val drop = lines.take(num.toInt).toList...
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...
#M2000_Interpreter
M2000 Interpreter
  Module checkit { \\ prepare a file \\ Save.Doc and Append.Doc to file, Load.Doc and Merge.Doc from file document a$ a$={First Line Second line Third Line Ελληνικά Greek Letters } Save.Doc a$, "checkthis.txt", 2 ' 2 for UTF-8   Buffe...
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...
#M4
M4
define(`foo',include(`file.txt')) defn(`foo') defn(`foo')
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...
#Tcl
Tcl
proc repstring {text} { set len [string length $text] for {set i [expr {$len/2}]} {$i > 0} {incr i -1} { set sub [string range $text 0 [expr {$i-1}]] set eq [string repeat $sub [expr {int(ceil($len/double($i)))}]] if {[string equal -length $len $text $eq]} { return $sub } } error "no repetition...
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
#Ring
Ring
  # Project : Regular expressions   text = "I am a text" if right(text,4) = "text" see "'" + text +"' ends with 'text'" + nl ok i = substr(text,"am") text = left(text,i - 1) + "was" + substr(text,i + 2) see "replace 'am' with 'was' = " + text + nl  
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 ...
#DWScript
DWScript
let str = "asdf"   func String.Reverse() { var cs = [] let len = this.Length() for n in 1..len { cs.Add(this[len - n]) } String(values: cs) }   str.Reverse()
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...
#Stata
Stata
!ren input.txt output.txt !ren 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...
#Tcl
Tcl
file rename inputs.txt output.txt file rename docs mydocs   file rename [file nativename /inputs.txt] [file nativename /output.txt] file rename [file nativename /docs] [file nativename /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...
#Toka
Toka
needs shell " input.txt" " output.txt" rename " /input.txt" " /output.txt" rename   " docs" " mydocs" rename " /docs" " /mydocs" rename
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...
#Run_BASIC
Run BASIC
for i = 1 to 10 read string$ j = 1 r$ = "" while word$(string$,j) <> "" r$ = word$(string$,j) + " " + r$ j = j + 1 WEND print r$ next end   data "---------- Ice and Fire ------------" data "" data "fire, in end will world the say Some" data "ice. in say Some" data "desire of tasted I've ...
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...
#Rust
Rust
const TEXT: &'static str = "---------- 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 -----------------------";   fn main() { println!("{}", TEXT.lines()...
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...
#Vala
Vala
string rot13(string s) { const string lcalph = "abcdefghijklmnopqrstuvwxyz"; const string ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string result = ""; int pos; unichar c;   for (int i = 0; s.get_next_char (ref i, out c);) { if ((pos = lcalph.index_of_char(c)) != -1) result += lcalph[(pos + 13) % 26]...
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT LOOP arab_number="1990'2008'1666" roman_number = ENCODE (arab_number,ROMAN) PRINT "Arabic number ",arab_number, " equals ", roman_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...
#Kotlin
Kotlin
fun main(args: Array<String>) { println("ha".repeat(5)) }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Sidef
Sidef
func foo(a,b) { return (a+b, a*b); }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Smalltalk
Smalltalk
foo multipleValuesInto:[:a :b | Transcript show:a; cr. Transcript show:b; cr. ]
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 ...
#Haskell
Haskell
print $ unique [4, 5, 4, 2, 3, 3, 4]   [4,5,2,3]
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Collections.Generic   Module Module1 Sub Main(ByVal args As String()) Dim a As List(Of Integer) = New List(Of Integer)() From { 0 }, used As HashSet(Of Integer) = New HashSet(Of Integer)() From { 0 }, used1000 As HashSet(Of Integer) = used.ToHashSet(), ...
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...
#Objeck
Objeck
  class RowEchelon { function : Main(args : String[]) ~ Nil { matrix := [ [1, 2, -1, -4 ] [2, 3, -1, -11 ] [-2, 0, -3, 22] ];   matrix := Rref(matrix);   sizes := matrix->Size(); for(i := 0; i < sizes[0]; i += 1;) { for(j := 0; j < sizes[1]; j += 1;) { IO.Console-...
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 ...
#Lambdatalk
Lambdatalk
  {E} -> 2.718281828459045 {PI} -> 3.141592653589793 {sqrt 2} -> 1.4142135623730951 {log {E}} -> 1 {exp 1} -> 2.718281828459045 {abs -1} -> 1 {floor -2.5} -> -3 {ceil -2.5} -> -2 {pow 2.5 3.5} -> 24.705294220065465  
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: removeLines (in string: fileName, in integer: start, in integer: count) is func local var file: inFile is STD_NULL; var file: outFile is STD_NULL; var integer: lineNumber is 1; var string: line is ""; begin inFile := open(fileName,...
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...
#Make
Make
contents := $(shell cat foo.txt)
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...
#Maple
Maple
  s1 := readbytes( "file1.txt", infinity, TEXT ):  
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...
#UNIX_Shell
UNIX Shell
is_repeated() { local str=$1 len rep part for (( len = ${#str} / 2; len > 0; len-- )); do part=${str:0:len} rep="" while (( ${#rep} < ${#str} )); do rep+=$part done if [[ ${rep:0:${#str}} == $str ]] && (( $len < ${#str} )); then echo "$part" ...
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
#Ruby
Ruby
str = "I am a string" p "Ends with 'string'" if str =~ /string$/ p "Does not start with 'You'" unless str =~ /^You/
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
#Run_BASIC
Run BASIC
string$ = "I am a string" if right$(string$,6) = "string" then print "'";string$;"' ends with 'string'" i = instr(string$,"am") string$ = left$(string$,i - 1) + "was" + mid$(string$,i + 2) print "replace 'am' with 'was' = ";string$  
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 ...
#Dyalect
Dyalect
let str = "asdf"   func String.Reverse() { var cs = [] let len = this.Length() for n in 1..len { cs.Add(this[len - n]) } String(values: cs) }   str.Reverse()
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...
#TorqueScript
TorqueScript
fileCopy("Input.txt", "Output.txt"); fileDelete("Input.txt");   for(%File = FindFirstFile("Path/*.*"); %File !$= ""; %File = FindNextFile("Path/*.*")) { fileCopy(%File, "OtherPath/" @ %File); fileDelete(%File); }
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT - rename file ERROR/STOP RENAME ("input.txt","output.txt") - rename directory ERROR/STOP RENAME ("docs","mydocs",-std-)  
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...
#S-lang
S-lang
variable ln, in = ["---------- 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 -----------------------"];   foreach ln (in) { ...
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...
#Vedit_macro_language
Vedit macro language
Translate_Load("ROT13.TBL") Translate_Block(0, File_Size)
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...
#TypeScript
TypeScript
  // Roman numerals/Encode   const weightsSymbols: [number, string][] = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]; // 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded // with thes...
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...
#LabVIEW
LabVIEW
  {S.map {lambda {_} ha} {S.serie 1 10}} -> ha ha ha ha ha ha ha ha ha ha   or   {S.replace \s by in {S.map {lambda {_} ha} {S.serie 1 10}}} -> hahahahahahahahahaha   or   {def repeat {lambda {:w :n} {if {< :n 0} then else :w{repeat :w {- :n 1}}}}} -> repeat   {repeat ha 1...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Standard_ML
Standard ML
fun addsub (x, y) = (x + y, x - y)
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 ...
#HicEst
HicEst
REAL :: nums(12) CHARACTER :: workspace*100   nums = (1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2) WRITE(Text=workspace) nums ! convert to string EDIT(Text=workspace, SortDelDbls=workspace) ! do the job for a string READ(Text=workspace, ItemS=individuals) nums ! convert to numeric   WRITE(ClipBoard) indi...
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...
#Wren
Wren
var a = [0] var used = { 0: true } var used1000 = { 0: true } var foundDup = false var n = 1 while (n <= 15 || !foundDup || used1000.count < 1001) { var next = a[n-1] - n if (next < 1 || used[next]) next = next + 2*n var alreadyUsed = used[next] a.add(next) if (!alreadyUsed) { used[next] = t...
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...
#OCaml
OCaml
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;;   let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0...
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 ...
#Lasso
Lasso
//e define e => 2.7182818284590452   //π define pi => 3.141592653589793   e pi 9.0->sqrt 1.64->log 1.64->log10 1.64->exp 1.64->abs 1.64->floor 1.64->ceil 1.64->pow(10.0)
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...
#SenseTalk
SenseTalk
removeLines "foobar.txt", 1, 2 to handle removeLines fileName, startingLine, linesToRemove If there is no file fileName then put !"No such file: [[the folder & fileName]]" Return End if set endingLine to startingLine + linesToRemove - 1 If endingLine is more than number of lines in file fileName then put !"Ca...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Import["filename","String"]
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...
#VBScript
VBScript
  Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = ...
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
#Rust
Rust
use regex::Regex;   fn main() { let s = "I am a string";   if Regex::new("string$").unwrap().is_match(s) { println!("Ends with string."); }   println!("{}", Regex::new(" a ").unwrap().replace(s, " another ")); }
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 ...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!print concat chars "Hello"
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...
#TXR
TXR
(rename-path "input.txt" "output.txt") ;; Windows (MinGW based port) (rename-path "C:\\input.txt" "C:\\output.txt") ;; Unix; Windows (Cygwin port) (rename-path "/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...
#UNIX_Shell
UNIX Shell
mv input.txt output.txt mv /input.txt /output.txt mv docs mydocs mv /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...
#Scala
Scala
object ReverseWords extends App {   """| ---------- 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 ......
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...
#Visual_Basic
Visual Basic
  Function ROT13(ByVal a As String) As String Dim i As Long Dim n As Integer, e As Integer   ROT13 = a For i = 1 To Len(a) n = Asc(Mid$(a, i, 1)) Select Case n Case 65 To 90 e = 90 n = n + 13 Case 97 To 122 e = 122 n = n + 13 Case Else e = 255 ...
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...
#uBasic.2F4tH
uBasic/4tH
Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 ' Initialize array For i = 12 To 0 Step -1 @(i) = Pop() Next ' Calculate and print numbers Print 1999, : Proc _FNroman (1999) Print 2014, : Proc _FNroman (2014) Print 1666, : Proc _F...
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...
#Lambdatalk
Lambdatalk
  {S.map {lambda {_} ha} {S.serie 1 10}} -> ha ha ha ha ha ha ha ha ha ha   or   {S.replace \s by in {S.map {lambda {_} ha} {S.serie 1 10}}} -> hahahahahahahahahaha   or   {def repeat {lambda {:w :n} {if {< :n 0} then else :w{repeat :w {- :n 1}}}}} -> repeat   {repeat ha 1...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Swift
Swift
func addsub(x: Int, y: Int) -> (Int, Int) { return (x + y, x - y) }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Tcl
Tcl
proc addsub {x y} { list [expr {$x+$y}] [expr {$x-$y}] }
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) every write(!noDups(args)) end   procedure noDups(L) every put(newL := [], notDup(set(),!L)) return newL end   procedure notDup(cache, a) if not member(cache, a) then { insert(cache, a) return a } end
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...
#zkl
zkl
fcn recamanW{ // -->iterator -->(n,a,True if a is a dup) Walker.tweak(fcn(rn,rp,d){ n,p,a := rn.value, rp.value, p - n; if(a<=0 or d.find(a)) a+=2*n; d.incV(a); rp.set(a); return(rn.inc(),a,d[a]>1); }.fp(Ref(0),Ref(0),Dictionary()) ) }
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...
#Octave
Octave
A = [ 1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22]; refA = rref(A); disp(refA);
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 ...
#Liberty_BASIC
Liberty BASIC
  print exp( 1) ' e not available print 4 *atn( 1) ' pi not available   x =12.345: y =1.23   print sqr( x), x^0.5 ' square root- NB the unusual name print log( x) ' natural logarithm base e print log( x) /2.303 ' base 10 logarithm print log( x) /log( y) ' arbitrary base logarith...
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...
#Sidef
Sidef
func remove_lines(file, beg, len) { var lines = file.open_r.lines; lines.splice(beg, len).len == len || warn "Too few lines"; file.open_w.print(lines.join) }   remove_lines(File(__FILE__), 2, 3);
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...
#MATLAB_.2F_Octave
MATLAB / Octave
fid = fopen('filename','r'); [str,count] = fread(fid, [1,inf], 'uint8=>char'); % s will be a character array, count has the number of bytes fclose(fid);
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...
#Mercury
Mercury
:- module read_entire_file. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module string.   main(!IO) :- io.open_input("file.txt", OpenResult, !IO), ( OpenResult = ok(File), io.read_file_as_string(File, ReadResult, !IO), ( Read...
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...
#Vlang
Vlang
fn rep(s string) int { for x := s.len / 2; x > 0; x-- { if s.starts_with(s[x..]) { return x } } return 0 }   const m = ' 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1'   fn main() { for s in m.fields() { n := rep(s) if n...
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
#Sather
Sather
class MAIN is -- we need to implement the substitution regex_subst(re:REGEXP, s, sb:STR):STR is from, to:INT; re.match(s, out from, out to); if from = -1 then return s; end; return s.head(from) + sb + s.tail(s.size - to); end;   main is s ::= "I am a string"; re ::= REGEXP::regexp("strin...
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
#Scala
Scala
val Bottles1 = "(\\d+) bottles of beer".r // syntactic sugar val Bottles2 = """(\d+) bottles of beer""".r // using triple-quotes to preserve backslashes val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer") ...
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 ...
#E
E
pragma.enable("accumulator") def reverse(string) { return accum "" for i in (0..!(string.size())).descending() { _ + string[i] } }
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...
#Vedit_macro_language
Vedit macro language
// In current directory File_Rename("input.txt", "output.txt") File_Rename("docs", "mydocs")   // In the root directory File_Rename("/input.txt", "/output.txt") File_Rename("/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...
#Visual_Basic_.NET
Visual Basic .NET
'Current Directory IO.Directory.Move("docs", "mydocs") IO.File.Move("input.txt", "output.txt")   'Root IO.Directory.Move("\docs", "\mydocs") IO.File.Move("\input.txt", "\output.txt")   'Root, platform independent IO.Directory.Move(IO.Path.DirectorySeparatorChar & "docs", _ IO.Path.DirectorySeparatorChar & "mydocs") IO...
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...
#Scheme
Scheme
  (for-each (lambda (s) (print (string-join (reverse (string-split s #/ +/))))) (string-split "---------- 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 ...   ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Private Function rot13(ByVal str As String) As String Dim newChars As Char(), i, j As Integer, original, replacement As String   original = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" replacement = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"   newCha...
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...
#UNIX_Shell
UNIX Shell
roman() { local values=( 1000 900 500 400 100 90 50 40 10 9 5 4 1 ) local roman=( [1000]=M [900]=CM [500]=D [400]=CD [100]=C [90]=XC [50]=L [40]=XL [10]=X [9]=IX [5]=V [4]=IV [1]=I ) local nvmber="" local num=$1 for value in ${values[@]}; do ...
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...
#langur
langur
"ha" x 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...
#Lasso
Lasso
'ha'*5 // hahahahaha
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#TXR
TXR
@(define func (x y z)) @ (bind w "discarded") @ (bind (x y z) ("a" "b" "c")) @(end)
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#UNIX_Shell
UNIX Shell
  #!/bin/sh funct1() { a=$1 b=`expr $a + 1` echo $a $b }   values=`funct1 5`   set $values x=$1 y=$2 echo "x=$x" echo "y=$y"  
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 ...
#IDL
IDL
non_repeated_values = array[uniq(array, sort( array))]
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...
#PARI.2FGP
PARI/GP
matrref(M)= { my(s=matsize(M),t=s[1]); for(i=1,s[2], if(M[t,i]==0, next); M[t,] /= M[t,i]; for(j=1,t-1, M[j,] -= M[j,i]*M[t,] ); for(j=t+1,s[1], M[j,] -= M[j,i]*M[t,] ); if(t--<1,break) ); M; } addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");
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 ...
#Lingo
Lingo
the floatPrecision = 8   -- e (base of the natural logarithm) put exp(1) -- 2.71828183   -- pi put PI -- 3.14159265   -- square root put sqrt(2.0) -- 1.41421356   -- logarithm (any base allowed) x = 100   put log(x) -- calculate log for base e -- 4.60517019   put log(x)/log(10) -- calculate log for base 10 -- 2.0000000...
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 ...
#LiveCode
LiveCode
e‬: exp(1) pi: pi square root: sqrt(x) logarithm: log(x) exponential (‪ex‬): exp(x) absolute value: abs(x) floor: floor(x) ceiling: ceil(x) power: x^y
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...
#Snobol4
Snobol4
* Remove lines from a file   * Function to remove a chunk of lines from a file, will go backward, too, if numlines < 0 define("remlines(filename,startline,numlines)row,rowcount,lastline,swap")  :(remlines_end) remlines input(.inp1,1,filename) :f(freturn) output(.tmp1,2,"/tmp/Removem") :f(freturn) rowcount = ...
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...
#Stata
Stata
* drop lines 20 to 30 drop in 20/30   * keep lines 20 to 30, and remove everything else keep in 20/30
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...
#Microsoft_Small_Basic
Microsoft Small Basic
v=File.ReadContents(filename)
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...
#Nanoquery
Nanoquery
import Nanoquery.IO contents = new(File, "example.txt").readAll()
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...
#Wren
Wren
import "/fmt" for Fmt   var repString = Fn.new { |s| var reps = [] if (s.count < 2) return reps for (c in s) if (c != "0" && c != "1") Fiber.abort("Argument is not a binary string.") var size = s.count for (len in 1..(size/2).floor) { var t = s[0...len] var n = (size/len).floor ...
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
#SenseTalk
SenseTalk
  set text to "This is a story about R2D2 and C3P0 who are best friends." set pattern to <word start, letter, digit, letter, digit, word end>   put the sixth word of text matches pattern -- (note: the sixth word is "R2D2")   put every occurrence of pattern in text   replace the second occurrence of pattern in text with...
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
#Shiny
Shiny
str: 'I am a string'
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 ...
#EchoLisp
EchoLisp
  (define (string-reverse string) (list->string (reverse (string->list string))))   (string-reverse "ghij") → jihg (string-reverse "un roc lamina l animal cornu") → unroc lamina l animal cor nu  
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...
#Wren
Wren
import "/ioutil" for FileUtil   FileUtil.move("input.txt", "output.txt") FileUtil.move("/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...
#Yabasic
Yabasic
if peek$("os") = "windows" then slash$ = "\\" : com$ = "ren " else slash$ = "/" : com$ = "mv " end if   system(com$ + "input.txt output.txt") system(com$ + "docs mydocs") system(com$ + slash$ + "input.txt " + slash$ + "output.txt") system(com$ + slash$ + "docs " + slash$ + "mydocs")