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/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...
#sed
sed
#!/usr/bin/sed -f   G :loop s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/ t loop s/^[[:space:]]*//
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...
#VBScript
VBScript
  option explicit   function rot13(a) dim b,n1,n,i b="" for i=1 to len(a) n=asc(mid(a,i,1)) if n>=65 and n<= 91 then n1=(((n-65)+13)mod 26)+65 elseif n>=97 and n<= 123 then n1=(((n-97)+13)mod 26)+97 else n1=n end if b=b & chr(n1) next rot13=b end function   con...
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...
#Ursala
Ursala
#import nat   roman =   -+ 'IIII'%='IV'+ 'VIIII'%='IX'+ 'XXXX'%='XL'+ 'LXXXX'%='XC'+ 'CCCC'%='CD'+ 'DCCCC'%='CM', ~&plrDlSPSL/'MDCLXVI'+ iota*+ +^|(^|C/~&,\/division)@rlX=>~&iNC <1000,500,100,50,10,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...
#LFE
LFE
  (string:copies '"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...
#Liberty_BASIC
Liberty BASIC
a$ ="ha " print StringRepeat$( a$, 5)   end   function StringRepeat$( in$, n) o$ ="" for i =1 to n o$ =o$ +in$ next i StringRepeat$ =o$ end function
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Ursa
Ursa
def getstrs (int n) decl string<> input   while (> n 0) out ": " console append (in string console) input dec n end while   return input end getstrs   decl int amount out "how many strings do you want to enter? " console set amount (in int ...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#VBA
VBA
  Type Contact Name As String firstname As String Age As Byte End Type   Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function   'For use : Sub Test_SetContact() Dim Cont As Contact   Cont = SetConta...
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 ...
#Inform_7
Inform 7
To decide which list of Ks is (L - list of values of kind K) without duplicates: let result be a list of Ks; repeat with X running through L: add X to result, if absent; decide on result.
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...
#Perl
Perl
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));   foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r;   until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return...
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 ...
#Logo
Logo
make "e exp 1 make "pi 2*(RADARCTAN 0 1) sqrt :x ln :x exp :x ; there is no standard abs, floor, or ceiling; only INT and ROUND. power :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 ...
#Logtalk
Logtalk
  :- object(constants_and_functions).   :- public(show/0). show :- write('e = '), E is e, write(E), nl, write('pi = '), PI is pi, write(PI), nl, write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl, % only base e logorithm is avaialable as a standard built-in function wr...
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...
#Tcl
Tcl
proc removeLines {fileName startLine count} { # Work out range to remove set from [expr {$startLine - 1}] set to [expr {$startLine + $count - 2}] # Read the lines set f [open $fileName] set lines [split [read $f] "\n"] close $f # Write the lines back out, without removed range set 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...
#Neko
Neko
/** Read entire file Tectonics: nekoc read-entire-file.neko neko read-entire-file */   var file_contents = $loader.loadprim("std@file_contents", 1);   try { var entire_file = file_contents("read-entire-file.neko"); $print("Read: ", $ssize(entire_file), " bytes\n"); } catch e { $print("Exception: ", e, "\n...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   parse arg inFileName .   if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json' fileContents = slurp(inFileName) say fileContents   return   -- Slurp a file and return contents as a Rexx string method slurp(inFileName) ...
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...
#Yabasic
Yabasic
data "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", ""   sub rep$(c$, n) local r$, i   for i = 1 to n r$ = r$ + c$ next return r$ end sub   do read p$ : if p$ = "" break b$ = "" : l = len(p$) : m = int(l / 2)   ...
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...
#zkl
zkl
fcn repString(s){ foreach n in ([s.len()/2+1..1,-1]){ Walker.cycle(s[0,n]).pump(s.len(),String) : if(_==s and n*2<=s.len()) return(n); } return(False) }
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
#Sidef
Sidef
var str = "I am a string"; if (str =~ /string$/) { print "Ends with 'string'\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
#Slate
Slate
  'http://slatelanguage.org/test/page?query' =~ '^(([^:/?#]+)\\:)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'.   " ==> {'http:'. 'http'. '//slatelanguage.org'. 'slatelanguage.org'. '/test/page'. '?query'. 'query'. Nil} "  
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 ...
#EGL
EGL
function reverse( str string ) returns( string ) result string; for ( i int from StrLib.characterLen( str ) to 1 decrement by 1 ) result ::= str[i:i]; end return( result ); end
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...
#Yorick
Yorick
rename, "input.txt", "output.txt"; rename, "/input.txt", "/output.txt"; rename, "docs", "mydocs"; 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...
#zkl
zkl
ls -ld input.txt docs output.txt mydocs ls: cannot access 'output.txt': No such file or directory ls: cannot access 'mydocs': No such file or directory drwxr-xr-x 2 craigd craigd 4096 Aug 10 16:24 docs -rw-r--r-- 1 craigd craigd 0 Aug 10 16:24 input.txt $ zkl zkl: File.rename("input.txt","output.txt") True zkl: File...
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const array string: lines is [] ( "---------- 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/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...
#SenseTalk
SenseTalk
set poem to {{ ---------- 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 ----------------------- }}   repeat with each line in poem put (each word of it) reversed joined b...
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...
#Wart
Wart
def (rot13 s) (as string (map rot13 (as list s)))   Alphabet <- "abcdefghijklmnopqrstuvwxyz" def (rot13 c) :case (and string?.c len.c=1) if ("a" <= c <= "z") let idx (pos c Alphabet) Alphabet (idx+13 % 26) ("A" <= c <= "Z") (downcase.c -> rot13 -> upcase)  :else ...
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...
#Vala
Vala
string to_roman(int n) requires (n > 0 && n < 5000) { const int[] weights = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string[] symbols = {"M","CM","D","CD","C","XC","L", "XL","X","IX","V","IV","I"};   var roman = "", count = 0; foreach ...
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...
#Lingo
Lingo
on rep (str, n) res = "" repeat with i = 1 to n put str after res end repeat return res end
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Visual_FoxPro
Visual FoxPro
  *!* Return multiple values from a function *!* The simplest way is to pass the parameters by reference *!* either by SET UDFPARMS TO REFERENCE, or prefix the variables with @. LOCAL a, b a = 5 b = 6 ? "Sum =", AddUp(@a, @b) && Displays 11 ? "a =", a, "b =", b && Displays 4, 5 ? "Sum =", AddUp(@a, @b) && ...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Wren
Wren
var splitName = Fn.new { |fullName| fullName.split(" ") }   var names = splitName.call("George Bernard Shaw") System.print("First name: %(names[0]), middle name: %(names[1]) and surname: %(names[2]).")
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 ...
#IS-BASIC
IS-BASIC
100 PROGRAM "RemoveDu.bas" 110 RANDOMIZE 120 NUMERIC ARR(1 TO 20),TOP 130 LET TOP=FILL(ARR) 140 CALL WRITE(ARR,TOP) 150 LET TOP=REMOVE(ARR) 160 CALL WRITE(ARR,TOP) 170 DEF WRITE(REF A,N) 180 FOR I=1 TO N 190 PRINT A(I); 200 NEXT 210 PRINT 220 END DEF 230 DEF FILL(REF A) 240 LET FILL=UBOUND(A):LET A(LBOUND(A...
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...
#Phix
Phix
with javascript_semantics function ToReducedRowEchelonForm(sequence M) integer lead = 1, rowCount = length(M), columnCount = length(M[1]), i for r=1 to rowCount do if lead>=columnCount then exit end if i = r while M[i][lead]=0 do i += 1 if i=ro...
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 ...
#Lua
Lua
math.exp(1) math.pi math.sqrt(x) math.log(x) math.log10(x) math.exp(x) math.abs(x) math.floor(x) math.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 ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Def exp(x)= 2.71828182845905^x Print Ln(exp(1))==1 Print Log(10^5)==5 Print Sgn(-5)=-1 Print Abs(-2.10#)=2.1# Def exptype$(x)=type$(x) Print exptype$(Abs(-2.1#))="Currency" Print exptype$(Abs(-2.1~))="Single" Print exptype$(Abs(-2.1@))="Decimal" ...
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...
#TUSCRIPT
TUSCRIPT
  $$! input=testfile,begnr=3,endnr=4 $$ MODE TUSCRIPT - CREATE inputfile ERROR/STOP CREATE (input,FDF-o,-std-) FILE/ERASE $input LOOP n=1,9 content=CONCAT ("line",n) DATA {content} ENDLOOP ENDFILE   - CREATE outputfile output="outputfile"   ERROR/STOP CREATE (output,fdf-o,-std-) ACCESS q: READ/RECORDS/utf8 $input ...
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...
#NewLISP
NewLISP
(read-file "filename")
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
#Smalltalk
Smalltalk
|re s s1| re := Regex fromString: '[a-z]+ing'. s := 'this is a matching string'. s1 := 'this does not match'.   (s =~ re) ifMatched: [ :b | b match displayNl ]. (s1 =~ re) ifMatched: [ :b | 'Strangely matched!' displayNl ] ifNotMatched: [ 'no match!' displayNl ].   (s replacingRegex: re with: 'modified') displ...
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
#SNOBOL4
SNOBOL4
label subject pattern = object  :(goto)
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 ...
#Eiffel
Eiffel
class APPLICATION create make feature make -- Demonstrate string reversal. do my_string := "Hello World!" my_string.mirror print (my_string) end my_string: STRING -- Used for reversal end
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...
#Sidef
Sidef
DATA.each{|line| line.words.reverse.join(" ").say};   __DATA__ ---------- 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 -----------------------
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...
#Whenever
Whenever
  1 2#read()-N(2); 2 2; 3 defer(1 || N(2) > 90 || N(2) < 65) 5#65-N(5); 4 defer(1 || N(2) > 122 || N(2) < 97) 5#97-N(5); 5 5; 6 defer(3 && 4) put(U(((N(2) - N(5) + 13) % 26) + N(5))); 7 defer(1 || N(2) > 64 || N(2) == 0) put(U(N(2))); 8 again(8) defer(6 && 7) 1,-6#N(6)-1,-7#N(7)-1,-3#N(3)-1,-4#N(4)-1; 9 defer(1 || N(2)...
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...
#VBA
VBA
Private Function roman(n As Integer) As String roman = WorksheetFunction.roman(n) End Function Public Sub main() s = [{10, 2016, 800, 2769, 1666, 476, 1453}] For Each x In s Debug.Print roman(CInt(x)); " "; Next x End Sub
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...
#LiveCode
LiveCode
on mouseUp put repeatString("ha", 5) end mouseUp   function repeatString str n repeat n times put str after t end repeat return t end repeatString
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...
#Logo
Logo
to copies :n :thing [:acc "||] if :n = 0 [output :acc] output (copies :n-1 :thing combine :acc :thing) end
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Rect2Polar(X,Y,A,D); \Return two polar coordinate values real X,Y,A,D; [A(0):= ATan2(Y,X); D(0):= Sqrt(X*X+Y*Y); ]; \Rect2Polar   real Ang, Dist; [Rect2Polar(4.0, 3.0, @Ang, @Dist); \("@" is a new feature similar to 'addr') RlOut(0, Ang); Rl...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Z80_Assembly
Z80 Assembly
foo: ld hl,&ABCD ld bc,&FFFF ret
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 ...
#J
J
~. 4 3 2 8 0 1 9 5 1 7 6 3 9 9 4 2 1 5 3 2 4 3 2 8 0 1 9 5 7 6 ~. 'chthonic eleemosynary paronomasiac' chtoni elmsyarp
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...
#PHP
PHP
<?php   function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break...
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 ...
#Maple
Maple
> abs(ceil(floor(ln(exp(1)^sqrt(exp(Pi*I)+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...
#UNIX_Shell
UNIX Shell
#!/bin/sh error() { echo >&2 "$0: $*" exit 1 }   [ $# -ne 3 ] && error "Incorrect number of parameters"   file=$1 start=$2 count=$3 end=`expr $start + $count - 1`   [ -f "$file" ] || error "$file does not exist"   sed "$start,${end}d" "$file" >/tmp/$$ && mv /tmp/$$ "$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...
#Nim
Nim
readFile(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...
#Objeck
Objeck
  string := FileReader->ReadFile("in.txt");  
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
#Standard_ML
Standard ML
CM.make "$/regexp-lib.cm"; structure RE = RegExpFn ( structure P = AwkSyntax structure E = BackTrackEngine); val re = RE.compileString "string$"; val string = "I am a string"; case StringCvt.scanString (RE.find re) string of NONE => print "match failed\n" | SOME match => let val {pos, len} ...
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
#Stata
Stata
scalar s="ars longa vita brevis"   * is there a vowel? di regexm(s,"[aeiou]")   * replace the first vowel with "?" di regexr(s,"[aeiou]","?")
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 ...
#Ela
Ela
reverse_string str = rev len str where len = length str rev 0 str = "" rev n str = toString (str : nn) +> rev nn str where nn = n - 1   reverse_string "Hello"
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...
#Smalltalk
Smalltalk
  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 -----------------------'.   (poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ...
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...
#Sparkling
Sparkling
let lines = 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 ...   Frost Robert -----------------------", "\n");   foreach(lines, function(idx, line) { let words = split(line...
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...
#Whitespace
Whitespace
  ...
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...
#Vedit_macro_language
Vedit macro language
// Main program for testing the function // do { #1 = Get_Num("Number to convert: ", STATLINE) Call("NUM_TO_ROMAN") Num_Type(#1, NOCR) Message(" = ") Reg_Type(1) Type_Newline } while (Reg_Size(1)) Return   // Convert numeric value into Roman number // #1 = number to convert; on return: T-reg(1) = Roman num...
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...
#Lua
Lua
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#zkl
zkl
fcn f{return(1,2,"three")} a,b,c:=f() // a==1, b==2, c=="three"
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 ...
#Java
Java
import java.util.*;   class Test {   public static void main(String[] args) {   Object[] data = {1, 1, 2, 2, 3, 3, 3, "a", "a", "b", "b", "c", "d"}; Set<Object> uniqueSet = new HashSet<Object>(Arrays.asList(data)); for (Object o : uniqueSet) System.out.printf("%s ", o); } }
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...
#PicoLisp
PicoLisp
(de reducedRowEchelonForm (Mat) (let (Lead 1 Cols (length (car Mat))) (for (X Mat X (cdr X)) (NIL (loop (T (seek '((R) (n0 (get R 1 Lead))) X) @ ) (T (> (inc 'Lead) Cols)) ) ) (xchg @ X) (let D (get X 1 Lead) (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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
E Pi Sqrt[x] Log[x] Log[b,x] Exp[x] Abs[x] Floor[x] Ceiling[x] Power[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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
exp(1) % e pi % pi sqrt(x) % square root log(x) % natural logarithm log2(x) % logarithm base 2 log10(x) % logarithm base 10 exp(x) % exponential abs(-x) % absolute value floor(x) % floor ceil(x) % ceiling 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...
#VBA
VBA
Option Explicit   Sub Main() 'See Output #1 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 'See Output #2 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 'See Output #3 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5...
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...
#Objective-C
Objective-C
  /*** 0. PREPARATION */ // We need a text file to read; let's redirect a C string to a new file // using the shell by way of the stdlib system() function. system ("echo \"Hello, World!\" > ~/HelloRosetta");       /*** 1. THE TASK */ // Instantiate an NSString which describes the filesys...
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...
#OCaml
OCaml
let load_file f = let ic = open_in f in let n = in_channel_length ic in let s = Bytes.create n in really_input ic s 0 n; close_in ic; (s)
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
#Swift
Swift
import Foundation   let str = "I am a string" if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) { println("Ends with 'string'") }
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
#Tcl
Tcl
set theString "I am a string" if {[regexp -- {string$} $theString]} { puts "Ends with 'string'" }   if {![regexp -- {^You} $theString]} { puts "Does not start with 'You'" }
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 ...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   extension extension { reversedLiteral() = self.toArray().sequenceReverse().summarize(new StringWriter()); }   public program() { console.printLine("Hello World".reversedLiteral()) }
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...
#Standard_ML
Standard ML
val lines = [ " ---------- 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 ", " "...
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...
#Swift
Swift
import Foundation   // convenience extension for better clarity extension String { var lines: [String] { get { return self.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) } } var words: [String] { get { return self.componentsSeparate...
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...
#Wren
Wren
var rot13 = Fn.new { |s| var bytes = s.bytes.toList for (i in 0...bytes.count) { var c = bytes[i] if ((c >= 65 && c <= 77) || (c >= 97 && c <= 109)) { bytes[i] = c + 13 } else if ((c >= 78 && c <= 90) || (c >= 110 && c <= 122)) { bytes[i] = c - 13 } } ...
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...
#Visual_Basic
Visual Basic
Function toRoman(value) As String Dim arabic As Variant Dim roman As Variant   arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")   Dim i As Integer, result As String   For i = 0 To 12 ...
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...
#Maple
Maple
  > use StringTools in > Repeat( "abc", 10 ); # repeat an arbitrary string > Fill( "x", 20 ) # repeat a character > end use; "abcabcabcabcabcabcabcabcabcabc"   "xxxxxxxxxxxxxxxxxxxx"  
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* solution 1 *) rep[n_Integer,s_String]:=Apply[StringJoin,ConstantArray[s,{n}]] (* solution 2 -- @@ is the infix form of Apply[] *) rep[n_Integer,s_String]:=StringJoin@@Table[s,{n}] (* solution 3 -- demonstrating another of the large number of looping constructs available *) rep[n_Integer,s_String]:=Nest[StringJoin[s,...
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 ...
#JavaScript
JavaScript
function unique(ary) { // concat() with no args is a way to clone an array var u = ary.concat().sort(); for (var i = 1; i < u.length; ) { if (u[i-1] === u[i]) u.splice(i,1); else i++; } return u; }   var ary = [1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d", "...
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...
#Python
Python
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r ...
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 ...
#MAXScript
MAXScript
e -- Euler's number pi -- pi log x -- natural logarithm log10 x -- log base 10 exp x -- exponantial abs x -- absolute value floor x -- floor ceil x -- ceiling 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 ...
#Mercury
Mercury
  math.pi  % Pi. math.e  % Euler's number. math.sqrt(X)  % Square root of X. math.ln(X)  % Natural logarithm of X. math.log10(X)  % Logarithm to the base 10 of X. math.log2(X)  % Logarithm to the base 2 of X. math.log(B, X)  % Logarithm to the base B of X. math.exp(X)  % e raised to the 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...
#VBScript
VBScript
  Sub remove_lines(filepath,start,number) Set objFSO = CreateObject("Scripting.FileSystemObject") Set InFile = objFSO.OpenTextFile(filepath,1,False) line_count = 1 discard_count = 1 out_txt = "" Do Until InFile.AtEndOfStream line = InFile.ReadLine If line_count <> start Then If InFile.AtEndOfStream = False...
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...
#Wren
Wren
import "os" for Platform import "io" for File   var removeLines = Fn.new { |fileName, startLine, numLines| if (fileName == "" || startLine < 1 || numLines < 1) Fiber.abort("Invalid argument(s).") if (!File.exists(fileName)) Fiber.abort("Can't find %(fileName).") var text = File.read(fileName) System.pri...
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...
#Ol
Ol
  (define content (bytes->string (vec-iter (file->vector "file.txt"))))   (print 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...
#ooRexx
ooRexx
file = 'c:\test.txt' myStream = .stream~new(file) myString = myStream~charIn(,myStream~chars)
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
#Toka
Toka
#! Include the regex library needs regex   #! The two test strings " This is a string" is-data test.1 " Another string" is-data test.2   #! Create a new regex named 'expression' which tries #! to match strings beginning with 'This'. " ^This" regex: expression   #! An array to store the results of the match #! (Element...
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
#TXR
TXR
@(collect) @(coll :gap 0)@mismatch@{match /dog/}@(end)@suffix @(output) @(rep)@{mismatch}cat@(end)@suffix @(end) @(end)
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 ...
#Elixir
Elixir
  IO.puts (String.reverse "asdf") IO.puts (String.reverse "as⃝df̅")  
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...
#Tailspin
Tailspin
  def input: ['---------- 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', '', ...
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...
#Tcl
Tcl
set lines { "---------- 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 line $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...
#X86_Assembly
X86 Assembly
format ELF executable 3 entry start   segment readable writeable buf rb 1   segment readable executable start: mov eax, 3 ; syscall "read" mov ebx, 0 ; stdin mov ecx, buf ; buffer for read byte mov edx, 1 ; len (read one byte) int 80h   cmp eax, 0 ; EOF? jz exit   xor eax, eax ; load read char to eax mo...
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...
#Wren
Wren
var romans = [ [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"] ]   var encode = Fn.new { |n| if (n > 5000 || n < 1) return null var res = ""...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function S = repeat(s , n) S = repmat(s , [1,n]) ; return
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...
#Maxima
Maxima
"$*"(s, n) := apply(sconcat, makelist(s, n))$ infix("$*")$   "abc" $* 5; /* "abcabcabcabcabc" */
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 ...
#jq
jq
[4,3,2,1,1,2,3,4] | unique
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...
#R
R
rref <- function(m) { pivot <- 1 norow <- nrow(m) nocolumn <- ncol(m) for(r in 1:norow) { if ( nocolumn <= pivot ) break; i <- r while( m[i,pivot] == 0 ) { i <- i + 1 if ( norow == i ) { i <- r pivot <- pivot + 1 if ( nocolumn == pivot ) return(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 ...
#Metafont
Metafont
show mexp(256);  % outputs e; since MF uses mexp(x) = exp(x/256) show 3.14159;  % no pi constant built in; of course we can define it  % in several ways... even computing  % C/2r (which would be funny since MF handles paths,  % and a circle is a path...) show sqrt2...
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 ...
#min
min
e  ; e pi  ; π sqrt  ; square root log10  ; common logarithm log2  ; binary logarithm  ; no exponential  ; no absolute value floor  ; greatest whole number smaller than or equal ceil  ; smallest whole number greater than or equal trunc  ; remove the fractional part (i.e. round towards 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...
#zkl
zkl
fcn deleteLinesM(fname, start,num){ blob:=File(fname).read(); // file to memory n:=blob.seek(Void,start-1); // seek to line and remember it blob.del(n,blob.seek(Void,num)-n);   File.stdout.write(blob); } deleteLinesM("nn.zkl", 2,5);
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...
#Oz
Oz
declare FileHandle = {New Open.file init(name:"test.txt")} FileContents = {FileHandle read(size:all list:$)} in {FileHandle close} {System.printInfo FileContents}
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...
#Panda
Panda
file:readme.txt .text
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
#UNIX_Shell
UNIX Shell
s="I am a string" if [[ $s =~ str..g$ ]]; then echo "the string ends with 'str..g'" fi