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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Java
Java
import java.io.File; public class FileRenameTest { public static boolean renameFile(String oldname, String newname) { // File (or directory) with old name File file = new File(oldname);   // File (or directory) with new name File file2 = new File(newname);   // Rename file (or directory) boolean success = file.renameTo(file2); return success; } public static void test(String type, String oldname, String newname) { System.out.println("The following " + type + " called " + oldname + ( renameFile(oldname, newname) ? " was renamed as " : " could not be renamed into ") + newname + "." ); } public static void main(String args[]) { test("file", "input.txt", "output.txt"); test("file", File.separator + "input.txt", File.separator + "output.txt"); test("directory", "docs", "mydocs"); test("directory", File.separator + "docs" + File.separator, File.separator + "mydocs" + File.separator); } }
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#J
J
([:;@|.[:<;.1 ' ',]);._2]0 :0 ---------- 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 ----------------------- ) ------------ Fire and Ice ----------   Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.   ... last paragraph elided ...   ----------------------- Robert Frost  
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#Java
Java
public class ReverseWords {   static final String[] 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 ----------------------- "};   public static void main(String[] args) { for (String line : lines) { String[] words = line.split("\\s"); for (int i = words.length - 1; i >= 0; i--) System.out.printf("%s ", words[i]); System.out.println(); } } }
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
put .trans: ['A'..'Z','a'..'z'] => ['N'..'Z','A'..'M','n'..'z','a'..'m'] for $*IN.lines
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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#PureBasic
PureBasic
#SymbolCount = 12 ;0 based count DataSection denominations: Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12   denomValues: Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order EndDataSection   ;-setup Structure romanNumeral symbol.s value.i EndStructure   Global Dim refRomanNum.romanNumeral(#SymbolCount)   Restore denominations For i = 0 To #SymbolCount Read.s refRomanNum(i)\symbol Next   Restore denomValues For i = 0 To #SymbolCount Read refRomanNum(i)\value Next   Procedure.s decRoman(n) ;converts a decimal number to a roman numeral Protected roman$, i   For i = 0 To #SymbolCount Repeat If n >= refRomanNum(i)\value roman$ + refRomanNum(i)\symbol n - refRomanNum(i)\value Else Break EndIf ForEver Next   ProcedureReturn roman$ EndProcedure   If OpenConsole()   PrintN(decRoman(1999)) ;MCMXCIX PrintN(decRoman(1666)) ;MDCLXVI PrintN(decRoman(25)) ;XXV PrintN(decRoman(954)) ;CMLIV   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#Simula
Simula
BEGIN   INTEGER PROCEDURE FROMROMAN(S); TEXT S; BEGIN PROCEDURE P(INTVAL, NUM); INTEGER INTVAL; TEXT NUM; BEGIN INTEGER NLEN; NLEN := NUM.LENGTH; WHILE INDEX + NLEN - 1 <= SLEN AND THEN S.SUB(INDEX, NLEN) = NUM DO BEGIN RESULT := RESULT + INTVAL; INDEX := INDEX + NLEN; END WHILE; END P; INTEGER RESULT, INDEX, SLEN; SLEN := S.LENGTH; INDEX := 1; P( 1000, "M" ); P( 900, "CM" ); P( 500, "D" ); P( 400, "CD" ); P( 100, "C" ); P( 90, "XC" ); P( 50, "L" ); P( 40, "XL" ); P( 10, "X" ); P( 9, "IX" ); P( 5, "V" ); P( 4, "IV" ); P( 1, "I" ); FROMROMAN := RESULT; END FROMROMAN;   TEXT T; FOR T :- "MCMXC", "MMVIII", "MDCLXVI" DO BEGIN OUTTEXT("ROMAN """); OUTTEXT(T); OUTTEXT(""" => "); OUTINT(FROMROMAN(T), 0); OUTIMAGE; END FOR;   END PROGRAM;  
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ColdFusion
ColdFusion
  <cfset word = 'ha'> <Cfset n = 5> <Cfoutput> <Cfloop from="1" to="#n#" index="i">#word#</Cfloop> </Cfoutput>  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Harbour
Harbour
FUNCTION Addsub( x, y ) 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.
#Haskell
Haskell
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#Bracmat
Bracmat
2 3 5 7 11 13 17 19 cats 222 (-100.2) "+11" (1.1) "+7" (7.) 7 5 5 3 2 0 (4.4) 2:?LIST   (A= ( Hashing = h elm list . new$hash:?h & whl ' ( !arg:%?elm ?arg & ( (h..find)$str$!elm | (h..insert)$(str$!elm.!elm) ) ) & :?list & (h..forall) $ ( = .!arg:(?.?arg)&!arg !list:?list ) & !list ) & put$("Solution A:" Hashing$!LIST \n,LIN) );   (B= ( backtracking = answr elm .  :?answr &  !arg  :  ? (  %?`elm  ? ( !elm ? | &!answr !elm:?answr ) & ~ ) | !answr ) & put$("Solution B:" backtracking$!LIST \n,LIN) );   (C= ( summing = sum car LIST .  !arg:?LIST & 0:?sum & whl ' ( !LIST:%?car ?LIST & (.!car)+!sum:?sum ) & whl ' ( !sum:#*(.?el)+?sum & !el !LIST:?LIST ) & !LIST ) & put$("Solution C:" summing$!LIST \n,LIN) );   ( !A & !B & !C & )
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#CLU
CLU
% Recaman sequence recaman = cluster is new, fetch rep = array[int]   new = proc () returns (cvt) a: rep := rep$predict(0,1000000) rep$addh(a,0) return(a) end new    % Find the N'th element of the Recaman sequence fetch = proc (a: cvt, n: int) returns (int) if n > rep$high(a) then extend(a,n) end return(a[n]) end fetch    % See if N has already been generated prev = proc (a: rep, n: int) returns (bool) for el: int in rep$elements(a) do if el = n then return(true) end end return(false) end prev    % Generate members of the sequence until 'top' is reached extend = proc (a: rep, top: int) while rep$high(a) < top do n: int := rep$high(a) + 1 sub: int := a[n-1] - n add: int := a[n-1] + n if sub>0 cand ~prev(a, sub) then rep$addh(a, sub) else rep$addh(a, add) end end end extend end recaman     start_up = proc () po: stream := stream$primary_output() A: recaman := recaman$new()    % Print the first 15 members stream$puts(po, "First 15 items:") for i: int in int$from_to(0, 14) do stream$puts(po, " " || int$unparse(A[i])) end    % Find the first duplicated number begin i: int := 0 while true do i := i + 1 for j: int in int$from_to(0, i-1) do if A[i]=A[j] then exit found(i, A[i]) end end end end except when found(i, n: int): stream$putl(po, "\nFirst duplicated number: A(" || int$unparse(i) || ") = " || int$unparse(n)) end    % Find the amount of terms needed to generate all integers 0..1000 begin seen: array[bool] := array[bool]$fill(0,1001,false) left: int := 1001 n: int := -1 while left > 0 do n := n + 1 if A[n] <= 1000 cand ~seen[A[n]] then left := left - 1 seen[A[n]] := true end end stream$putl(po, "Terms needed to generate [0..1000]: " || int$unparse(n)) end end start_up
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#Comal
Comal
0010 DIM a#(0:100) 0020 // 0030 // Print the first 15 items 0040 PRINT "First 15 items: ", 0050 FOR i#:=0 TO 14 DO PRINT reca#(i#); 0060 PRINT 0070 // 0080 // Find and print the first repeated item 0090 i#:=15 0100 WHILE NOT find#(i#,reca#(i#)) DO i#:+1 0110 PRINT "First repeated item: A(",i#,") = ",a#(i#) 0120 // 0130 // Generate the n'th member of the Recaman sequence 0140 FUNC reca#(n#) 0150 IF n#=0 THEN RETURN 0 0160 a#(n#):=a#(n#-1)-n# 0180 IF a#(n#)<=0 OR find#(n#,a#(n#)) THEN a#(n#):=a#(n#-1)+n# 0190 RETURN a#(n#) 0200 ENDFUNC reca# 0210 // 0220 // See if a number occurs before the n'th member of the Recaman sequence 0230 FUNC find#(n#,num#) 0240 FOR x#:=0 TO n#-1 DO IF a#(x#)=num# THEN RETURN x# 0250 RETURN 0 0260 ENDFUNC find# 0270 END
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 will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#ALGOL_68
ALGOL 68
MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc # MODE VEC = [0]FIELD; MODE MAT = [0,0]FIELD;   PROC to reduced row echelon form = (REF MAT m)VOID: ( INT lead col := 2 LWB m;   FOR this row FROM LWB m TO UPB m DO IF lead col > 2 UPB m THEN return FI; INT other row := this row; WHILE m[other row,lead col] = 0 DO other row +:= 1; IF other row > UPB m THEN other row := this row; lead col +:= 1; IF lead col > 2 UPB m THEN return FI FI OD; IF this row /= other row THEN VEC swap = m[this row,lead col:]; m[this row,lead col:] := m[other row,lead col:]; m[other row,lead col:] := swap FI; FIELD scale = 1/m[this row,lead col]; IF scale /= 1 THEN m[this row,lead col] := 1; FOR col FROM lead col+1 TO 2 UPB m DO m[this row,col] *:= scale OD FI; FOR other row FROM LWB m TO UPB m DO IF this row /= other row THEN REAL scale = m[other row,lead col]; m[other row,lead col]:=0; FOR col FROM lead col+1 TO 2 UPB m DO m[other row,col] -:= scale*m[this row,col] OD FI OD; lead col +:= 1 OD; return: EMPTY );   [3,4]FIELD mat := ( ( 1, 2, -1, -4), ( 2, 3, -1, -11), (-2, 0, -3, 22) );   to reduced row echelon form( mat );   FORMAT real repr = $g(-7,4)$, vec repr = $"("n(2 UPB mat-1)(f(real repr)", ")f(real repr)")"$, mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;   printf((mat repr, mat, $l$))
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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#ALGOL_W
ALGOL W
begin real t, u; t := 10; u := -2.3; i_w := 4; s_w := 0; r_format := "A"; r_d := 4; r_w := 9; % set output format % write( " e: ", exp( 1 ) );  % e  % write( " pi: ", pi );  % pi  % write( " root t: ", sqrt( t ) );  % square root  % write( " log t: ", log( t ) );  % log base 10  % write( " ln t: ", ln( t ) );  % log base e  % write( " exp u: ", exp( u ) );  % exponential  % write( " abs u: ", abs u );  % absolute value % write( " floor pi: ", entier( pi ) );  % floor  % write( "ceiling pi: ", - entier( - pi ) ); % ceiling  %  % the raise-to-the-power operator is "**" - it only allows integers for the power % write( " pi cubed: ", pi ** 3 ) % use exp( ln( x ) * y ) for general x^y % end.
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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#ARM_Assembly
ARM Assembly
  /* functions not availables */  
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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#D
D
import std.stdio, std.file, std.string;   void main() { deleteLines("deleteline_test.txt", 1, 2); }   void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--;   if (!exists(name) || !isFile(name)) throw new FileException("File not found");   auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!");   auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#BASIC
BASIC
DIM f AS STRING OPEN "file.txt" FOR BINARY AS 1 f = SPACE$(LOF(1)) GET #1, 1, f CLOSE 1
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#BBC_BASIC
BBC BASIC
file% = OPENIN("input.txt") strvar$ = "" WHILE NOT EOF#file% strvar$ += CHR$(BGET#file%) ENDWHILE CLOSE #file%
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Scala
Scala
object ListMethods extends App {   private val obj = new { def examplePublicInstanceMethod(c: Char, d: Double) = 42   private def examplePrivateInstanceMethod(s: String) = true } private val clazz = obj.getClass   println("All public methods (including inherited):") clazz.getMethods.foreach(m => println(s"${m}"))   println("\nAll declared fields (excluding inherited):") clazz.getDeclaredMethods.foreach(m => println(s"${m}}"))   }
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Sidef
Sidef
class Example { method foo { } method bar(arg) { say "bar(#{arg})" } }   var obj = Example() say obj.methods.keys.sort #=> ["bar", "call", "foo", "new"]   var meth = obj.methods.item(:bar) # `LazyMethod` representation for `obj.bar()` meth(123) # calls obj.bar()
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#F.23
F#
let isPrefix p (s : string) = s.StartsWith(p) let getPrefix n (s : string) = s.Substring(0,n)   let repPrefixOf str = let rec isRepeatedPrefix p s = if isPrefix p s then isRepeatedPrefix p (s.Substring (p.Length)) else isPrefix s p   let rec getLongestRepeatedPrefix n = if n = 0 then None elif isRepeatedPrefix (getPrefix n str) str then Some(getPrefix n str) else getLongestRepeatedPrefix (n-1)   getLongestRepeatedPrefix (str.Length/2)   [<EntryPoint>] let main argv = printfn "Testing for rep-string (and showing the longest repeated prefix in case):" [ "1001110011" "1110111011" "0010010010" "1010101010" "1111111111" "0100101101" "0100100" "101" "11" "00" "1" ] |> List.map (fun s -> match repPrefixOf s with | None -> s + ": NO" | Some(p) -> s + ": YES ("+ p + ")") |> List.iter (printfn "%s") 0
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
#Genie
Genie
[indent=4] /* Regular expressions, in Genie */   init var sentence = "This is a sample sentence." try var re = new Regex("s[ai]mple")   if re.match(sentence) print "matched '%s' in '%s'", re.get_pattern(), sentence   var offs = 0 print("replace with 'different': %s", re.replace(sentence, sentence.length, offs, "different"))   except err:RegexError print err.message
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
#Go
Go
package main import "fmt" import "regexp"   func main() { str := "I am the original string"   // Test matched, _ := regexp.MatchString(".*string$", str) if matched { fmt.Println("ends with 'string'") }   // Substitute pattern := regexp.MustCompile("original") result := pattern.ReplaceAllString(str, "modified") fmt.Println(result) }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BaCon
BaCon
OPTION UTF8 TRUE s$ = "asdf" PRINT REVERSE$(s$)
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Nanoquery
Nanoquery
def repeat(f,n) for i in range(1, n) f() end end   def procedure() println "Example" end   repeat(procedure, 3)
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type systems, only the user root would have sufficient permissions in the filesystem root.)
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject") fso.MoveFile("input.txt", "output.txt") fso.MoveFile("c:/input.txt", "c:/output.txt") fso.MoveFolder("docs", "mydocs") fso.MoveFolder("c:/docs", "c:/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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#JavaScript
JavaScript
var strReversed = "---------- Ice and Fire ------------\n\ \n\ fire, in end will world the say Some\n\ ice. in say Some\n\ desire of tasted I've what From\n\ fire. favor who those with hold I\n\ \n\ ... elided paragraph last ...\n\ \n\ Frost Robert -----------------------";   function reverseString(s) { return s.split('\n').map( function (line) { return line.split(/\s/).reverse().join(' '); } ).join('\n'); }   console.log( reverseString(strReversed) );
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#RapidQ
RapidQ
  function ROT13 (InputTxt as string) as string dim i as integer, ascVal as byte Result = ""   for i = 1 to len(InputTxt) ascVal = asc(InputTxt[i])   select case ascVal case 65 to 77, 97 to 109 Result = Result + chr$(ascVal + 13) case 78 to 90, 110 to 122 Result = Result + chr$(ascVal - 13) case else Result = Result + chr$(ascVal) end select next end function   Input "Text to encode: "; a$ Print ROT13(a$) Input "Press a key to end..."; a$    
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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Python
Python
import roman print(roman.toRoman(2022))
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#SNOBOL4
SNOBOL4
* Roman to Arabic define('arabic(n)s,ch,val,sum,x') :(arabic_end) arabic s = 'M1000 D500 C100 L50 X10 V5 I1 ' n = reverse(n) arab1 n len(1) . ch = :f(arab2) s ch break(' ') . val val = lt(val,x) (-1 * val) sum = sum + val; x = val  :(arab1) arab2 arabic = sum  :(return) arabic_end   * Test and display tstr = 'MMX MCMXCIX MCDXCII MLXVI CDLXXVI " tloop tstr break(' ') . r span(' ') = :f(out) astr = astr r '=' arabic(r) ' ' :(tloop) out output = astr end
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Common_Lisp
Common Lisp
(defun repeat-string (n string) (with-output-to-string (stream) (loop repeat n do (write-string string stream))))
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Icon_and_Unicon
Icon and Unicon
procedure retList() # returns as ordered list return [1,2,3] end   procedure retSet() # returns as un-ordered list insert(S := set(),3,1,2) return S end   procedure retLazy() # return as a generator suspend 1|2|3 end   procedure retTable() # return as a table T := table() T["A"] := 1 T["B"] := 2 T["C"] := 3 return T end   record retdata(a,b,c)   procedure retRecord() # return as a record, least general method return retdata(1,2,3) end
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#Brat
Brat
some_array = [1 1 2 1 'redundant' [1 2 3] [1 2 3] 'redundant']   unique_array = some_array.unique
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. RECAMAN.   DATA DIVISION. WORKING-STORAGE SECTION. 01 RECAMAN-SEQUENCE COMP. 02 A PIC 999 OCCURS 99 TIMES INDEXED BY I. 02 N PIC 999 VALUE 0.   01 VARIABLES COMP. 02 ADDC PIC S999. 02 SUBC PIC S999. 02 SPTR PIC 99 VALUE 1.   01 OUTPUT-FORMAT. 02 OUTI PIC Z9. 02 OUTN PIC BZ9. 02 OUTS PIC X(79).   PROCEDURE DIVISION. BEGIN. PERFORM GENERATE-NEXT-ITEM 15 TIMES. PERFORM COLLATE-ITEM VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN 15. DISPLAY 'First 15 items:' OUTS.   FIND-REPEATING. PERFORM GENERATE-NEXT-ITEM. SET I TO 1. SEARCH A VARYING I WHEN I IS NOT LESS THAN N NEXT SENTENCE WHEN A(I) IS EQUAL TO A(N) SUBTRACT 1 FROM N GIVING OUTI MOVE A(N) TO OUTN DISPLAY 'First repeated item: A(' OUTI ') =' OUTN STOP RUN. GO TO FIND-REPEATING.   GENERATE-NEXT-ITEM. IF N IS EQUAL TO ZERO MOVE ZERO TO A(1) ELSE ADD N, A(N) GIVING ADDC SUBTRACT N FROM A(N) GIVING SUBC IF SUBC IS NOT GREATER THAN ZERO MOVE ADDC TO A(N + 1) ELSE SET I TO 1 SEARCH A VARYING I WHEN I IS NOT LESS THAN N MOVE SUBC TO A(N + 1) WHEN A(I) IS EQUAL TO SUBC MOVE ADDC TO A(N + 1). ADD 1 TO N.   COLLATE-ITEM. MOVE A(I) TO OUTN. STRING OUTN DELIMITED BY SIZE INTO OUTS WITH POINTER SPTR.
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 will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#ALGOL_W
ALGOL W
begin  % replaces M with it's reduced row echelon form  %  % M should have bounds ( 0 :: rMax, 0 :: cMax )  % procedure toReducedRowEchelonForm ( real array M ( *, * )  ; integer value rMax, cMax ) ; begin integer lead; lead := 0; for r := 0 until rMax do begin integer i; if lead > cMax then goto done; i := r; while M( i, lead ) = 0 do begin i := i + 1; if rMax = i then begin i  := r; lead := lead + 1; if cMax = lead then goto done end if_rowCount_eq_i end while_M_i_lead_eq_0 ;  % Swap rows i and r % for c := 0 until cMax do begin real t; t  := M( i, c ); M( i, c ) := M( r, c ); M( r, c ) := t end swap_rows_i_and_r ; If M( r, lead ) not = 0 then begin  % divide row r by M[r, lead] % real rLead; rLead := M( r, lead ); for c := 0 until cMax do M( r, c ) := M( r, c ) / rLead end if_M_r_lead_ne_0 ; for i := 0 until rMax do begin if i not = r then begin  % Subtract M[i, lead] multiplied by row r from row i % real iLead; iLead := M( i, lead ); for c := 0 until cMax do M( i, c ) := M( i, c ) - ( iLead * M( r, c ) ) end if_i_ne_r end for_i ; lead := lead + 1 end for_r ; done: end toReducedRowEchelonForm ;  % test the toReducedRowEchelonForm procedure % begin real array m( 0 :: 2, 0 :: 3 ); M( 0, 0 ) := 1; M( 0, 1 ) := 2; M( 0, 2 ) := -1; M( 0, 3 ) := -4; M( 1, 0 ) := 2; M( 1, 1 ) := 3; M( 1, 2 ) := -1; M( 1, 3 ) := -11; M( 2, 0 ) := -2; M( 2, 1 ) := 0; M( 2, 2 ) := -3; M( 2, 3 ) := 22; toReducedRowEchelonForm( M, 2, 3 ); r_format := "A"; s_w := 0; r_w := 6; r_d := 1; % set output formating % for r := 0 until 2 do begin write( M( r, 0 ) ); for c := 1 until 3 do writeon( " ", M( r, c ) ); end for_r end end.
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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#Arturo
Arturo
print ["Euler:" e] print ["Pi:" pi]   print ["sqrt 2.0:" sqrt 2.0] print ["ln 100:" ln 100] print ["log(10) 100:" log 100 10] print ["exp 3:" exp 3] print ["abs -1:" abs neg 1] print ["floor 23.536:" floor 23.536] print ["ceil 23.536:" ceil 23.536] print ["2 ^ 8:" 2 ^ 8]
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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#Delphi
Delphi
  program Remove_lines_from_a_file_using_TStringDynArray;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IoUtils;   // zero started Index procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal); begin if not FileExists(FileName) then exit;   var lines := TFile.ReadAllLines(FileName);   Delete(lines, Index, Line_count); TFile.WriteAllLines(FileName, lines); end;   begin // Remove 2th & 3td line of file RemoveLines('input.txt', 1, 2); end.
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#Blue
Blue
global _start   : syscall ( num:eax -- result:eax ) syscall ;   : exit ( status:edi -- noret ) 60 syscall ; : bye ( -- noret ) 0 exit ; : die ( err:eax -- noret ) neg exit ;   : unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ; : ordie ( result -- ) unwrap drop ;   : open ( pathname:edi flags:esi -- fd:eax ) 2 syscall unwrap ; : close ( fd:edi -- ) 3 syscall ordie ;   48 resb stat_buf 8 resb file-size 88 resb padding   : fstat ( fd:edi buf:esi -- ) 5 syscall ordie ;   1 const prot_read 2 const map_private   : mmap ( fd:r8d len:esi addr:edi off:r9d prot:edx flags:r10d -- buf:eax ) 9 syscall unwrap ; : munmap ( addr:edi len:esi -- ) 11 syscall ordie ;   1 resd fd 0 const read-only   : open-file ( pathname:edi -- ) read-only open fd ! ; : read-file-size ( -- ) fd @ stat_buf fstat ; : map-file ( fd len -- buf ) 0 0 prot_read map_private mmap ; : map-file ( -- buf ) fd @ file-size @ map-file ; : unmap-file ( buf -- ) file-size @ munmap ; : close-file ( -- ) fd @ close ;   : open-this-file ( -- ) s" read_entire_file.blue" drop open-file ;   : _start ( -- noret ) open-this-file read-file-size map-file \ do something ... unmap-file close-file bye ;  
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#BQN
BQN
•file.Chars "file" •file.Bytes "file"   # Shorthands: •FChars "file" •FBytes "file"  
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Tcl
Tcl
% info object methods ::oo::class -all -private <cloned> create createWithNamespace destroy eval new unknown variable varname
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Wren
Wren
#! instance_methods(m, n, o) #! instance_properties(p, q, r) class C { construct new() {}   m() {}   n() {}   o() {}   p {}   q {}   r {} }   var c = C.new() // create an object of type C System.print("List of instance methods available for object 'c':") for (method in c.type.attributes.self["instance_methods"]) System.print(method.key)
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Factor
Factor
USING: formatting grouping kernel math math.ranges qw sequences ; IN: rosetta-code.rep-string   : (find-rep-string) ( str -- str ) dup dup length 2/ [1,b] [ <groups> [ head? ] monotonic? ] with find nip dup [ head ] [ 2drop "N/A" ] if ;   : find-rep-string ( str -- str ) dup length 1 <= [ drop "N/A" ] [ (find-rep-string) ] if ;   qw{ 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 } "Shortest cycle:\n\n" printf [ dup find-rep-string "%-10s -> %s\n" printf ] each
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Forth
Forth
: rep-string ( caddr1 u1 -- caddr2 u2 ) \ u2=0: not a rep-string 2dup dup >r r@ 2/ /string begin 2over 2over string-prefix? 0= over r@ < and while -1 /string repeat r> swap - >r 2drop r> ;   : test ( caddr u -- ) 2dup type ." has " rep-string ?dup 0= if drop ." no " else type ." as " then ." repeating substring" cr ; : tests s" 1001110011" test s" 1110111011" test s" 0010010010" test s" 1010101010" test s" 1111111111" test s" 0100101101" test s" 0100100" test s" 101" test s" 11" test s" 00" test s" 1" test ;
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
#Groovy
Groovy
import java.util.regex.*;   def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" def pepper = "Peter Piper picked a peck of pickled peppers"     println "=== Regular-expression String syntax (/string/) ===" def woodRE = /[Ww]o\w+d/ def piperRE = /[Pp]\w+r/ assert woodRE instanceof String && piperRE instanceof String assert (/[Ww]o\w+d/ == "[Ww]o\\w+d") && (/[Pp]\w+r/ == "[Pp]\\w+r") println ([woodRE: woodRE, piperRE: piperRE]) println ()     println "=== Pattern (~) operator ===" def woodPat = ~/[Ww]o\w+d/ def piperPat = ~piperRE assert woodPat instanceof Pattern && piperPat instanceof Pattern   def woodList = woodchuck.split().grep(woodPat) println ([exactTokenMatches: woodList]) println ([exactTokenMatches: pepper.split().grep(piperPat)]) println ()     println "=== Matcher (=~) operator ===" def wwMatcher = (woodchuck =~ woodRE) def ppMatcher = (pepper =~ /[Pp]\w+r/) def wpMatcher = (woodchuck =~ /[Pp]\w+r/) assert wwMatcher instanceof Matcher && ppMatcher instanceof Matcher assert wwMatcher.toString() == woodPat.matcher(woodchuck).toString() assert ppMatcher.toString() == piperPat.matcher(pepper).toString() assert wpMatcher.toString() == piperPat.matcher(woodchuck).toString()   println ([ substringMatches: wwMatcher.collect { it }]) println ([ substringMatches: ppMatcher.collect { it }]) println ([ substringMatches: wpMatcher.collect { it }]) println ()     println "=== Exact Match (==~) operator ===" def containsWoodRE = /.*/ + woodRE + /.*/ def containsPiperRE = /.*/ + piperRE + /.*/ def wwMatches = (woodchuck ==~ containsWoodRE) assert wwMatches instanceof Boolean def wwNotMatches = ! (woodchuck ==~ woodRE) def ppMatches = (pepper ==~ containsPiperRE) def pwNotMatches = ! (pepper ==~ containsWoodRE) def wpNotMatches = ! (woodchuck ==~ containsPiperRE) assert wwMatches && wwNotMatches && ppMatches && pwNotMatches && pwNotMatches   println ("'${woodchuck}' ${wwNotMatches ? 'does not' : 'does'} match '${woodRE}' exactly") println ("'${woodchuck}' ${wwMatches ? 'does' : 'does not'} match '${containsWoodRE}' exactly")
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BASIC
BASIC
FUNCTION reverse$(a$) b$ = "" FOR i = 1 TO LEN(a$) b$ = MID$(a$, i, 1) + b$ NEXT i reverse$ = b$ END FUNCTION
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Nim
Nim
proc example = echo "Example"   # Ordinary procedure proc repeatProc(fn: proc, n: int) = for x in 0..<n: fn()   repeatProc(example, 4)   # Template (code substitution), simplest form of metaprogramming # that Nim has template repeatTmpl(n: int, body: untyped): untyped = for x in 0..<n: body   # This gets rewritten into a for loop repeatTmpl 4: example()   import std/macros # A macro which takes some code block and returns code # with that code block repeated n times. Macros run at # compile-time macro repeatMacro(n: static[int], body: untyped): untyped = result = newStmtList()   for x in 0..<n: result.add body   # This gets rewritten into 4 calls to example() # at compile-time repeatMacro 4: example()  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Objeck
Objeck
class Repeat { function : Main(args : String[]) ~ Nil { Repeat(Example() ~ Nil, 3); }   function : Repeat(e : () ~ Nil, i : Int) ~ Nil { while(i-- > 0) { e(); }; }   function : Example() ~ Nil { "Example"->PrintLine(); } }
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Joy
Joy
  "input.txt" "output.txt" frename "/input.txt" "/output.txt" frename "docs" "mydocs" frename "/docs" "/mydocs" frename.  
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Jsish
Jsish
/* File rename, in jsish */ try { File.rename('input.txt', 'output.txt', false); } catch (str) { puts(str); }   exec('touch input.txt'); puts("overwrite set true if output.txt exists"); File.rename('input.txt', 'output.txt', true);   try { File.rename('docs', 'mydocs', false); } catch (str) { puts(str); } try { File.rename('/docs', '/mydocs', false); } catch (str) { puts(str); }
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#jq
jq
split("[ \t\n\r]+") | 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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raven
Raven
define rot13 use $str $str each chr dup m/[A-Ma-m]/ if ord 13 + chr else dup m/[N-Zn-z]/ if ord 13 - chr $str length list "" join   "12!ABJURER nowhere" dup print "\nas rot13 is\n" print rot13 print "\n" print
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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#QBasic
QBasic
DIM SHARED arabic(0 TO 12) DIM SHARED roman$(0 TO 12)   FUNCTION toRoman$ (value) LET result$ = "" FOR i = 0 TO 12 DO WHILE value >= arabic(i) LET result$ = result$ + roman$(i) LET value = value - arabic(i) LOOP NEXT i toRoman$ = result$ END FUNCTION   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"   'Testing PRINT "2009 = "; toRoman$(2009) PRINT "1666 = "; toRoman$(1666) PRINT "3888 = "; toRoman$(3888)
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#SPL
SPL
r2a(r)= n = [1,5,10,50,100,500,1000] a,m = 0 > i, #.size(r)..1, -1 v,c = n[#.pos("IVXLCDM",#.mid(r,i))]  ? v<m, v = -v  ? c>m, m = c a += v < <= a .   t = ["MMXI","MIM","MCMLVI","MDCLXVI","XXCIII","LXXIIX","IIIIX"] > i, 1..#.size(t,1) #.output(t[i]," = ",r2a(t[i])) <
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Crystal
Crystal
  puts "ha" * 5  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#J
J
1 2+3 4 4 6
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Java
Java
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap;   // ============================================================================= public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R";   // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; }   RReturnMultipleVals lcl = new RReturnMultipleVals();   Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); // values returned in a bespoke object System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal());   List<Object> rvl = lcl.getPairFromList(nv_, sv_); // values returned in a Java Collection object System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1));   Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); // values returned in a Java Collection object System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Return a bespoke object. // Permits any number and type of value to be returned public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Exploit Java Collections classes to assemble a collection of results. // This example uses java.util.List public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Exploit Java Collections classes to assemble a collection of results. // This example uses java.util.Map public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; }   // =========================================================================== private static class Pair<L, R> { private L leftVal; private R rightVal;   public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#C
C
#include <stdio.h> #include <stdlib.h>   struct list_node {int x; struct list_node *next;}; typedef struct list_node node;   node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL;   for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}}   return start;}   int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#D
D
import std.stdio;   void main() { int[] a; bool[int] used; bool[int] used1000; bool foundDup;   a ~= 0; used[0] = true; used1000[0] = true;   int n = 1; while (n <= 15 || !foundDup || used1000.length < 1001) { int next = a[n - 1] - n; if (next < 1 || (next in used) !is null) { next += 2 * n; } bool alreadyUsed = (next in used) !is null; a ~= next; if (!alreadyUsed) { used[next] = true; if (0 <= next && next <= 1000) { used1000[next] = true; } } if (n == 14) { writeln("The first 15 terms of the Recaman sequence are: ", a); } if (!foundDup && alreadyUsed) { writefln("The first duplicated term is a[%d] = %d", n, next); foundDup = true; } if (used1000.length == 1001) { writefln("Terms up to a[%d] are needed to generate 0 to 1000", n); } n++; } }
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 will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#AutoHotkey
AutoHotkey
ToReducedRowEchelonForm(M){ rowCount := M.Count() ; the number of rows in M columnCount := M.1.Count() ; the number of columns in M r := lead := 1 while (r <= rowCount) { if (columnCount < lead) return M i := r while (M[i, lead] = 0) { i++ if (rowCount+1 = i) { i := r, lead++ if (columnCount+1 = lead) return M } } if (i<>r) for col, v in M[i] ; Swap rows i and r tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal   num := M[r, lead] if (M[r, lead] <> 0) for col, val in M[r] M[r, col] /= num ; If M[r, lead] is not 0 divide row r by M[r, lead]   i := 2 while (i <= rowCount) { num := M[i, lead] if (i <> r) for col, val in M[i] ; Subtract M[i, lead] multiplied by row r from row i M[i, col] -= num * M[r, col] i++ } lead++, r++ } 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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#Asymptote
Asymptote
real e = exp(1); // e not available write("e = ", e); write("pi = ", pi);   real x = 12.345; real y = 1.23;   write("sqrt = ", sqrt(2)); // square root write("ln = ", log(e)); // natural logarithm base e write("log = ", log10(x)); // base 10 logarithm write("log1p = ", log1p(x)); // log (1+x) write("exp = ", exp(e)); // exponential write("abs = ", abs(-1)); // absolute value write("fabs = ", fabs(-1)); // absolute value write("floor = ", floor(-e)); // floor write("ceil = ", ceil(-e)); // ceiling write("power = ", x ^ y); // power write("power = ", 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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#ECL
ECL
  IMPORT STD; RemoveLines(logicalfile, startline, numlines) := FUNCTIONMACRO EndLine := startline + numlines - 1; RecCnt  := COUNT(logicalfile); Res := logicalfile[1..startline-1] + logicalfile[endline+1..]; RETURN WHEN(IF(RecCnt < EndLine,logicalfile,Res), IF(RecCnt < EndLine,STD.System.Log.addWorkunitWarning('Attempted removal past end of file-removal ignored'))); ENDMACRO;  
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#Bracmat
Bracmat
> Keep cell 0 at 0 as a sentinel value ,[>,] Read into successive cells until EOF <[<] Go all the way back to the beginning >[.>] Print successive cells while nonzero
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#zkl
zkl
methods:=List.methods; methods.println(); List.method(methods[0]).println(); // == .Method(name) == .BaseClass(name)
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#FreeBASIC
FreeBASIC
  Data "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", ""   Function rep(c As String, n As Integer) As String Dim As String r   For i As Integer = 1 To n r = r + c Next i Return r End Function   Do Dim As String p, b = "", t, s Read p : If p = "" Then Exit Do Dim As Integer l = Len(p), m = Int(l / 2)   For i As Integer = m To 1 Step -1 t = Left(p, i) s = rep(t, l / i + 1) If p = Left(s, l) Then b = t : Exit For Next i   If b = "" Then Print p; " no es una cadena repetida" Else Print p; " secuencia m s larga: "; b End If Loop Sleep  
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
#Haskell
Haskell
import Text.Regex   str = "I am a string"   case matchRegex (mkRegex ".*string$") str of Just _ -> putStrLn $ "ends with 'string'" Nothing -> return ()
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion call :reverse %1 res echo %res% goto :eof   :reverse set str=%~1 set cnt=0 :loop if "%str%" equ "" ( goto :eof ) set chr=!str:~0,1! set str=%str:~1% set %2=%chr%!%2! goto loop
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#OCaml
OCaml
let repeat ~f ~n = for i = 1 to n do f () done   let func () = print_endline "Example"   let () = repeat ~n:4 ~f:func  
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Julia
Julia
  mv("input.txt", "output.txt") mv("docs", "mydocs") mv("/input.txt", "/output.txt") mv("/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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Kotlin
Kotlin
// version 1.0.6   /* testing on Windows 10 which needs administrative privileges to rename files in the root */   import java.io.File   fun main(args: Array<String>) { val oldPaths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") val newPaths = arrayOf("output.txt", "mydocs", "c:\\output.txt", "c:\\mydocs") var oldFile: File var newFile: File for (i in 0 until oldPaths.size) { oldFile = File(oldPaths[i]) newFile = File(newPaths[i]) if (oldFile.renameTo(newFile)) println("${oldPaths[i]} successfully renamed to ${newPaths[i]}") else println("${oldPaths[i]} could not be renamed") } }
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#Jsish
Jsish
var strReversed = "---------- Ice and Fire ------------\n 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 \n... elided paragraph last ...\n Frost Robert -----------------------";   function reverseString(s) { return s.split('\n').map( function (line) { return line.split().reverse().join(' '); } ).join('\n'); }   ;reverseString('Hey you, Bub!'); ;strReversed; ;reverseString(strReversed);   /* =!EXPECTSTART!= reverseString('Hey you, Bub!') ==> Bub! you, Hey strReversed ==> ---------- 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 ----------------------- reverseString(strReversed) ==> ------------ Fire and Ice ----------   Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.   ... last paragraph elided ...   ----------------------- Robert Frost =!EXPECTEND!= */
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REBOL
REBOL
rebol [ Title: "Rot-13" URL: http://rosettacode.org/wiki/Rot-13 ]   ; Test data has upper and lower case characters as well as characters ; that should not be transformed, like numbers, spaces and symbols.   text: "This is a 28-character test!"   print "Using cipher table:"   ; I build a set of correspondence lists here. 'x' is the letters from ; A-Z, in both upper and lowercase form. Note that REBOL can iterate ; directly over the alphabetic character sequence in the for loop. 'y' ; is the cipher form, 'x' rotated by 26 characters (remember, I have ; the lower and uppercase forms together). 'r' holds the final result, ; built as I iterate across the 'text' string. I search for the ; current character in the plaintext list ('x'), if I find it, I get ; the corresponding character from the ciphertext list ; ('y'). Otherwise, I pass the character through untransformed, then ; return the final string.   rot-13: func [ "Encrypt or decrypt rot-13 with tables." text [string!] "Text to en/decrypt." /local x y r i c ] [ x: copy "" for i #"a" #"z" 1 [append x rejoin [i uppercase i]] y: rejoin [copy skip x 26 copy/part x 26] r: copy ""   repeat i text [append r either c: find/case x i [y/(index? c)][i]] r ]   ; Note that I am setting the 'text' variable to the result of rot-13 ; so I can reuse it again on the next call. The rot-13 algorithm is ; reversible, so I can just run it again without modification to decrypt.   print [" Encrypted:" text: rot-13 text] print [" Decrypted:" text: rot-13 text]     print "Using parse:"   clamp: func [ "Contain a value within two enclosing values. Wraps if necessary." x v y ][ x: to-integer x v: to-integer v y: to-integer y case [v < x [y - v] v > y [v - y + x - 1] true v] ]   ; I'm using REBOL's 'parse' word here. I set up character sets for ; upper and lower-case letters, then let parse walk across the ; text. It looks for matches to upper-case letters, then lower-case, ; then skips to the next one if it can't find either. If a matching ; character is found, it's mathematically incremented by 13 and ; clamped to the appropriate character range. parse changes the ; character in place in the string, hence this is a destructive ; operation.   rot-13: func [ "Encrypt or decrypt rot-13 with parse." text [string!] "Text to en/decrypt. Note: Destructive!" ] [ u: charset [#"A" - #"Z"] l: charset [#"a" - #"z"]   parse text [some [ i: ; Current position. u (i/1: to-char clamp #"A" i/1 + 13 #"Z") | ; Upper case. l (i/1: to-char clamp #"a" i/1 + 13 #"z") | ; Lower case. skip]] ; Ignore others. text ]   ; As you see, I don't need to re-assign 'text' anymore.   print [" Encrypted:" rot-13 text] print [" Decrypted:" rot-13 text]
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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Quackery
Quackery
[ $ "" swap 1000 /mod $ "M" rot of rot swap join swap dup 900 < not if [ 900 - dip [ $ "CM" join ] ] dup 500 < not if [ 500 - dip [ $ "D" join ] ] dup 400 < not if [ 400 - dip [ $ "CD" join ] ] 100 /mod $ "C" rot of rot swap join swap dup 90 < not if [ 90 - dip [ $ "XC" join ] ] dup 50 < not if [ 50 - dip [ $ "L" join ] ] dup 40 < not if [ 40 - dip [ $ "XL" join ] ] 10 /mod $ "X" rot of rot swap join swap dup 9 < not if [ 9 - dip [ $ "IX" join ] ] dup 5 < not if [ 5 - dip [ $ "V" join ] ] dup 4 < not if [ 4 - dip [ $ "IV" join ] ] $ "I" swap of join ] is ->roman ( n --> $ )   1990 dup echo say " = " ->roman echo$ cr 2008 dup echo say " = " ->roman echo$ cr 1666 dup echo say " = " ->roman echo$ cr
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#Swift
Swift
extension Int { init(romanNumerals: String) { let values = [ ( "M", 1000), ("CM", 900), ( "D", 500), ("CD", 400), ( "C", 100), ("XC", 90), ( "L", 50), ("XL", 40), ( "X", 10), ("IX", 9), ( "V", 5), ("IV", 4), ( "I", 1), ]   self = 0 var raw = romanNumerals for (digit, value) in values { while raw.hasPrefix(digit) { self += value raw.removeFirst(digit.count) } } } }  
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D
D
import std.stdio, std.array;   void main() { writeln("ha".replicate(5)); }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#JavaScript
JavaScript
//returns array with three values var arrBind = function () { return [1, 2, 3]; //return array of three items to assign };   //returns object with three named values var objBind = function () { return {foo: "abc", bar: "123", baz: "zzz"}; };   //keep all three values var [a, b, c] = arrBind();//assigns a => 1, b => 2, c => 3 //skip a value var [a, , c] = arrBind();//assigns a => 1, c => 3 //keep final values together as array var [a, ...rest] = arrBind();//assigns a => 1, rest => [2, 3]     //same return name var {foo, bar, baz} = objBind();//assigns foo => "abc", bar => "123", baz => "zzz" //different return name (ignoring baz) var {baz: foo, buz: bar} = objBind();//assigns baz => "abc", buz => "123" //keep rest of values together as object var {foo, ...rest} = objBind();//assigns foo => "abc, rest => {bar: "123", baz: "zzz"}
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#C.23
C#
int[] nums = { 1, 1, 2, 3, 4, 4 }; List<int> unique = new List<int>(); foreach (int n in nums) if (!unique.Contains(n)) unique.Add(n);
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#Draco
Draco
proc nonrec find([*] int A; word top; int n) bool: word i; bool found; i := 0; found := false; while i < top and not found do found := A[i] = n; i := i + 1 od; found corp   proc nonrec gen_next([*] int A; word n) int: int add, sub; add := A[n-1] + n; sub := A[n-1] - n; A[n] := if sub > 0 and not find(A, n, sub) then sub else add fi; A[n] corp   proc nonrec main() void: [30] int A; word i;   A[0] := 0; write("First 15 items: 0"); for i from 1 upto 14 do write(gen_next(A, i):3) od; writeln();   while not find(A, i, gen_next(A, i)) do i := i + 1 od; writeln("First repeated item: A(", i:2, ") = ", A[i]:2) corp
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 first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#Forth
Forth
: array ( n -- ) ( i -- addr) create cells allot does> swap cells + ;   100 array sequence   : sequence. ( n -- ) cr 0 ?do i sequence @ . loop ;   : ?unused ( n -- t | n ) 100 0 ?do dup i sequence @ = if unloop exit then loop drop true ;   : sequence-next ( n -- a[n] ) dup 0= if 0 0 sequence ! exit then ( case a[0]=0 ) dup dup 1- sequence @ swap - ( a[n]=a[n-1]-n ) dup dup 0> swap ?unused true = and if nip exit then drop dup 1- sequence @ swap + ; ( a[n]=a[n-1]+n )   : sequence-gen ( n -- ) 0 ?do i sequence-next i sequence ! loop ;   : sequence-repeated 100 0 ?do i 0 ?do i sequence @ j sequence @ = if cr ." first repeated : a[" i . ." ]=a[" j . ." ]=" i sequence @ . unloop unloop exit then loop loop ;   100 sequence-gen 15 sequence. sequence-repeated
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 will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#AutoIt
AutoIt
  Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]] ToReducedRowEchelonForm($ivMatrix)   Func ToReducedRowEchelonForm($matrix) Local $clonematrix, $i Local $lead = 0 Local $rowCount = UBound($matrix) - 1 Local $columnCount = UBound($matrix, 2) - 1 For $r = 0 To $rowCount If $columnCount = $lead Then ExitLoop $i = $r While $matrix[$i][$lead] = 0 $i += 1 If $rowCount = $i Then $i = $r $lead += 1 If $columnCount = $lead Then ExitLoop EndIf WEnd ; There´s no built in Function to swap Rows of a 2-Dimensional Array ; We need to clone our matrix to swap complete lines $clonematrix = $matrix ; Swap Lines, no For $s = 0 To $columnCount $matrix[$r][$s] = $clonematrix[$i][$s] $matrix[$i][$s] = $clonematrix[$r][$s] Next Local $m = $matrix[$r][$lead] For $k = 0 To $columnCount $matrix[$r][$k] = $matrix[$r][$k] / $m Next For $i = 0 To $rowCount If $i <> $r Then Local $m = $matrix[$i][$lead] For $k = 0 To $columnCount $matrix[$i][$k] -= $m * $matrix[$r][$k] Next EndIf Next $lead += 1 Next ; Console Output For $i = 0 To $rowCount ConsoleWrite("[") For $k = 0 To $columnCount ConsoleWrite($matrix[$i][$k]) If $k <> $columnCount Then ConsoleWrite(",") Next ConsoleWrite("]" & @CRLF) Next ; End of Console Output Return $matrix EndFunc ;==>ToReducedRowEchelonForm  
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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#AutoHotkey
AutoHotkey
Sqrt(Number) ; square root Log(Number) ; logarithm (base 10) Ln(Number) ; natural logarithm (base e) Exp(N) ; e to the power N Abs(Number) ; absolute value Floor(Number) ; floor Ceil(Number) ; ceiling x**y ; x to the power 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 integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#AWK
AWK
BEGIN { print sqrt(2) # square root print log(2) # logarithm base e print exp(2) # exponential print 2 ^ -3.4 # power } # outputs 1.41421, 0.693147, 7.38906, 0.0947323
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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#Elixir
Elixir
defmodule RC do def remove_lines(filename, start, number) do File.open!(filename, [:read], fn file -> remove_lines(file, start, number, IO.read(file, :line)) end) end   defp remove_lines(_file, 0, 0, :eof), do: :ok defp remove_lines(_file, _, _, :eof) do IO.puts(:stderr, "Warning: End of file encountered before all lines removed") end defp remove_lines(file, 0, 0, line) do IO.write line remove_lines(file, 0, 0, IO.read(file, :line)) end defp remove_lines(file, 0, number, _line) do remove_lines(file, 0, number-1, IO.read(file, :line)) end defp remove_lines(file, start, number, line) do IO.write line remove_lines(file, start-1, number, IO.read(file, :line)) end end   [filename, start, number] = System.argv IO.puts "before:" IO.puts File.read!(filename) IO.puts "after:" RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#Erlang
Erlang
  -module( remove_lines ).   -export( [from_file/3, task/0] ).   from_file( Name, Start, How_many ) -> {Name, {ok, Binary}} = {Name, file:read_file( Name )}, Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ), {Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ), ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ), io:fwrite( "~s~n", [Message] ).   task() -> file:copy( "priv/foobar.txt", "foobar.txt" ), from_file( "foobar.txt", 1, 2 ).       compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T ); compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).   keep_lines( Start, _How_many, Lines, Available ) when Start > Available -> {"Start > avaliable. Nothing removed.", Lines}; keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available -> Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ), {Keeps, _Removes} = lists:split( Start, Lines ), {Message, Keeps}; keep_lines( Start, How_many, Lines, _Available ) -> {Keeps, Removes} = lists:split( Start, Lines ), {"ok", Keeps ++ lists:nthtail( How_many, Removes )}.  
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#Brainf.2A.2A.2A
Brainf***
> Keep cell 0 at 0 as a sentinel value ,[>,] Read into successive cells until EOF <[<] Go all the way back to the beginning >[.>] Print successive cells while nonzero
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 check File IO); this is for those cases where having the entire file is actually what is wanted.
#Brat
Brat
include :file   file.read file_name
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Go
Go
package main   import ( "fmt" "strings" )   func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 }   const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1`   func main() { for _, s := range strings.Fields(m) { if n := rep(s); n > 0 { fmt.Printf("%q  %d rep-string %q\n", s, n, s[:n]) } else { fmt.Printf("%q not a rep-string\n", 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
#HicEst
HicEst
CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" / REAL, PARAMETER :: Regex=128, Count=256   characters_a_m = INDEX(string, "[a-m]", Regex+Count) ! counts 16   vocals_changed = EDIT(Text=string, Option=Regex, Right="[aeiou]", RePLaceby='**', DO=LEN(string) ) ! changes 11 WRITE(ClipBoard) string ! Th** q****ck br**wn f**x j**mps **v**r th** l**zy d**g
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
#Icon_and_Unicon
Icon and Unicon
procedure main()   s := "A simple string" p := "string$" # regular expression   s ? write(image(s),if ReFind(p) then " matches " else " doesn't match ",image(p))   s[j := ReFind(p,s):ReMatch(p,s,j)] := "replacement" write(image(s)) end   link regexp # link to IPL regexp
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BBC_BASIC
BBC BASIC
PRINT FNreverse("The five boxing wizards jump quickly") END   DEF FNreverse(A$) LOCAL B$, C% FOR C% = LEN(A$) TO 1 STEP -1 B$ += MID$(A$,C%,1) NEXT = B$
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Oforth
Oforth
: hello "Hello, World!" println ; 10 #hello times
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Ol
Ol
  ; sample function (define (function) (display "+"))   ; simple case for 80 times (for-each (lambda (unused) (function)) (iota 80)) (print) ; print newline ; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   ; detailed case for 80 times (let loop ((fnc function) (n 80)) (unless (zero? n) (begin (fnc) (loop fnc (- n 1))))) (print) ; print newline ; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#Lasso
Lasso
// move file local(f = file('input.txt')) #f->moveTo('output.txt') #f->close   // move directory, just like a file local(d = dir('docs')) #d->moveTo('mydocs')   // move file in root file system (requires permissions at user OS level) local(f = file('//input.txt')) #f->moveTo('//output.txt') #f->close   // move directory in root file system (requires permissions at user OS level) local(d = file('//docs')) #d->moveTo('//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 systems, only the user root would have sufficient permissions in the filesystem root.)
#LFE
LFE
  (file:rename "input.txt" "output.txt") (file:rename "docs" "mydocs") (file:rename "/input.txt" "/output.txt") (file:rename "/docs" "/mydocs")  
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#Julia
Julia
revstring (str) = join(reverse(split(str, " ")), " ")
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#Kotlin
Kotlin
fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")   fun main() { val s = "Hey you, Bub!" println(reversedWords(s)) println() val sl = listOf( " ---------- 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 ----------------------- ", ) sl.forEach { println(reversedWords(it)) } }
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Retro
Retro
{{  : rotate ( cb-c ) tuck - 13 + 26 mod + ;  : rotate? ( c-c ) dup 'a 'z within [ 'a rotate ] ifTrue dup 'A 'Z within [ 'A rotate ] ifTrue ; ---reveal---  : rot13 ( s-s ) dup [ [ @ rotate? ] sip ! ] ^types'STRING each@ ; }}   "abcdef123GHIJKL" rot13 dup puts cr rot13 puts "abjurer NOWHERE" rot13 puts
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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#R
R
as.roman(1666) # MDCLXVI
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#Tailspin
Tailspin
  def digits: [(M:1000"1"), (CM:900"1"), (D:500"1"), (CD:400"1"), (C:100"1"), (XC:90"1"), (L:50"1"), (XL:40"1"), (X:10"1"), (IX:9"1"), (V:5"1"), (IV:4"1"), (I:1"1")]; composer decodeRoman @: 1; [ <digit>* ] -> \(@: 0; $... -> @: $@ + $; $@ !\) rule digit: <value>* (@: $@ + 1;) rule value: <='$digits($@)::key;'> -> $digits($@)::value end decodeRoman   'MCMXC' -> decodeRoman -> !OUT::write ' ' -> !OUT::write 'MMVIII' -> decodeRoman -> !OUT::write ' ' -> !OUT::write 'MDCLXVI' -> decodeRoman -> !OUT::write  
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#DCL
DCL
$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" ) $ write sys$output f$fao( "!12*d" )
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Delphi
Delphi
  function RepeatString(const s: string; count: cardinal): string; var i: Integer; begin for i := 1 to count do Result := Result + s; end;   Writeln(RepeatString('ha',5));