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.)
|
#Standard_ML
|
Standard ML
|
OS.FileSys.rename {old = "input.txt", new = "output.txt"};
OS.FileSys.rename {old = "docs", new = "mydocs"};
OS.FileSys.rename {old = "/input.txt", new = "/output.txt"};
OS.FileSys.rename {old = "/docs", new = "/mydocs"};
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Ring
|
Ring
|
aList = str2list("
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
")
aList = str2list(cStr)
for x in aList
x2 = substr(x," ",nl) alist2 = str2list(x2) aList2 = reverse(aList2)
for y in aList2 see y + " " next see nl
next
|
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
|
#Ruby
|
Ruby
|
puts <<EOS
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')}
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#Ursala
|
Ursala
|
#import std
#executable (<'parameterized','default-to-stdin'>,<>)
rot = ~command.files; * contents:= ~contents; * * -:~& -- ^p(~&,rep13~&zyC)~~ ~=`A-~ letters
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#True_BASIC
|
True BASIC
|
OPTION BASE 0
DIM arabic(12), roman$(12)
FOR i = 0 TO 12
READ arabic(i), roman$(i)
NEXT i
DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
FUNCTION toRoman$(value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ & roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
LET toRoman$ = result$
END FUNCTION
!Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)
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
|
#Julia
|
Julia
|
@show "ha" ^ 5
# The ^ operator is really just call to the `repeat` function
@show repeat("ha", 5)
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#K
|
K
|
,/5#,"ha"
"hahahahaha"
5#"*"
"*****"
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func
begin
sum := x + y;
diff := x - y;
end func;
const proc: main is func
local
var integer: sum is 0;
var integer: diff is 0;
begin
sumAndDiff(5, 3, sum, diff);
writeln("Sum: " <& sum);
writeln("Diff: " <& diff);
end func;
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#SenseTalk
|
SenseTalk
|
set [quotient,remainder] to quotientAndRemainder(13,4)
put !"The quotient of 13 ÷ 4 is: [[quotient]] with remainder: [[remainder]]"
to handle quotientAndRemainder of num, divisor
return [num div divisor, num rem divisor]
end quotientAndRemainder
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#GW-BASIC
|
GW-BASIC
|
10 ' Remove Duplicates
20 OPTION BASE 1
30 LET MAXI% = 7
40 DIM D(7), R(7): ' data, result
50 ' Set the data.
60 FOR I% = 1 TO 7
70 READ D(I%)
80 NEXT I%
90 ' Remove duplicates.
100 LET R(1) = D(1)
110 LET LRI% = 1: ' last index of result
120 LET P% = 1: ' position
130 WHILE P% < MAXI%
140 LET P% = P% + 1
150 LET ISNEW = 1: ' is a new number?
160 LET RI% = 1: ' current index of result
170 WHILE (RI% <= LRI%) AND ISNEW
180 IF D(P%) = R(RI%) THEN LET ISNEW = 0
190 LET RI% = RI% + 1
200 WEND
210 IF ISNEW THEN LET LRI% = LRI% + 1: LET R(LRI%) = D(P%)
220 WEND
230 FOR RI% = 1 TO LRI%
240 PRINT R(RI%)
250 NEXT RI%
260 END
1000 DATA 1, 2, 2, 3, 4, 5, 5
|
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.
|
#uBasic.2F4tH
|
uBasic/4tH
|
a = 0 ' the first one is free ;-)
Print "First 15 numbers:"
For i = 1 Step 1 ' start loop
If i<16 Then Print a, ' print first 15 numbers
b = Iif ((a-i<1) + (Func(_Peek(Max(0, a-i)))), a+i, a-i)
If Func(_Peek(b)) Then Print "\nFirst repetition: ";b : Break
Proc _Set(Set(a, b)) ' set bit in bitmap
Next
End ' terminate program
' bitmap functions
_Set Param(1) : Let @(a@/32) = Func(_Poke(a@/32, a@%32)) : Return
_Poke Param(2) : Return (Or(@(a@), Shl(1, b@)))
_Peek Param(1) : Return (And(@(a@/32), Shl(1, a@%32))>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.
|
#VBScript
|
VBScript
|
' Recaman's sequence - vbscript - 04/08/2015
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman's sequence for the first " & nx & " numbers:"
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0 'a(0)=0
b.Add 0,1 'b(0)=1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an 'a(n)=an
if not b.Exists(an) then b.Add an,1 'b(an)=1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1 'd(an)=1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1 'd(an)=1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next 'n
recaman=list
end function 'recaman
|
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
|
#Nim
|
Nim
|
import rationals, strutils
type Fraction = Rational[int]
const Zero: Fraction = 0 // 1
type Matrix[M, N: static Positive] = array[M, array[N, Fraction]]
func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] =
## Convert a matrix of integers to a matrix of integer fractions.
for i in 0..<M:
for j in 0..<N:
result[i][j] = a[i][j] // 1
func transformToRref(mat: var Matrix) =
## Transform the given matrix to reduced row echelon form.
var lead = 0
for r in 0..<mat.M:
if lead >= mat.N: return
var i = r
while mat[i][lead] == Zero:
inc i
if i == mat.M:
i = r
inc lead
if lead == mat.N: return
swap mat[i], mat[r]
if (let d = mat[r][lead]; d) != Zero:
for item in mat[r].mitems:
item /= d
for i in 0..<mat.M:
if i != r:
let m = mat[i][lead]
for c in 0..<mat.N:
mat[i][c] -= mat[r][c] * m
inc lead
proc `$`(mat: Matrix): string =
## Display a matrix.
for row in mat:
var line = ""
for val in row:
line.addSep(" ", 0)
line.add val.toFloat.formatFloat(ffDecimal, 2).align(7)
echo line
#———————————————————————————————————————————————————————————————————————————————————————————————————
template runTest(mat: Matrix) =
## Run a test using matrix "mat".
echo "Original matrix:"
echo mat
echo "Reduced row echelon form:"
mat.transformToRref()
echo mat
echo ""
var m1 = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]].toMatrix()
var m2 = [[2, 0, -1, 0, 0],
[1, 0, 0, -1, 0],
[3, 0, 0, -2, -1],
[0, 1, 0, 0, -2],
[0, 1, -1, 0, 0]].toMatrix()
var m3 = [[1, 2, 3, 4, 3, 1],
[2, 4, 6, 2, 6, 2],
[3, 6, 18, 9, 9, -6],
[4, 8, 12, 10, 12, 4],
[5, 10, 24, 11, 15, -4]].toMatrix()
var m4 = [[0, 1],
[1, 2],
[0, 5]].toMatrix()
runTest(m1)
runTest(m2)
runTest(m3)
runTest(m4)
|
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
|
#Julia
|
Julia
|
e
π, pi
sqrt(x)
log(x)
exp(x)
abs(x)
floor(x)
ceil(x)
x^y
|
http://rosettacode.org/wiki/Real_constants_and_functions
|
Real constants and functions
|
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest 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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun main(args: Array<String>) {
println(Math.E) // e
println(Math.PI) // pi
println(Math.sqrt(2.0)) // square root
println(Math.log(Math.E)) // log to base e
println(Math.log10(10.0)) // log to base 10
println(Math.exp(1.0)) // exponential
println(Math.abs(-1)) // absolute value
println(Math.floor(-2.5)) // floor
println(Math.ceil(-2.5)) // ceiling
println(Math.pow(2.5, 3.5)) // 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.
|
#Scala
|
Scala
|
object RemoveLinesFromAFile extends App {
args match {
case Array(filename, start, num) =>
import java.nio.file.{Files,Paths}
val lines = scala.io.Source.fromFile(filename).getLines
val keep = start.toInt - 1
val top = lines.take(keep).toList
val drop = lines.take(num.toInt).toList
Files.write(Paths.get(filename), scala.collection.JavaConversions.asJavaIterable(top ++ lines))
if (top.size < keep || drop.size < num.toInt)
println(s"Too few lines: removed only ${drop.size} of $num lines starting at $start")
case _ =>
println("Usage: RemoveLinesFromAFile <filename> <startLine> <numLines>")
}
}
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module checkit {
\\ prepare a file
\\ Save.Doc and Append.Doc to file, Load.Doc and Merge.Doc from file
document a$
a$={First Line
Second line
Third Line
Ελληνικά Greek Letters
}
Save.Doc a$, "checkthis.txt", 2 ' 2 for UTF-8
Buffer1=Buffer("checkthis.txt")
Print Len(Buffer1)=Filelen("checkthis.txt")
b$=String$(Eval$(Buffer1, 0) as UTF8Dec)
Report b$
openfile$=FILE$("text file","txt")
Merge.doc a$, openfile$
Edit.Doc a$
}
checkit
|
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.
|
#M4
|
M4
|
define(`foo',include(`file.txt'))
defn(`foo')
defn(`foo')
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#Tcl
|
Tcl
|
proc repstring {text} {
set len [string length $text]
for {set i [expr {$len/2}]} {$i > 0} {incr i -1} {
set sub [string range $text 0 [expr {$i-1}]]
set eq [string repeat $sub [expr {int(ceil($len/double($i)))}]]
if {[string equal -length $len $text $eq]} {
return $sub
}
}
error "no repetition"
}
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Ring
|
Ring
|
# Project : Regular expressions
text = "I am a text"
if right(text,4) = "text"
see "'" + text +"' ends with 'text'" + nl
ok
i = substr(text,"am")
text = left(text,i - 1) + "was" + substr(text,i + 2)
see "replace 'am' with 'was' = " + text + nl
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#DWScript
|
DWScript
|
let str = "asdf"
func String.Reverse() {
var cs = []
let len = this.Length()
for n in 1..len {
cs.Add(this[len - n])
}
String(values: cs)
}
str.Reverse()
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Stata
|
Stata
|
!ren input.txt output.txt
!ren docs mydocs
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Tcl
|
Tcl
|
file rename inputs.txt output.txt
file rename docs mydocs
file rename [file nativename /inputs.txt] [file nativename /output.txt]
file rename [file nativename /docs] [file nativename /mydocs]
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Toka
|
Toka
|
needs shell
" input.txt" " output.txt" rename
" /input.txt" " /output.txt" rename
" docs" " mydocs" rename
" /docs" " /mydocs" rename
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Run_BASIC
|
Run BASIC
|
for i = 1 to 10
read string$
j = 1
r$ = ""
while word$(string$,j) <> ""
r$ = word$(string$,j) + " " + r$
j = j + 1
WEND
print r$
next
end
data "---------- Ice and Fire ------------"
data ""
data "fire, in end will world the say Some"
data "ice. in say Some"
data "desire of tasted I've what From"
data "fire. favor who those with hold I"
data ""
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"
|
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
|
#Rust
|
Rust
|
const TEXT: &'static str =
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
fn main() {
println!("{}",
TEXT.lines() // Returns iterator over lines
.map(|line| // Applies closure to each item in iterator (for each line)
line.split_whitespace() // Returns iterator of words
.rev() // Reverses iterator of words
.collect::<Vec<_>>() // Collects words into Vec<&str>
.join(" ")) // Convert vector of words back into line
.collect::<Vec<_>>() // Collect lines into Vec<String>
.join("\n")); // Concatenate lines into String
}
|
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
|
#Vala
|
Vala
|
string rot13(string s) {
const string lcalph = "abcdefghijklmnopqrstuvwxyz";
const string ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string result = "";
int pos;
unichar c;
for (int i = 0; s.get_next_char (ref i, out c);) {
if ((pos = lcalph.index_of_char(c)) != -1)
result += lcalph[(pos + 13) % 26].to_string();
else if ((pos = ucalph.index_of_char(c)) != -1)
result += ucalph[(pos + 13) % 26].to_string();
else
result += c.to_string();
}
return result;
}
void main() {
print(rot13("The Quick Brown Fox Jumped Over the Lazy Dog!"));
}
|
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
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
LOOP arab_number="1990'2008'1666"
roman_number = ENCODE (arab_number,ROMAN)
PRINT "Arabic number ",arab_number, " equals ", roman_number
ENDLOOP
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Kotlin
|
Kotlin
|
fun main(args: Array<String>) {
println("ha".repeat(5))
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Sidef
|
Sidef
|
func foo(a,b) {
return (a+b, a*b);
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Smalltalk
|
Smalltalk
|
foo multipleValuesInto:[:a :b |
Transcript show:a; cr.
Transcript show:b; cr.
]
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Haskell
|
Haskell
|
print $ unique [4, 5, 4, 2, 3, 3, 4]
[4,5,2,3]
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main(ByVal args As String())
Dim a As List(Of Integer) = New List(Of Integer)() From { 0 },
used As HashSet(Of Integer) = New HashSet(Of Integer)() From { 0 },
used1000 As HashSet(Of Integer) = used.ToHashSet(),
foundDup As Boolean = False
For n As Integer = 1 to Integer.MaxValue
Dim nv As Integer = a(n - 1) - n
If nv < 1 OrElse used.Contains(nv) Then nv += 2 * n
Dim alreadyUsed As Boolean = used.Contains(nv) : a.Add(nv)
If Not alreadyUsed Then used.Add(nv) : If nv > 0 AndAlso nv <= 1000 Then used1000.Add(nv)
If Not foundDup Then
If a.Count = 15 Then _
Console.WriteLine("The first 15 terms of the Recamán sequence are: ({0})", String.Join(", ", a))
If alreadyUsed Then _
Console.WriteLine("The first duplicated term is a({0}) = {1}", n, nv) : foundDup = True
End If
If used1000.Count = 1001 Then _
Console.WriteLine("Terms up to a({0}) are needed to generate 0 to 1000", n) : Exit For
Next
End Sub
End Module
|
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
|
#Objeck
|
Objeck
|
class RowEchelon {
function : Main(args : String[]) ~ Nil {
matrix := [
[1, 2, -1, -4 ]
[2, 3, -1, -11 ]
[-2, 0, -3, 22]
];
matrix := Rref(matrix);
sizes := matrix->Size();
for(i := 0; i < sizes[0]; i += 1;) {
for(j := 0; j < sizes[1]; j += 1;) {
IO.Console->Print(matrix[i,j])->Print(",");
};
IO.Console->PrintLine();
};
}
function : native : Rref(matrix : Int[,]) ~ Int[,] {
lead := 0;
sizes := matrix->Size();
rowCount := sizes[0];
columnCount := sizes[1];
for(r := 0; r < rowCount; r+=1;) {
if (columnCount <= lead) {
break;
};
i := r;
while(matrix[i, lead] = 0) {
i+=1;
if (i = rowCount) {
i := r;
lead += 1;
if (columnCount = lead) {
lead-=1;
break;
};
};
};
for (j := 0; j < columnCount; j+=1;) {
temp := matrix[r, j];
matrix[r, j] := matrix[i, j];
matrix[i, j] := temp;
};
div := matrix[r, lead];
for(j := 0; j < columnCount; j+=1;) {
matrix[r, j] /= div;
};
for(j := 0; j < rowCount; j+=1;) {
if (j <> r) {
sub := matrix[j, lead];
for (k := 0; k < columnCount; k+=1;) {
matrix[j, k] -= sub * matrix[r, k];
};
};
};
lead+=1;
};
return matrix;
}
}
|
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
|
#Lambdatalk
|
Lambdatalk
|
{E} -> 2.718281828459045
{PI} -> 3.141592653589793
{sqrt 2} -> 1.4142135623730951
{log {E}} -> 1
{exp 1} -> 2.718281828459045
{abs -1} -> 1
{floor -2.5} -> -3
{ceil -2.5} -> -2
{pow 2.5 3.5} -> 24.705294220065465
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: removeLines (in string: fileName, in integer: start, in integer: count) is func
local
var file: inFile is STD_NULL;
var file: outFile is STD_NULL;
var integer: lineNumber is 1;
var string: line is "";
begin
inFile := open(fileName, "r");
outFile := open(fileName & ".tmp", "w");
while hasNext(inFile) do
line := getln(inFile);
if lineNumber < start or lineNumber >= start + count then
writeln(outFile, line);
end if;
incr(lineNumber);
end while;
close(inFile);
close(outFile);
removeFile(fileName);
moveFile(fileName & ".tmp", fileName);
end func;
const proc: main is func
begin
if length(argv(PROGRAM)) = 3 then
removeLines(argv(PROGRAM)[1], integer parse (argv(PROGRAM)[2]), integer parse (argv(PROGRAM)[3]));
end if;
end func;
|
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.
|
#Make
|
Make
|
contents := $(shell cat foo.txt)
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Maple
|
Maple
|
s1 := readbytes( "file1.txt", infinity, TEXT ):
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#UNIX_Shell
|
UNIX Shell
|
is_repeated() {
local str=$1 len rep part
for (( len = ${#str} / 2; len > 0; len-- )); do
part=${str:0:len}
rep=""
while (( ${#rep} < ${#str} )); do
rep+=$part
done
if [[ ${rep:0:${#str}} == $str ]] && (( $len < ${#str} )); then
echo "$part"
return 0
fi
done
return 1
}
while read test; do
if part=$( is_repeated "$test" ); then
echo "$test is composed of $part repeated"
else
echo "$test is not a repeated string"
fi
done <<END_TESTS
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
END_TESTS
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Ruby
|
Ruby
|
str = "I am a string"
p "Ends with 'string'" if str =~ /string$/
p "Does not start with 'You'" unless str =~ /^You/
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Run_BASIC
|
Run BASIC
|
string$ = "I am a string"
if right$(string$,6) = "string" then print "'";string$;"' ends with 'string'"
i = instr(string$,"am")
string$ = left$(string$,i - 1) + "was" + mid$(string$,i + 2)
print "replace 'am' with 'was' = ";string$
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#Dyalect
|
Dyalect
|
let str = "asdf"
func String.Reverse() {
var cs = []
let len = this.Length()
for n in 1..len {
cs.Add(this[len - n])
}
String(values: cs)
}
str.Reverse()
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#TorqueScript
|
TorqueScript
|
fileCopy("Input.txt", "Output.txt");
fileDelete("Input.txt");
for(%File = FindFirstFile("Path/*.*"); %File !$= ""; %File = FindNextFile("Path/*.*"))
{
fileCopy(%File, "OtherPath/" @ %File);
fileDelete(%File);
}
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
- rename file
ERROR/STOP RENAME ("input.txt","output.txt")
- rename directory
ERROR/STOP RENAME ("docs","mydocs",-std-)
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#S-lang
|
S-lang
|
variable ln, in =
["---------- Ice and Fire ------------",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"Frost Robert -----------------------"];
foreach ln (in) {
ln = strtok(ln, " \t");
array_reverse(ln);
() = printf("%s\n", strjoin(ln, " "));
}
|
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
|
#Vedit_macro_language
|
Vedit macro language
|
Translate_Load("ROT13.TBL")
Translate_Block(0, File_Size)
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#TypeScript
|
TypeScript
|
// Roman numerals/Encode
const weightsSymbols: [number, string][] =
[[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'],
[50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
// 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
// with these symbols.
function toRoman(n: number): string {
var roman = ""; // Result
for (i = 0; i <= 12 && n > 0; i++) {
var w = weightsSymbols[i][0];
while (n >= w) {
roman += weightsSymbols[i][1];
n -= w;
}
}
return roman;
}
console.log(toRoman(1990)); // MCMXC
console.log(toRoman(2022)); // MMXXII
console.log(toRoman(3888)); // MMMDCCCLXXXVIII
|
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
|
#LabVIEW
|
LabVIEW
|
{S.map {lambda {_} ha} {S.serie 1 10}}
-> ha ha ha ha ha ha ha ha ha ha
or
{S.replace \s
by
in {S.map {lambda {_} ha}
{S.serie 1 10}}}
-> hahahahahahahahahaha
or
{def repeat
{lambda {:w :n}
{if {< :n 0}
then
else :w{repeat :w {- :n 1}}}}}
-> repeat
{repeat ha 10}
-> hahahahahahahahahahaha
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Standard_ML
|
Standard ML
|
fun addsub (x, y) =
(x + y, x - y)
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#HicEst
|
HicEst
|
REAL :: nums(12)
CHARACTER :: workspace*100
nums = (1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2)
WRITE(Text=workspace) nums ! convert to string
EDIT(Text=workspace, SortDelDbls=workspace) ! do the job for a string
READ(Text=workspace, ItemS=individuals) nums ! convert to numeric
WRITE(ClipBoard) individuals, "individuals: ", nums ! 6 individuals: 0 1 2 3 8 9 0 0 0 0 0 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.
|
#Wren
|
Wren
|
var a = [0]
var used = { 0: true }
var used1000 = { 0: true }
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.count < 1001) {
var next = a[n-1] - n
if (next < 1 || used[next]) next = next + 2*n
var alreadyUsed = used[next]
a.add(next)
if (!alreadyUsed) {
used[next] = true
if (next >= 0 && next <= 1000) used1000[next] = true
}
if (n == 14) System.print("The first 15 terms of the Recaman's sequence are:\n%(a)")
if (!foundDup && alreadyUsed) {
System.print("The first duplicated term is a[%(n)] = %(next)")
foundDup = true
}
if (used1000.count == 1001) {
System.print("Terms up to a[%(n)] are needed to generate 0 to 1000")
}
n = n + 1
}
|
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
|
#OCaml
|
OCaml
|
let swap_rows m i j =
let tmp = m.(i) in
m.(i) <- m.(j);
m.(j) <- tmp;
;;
let rref m =
try
let lead = ref 0
and rows = Array.length m
and cols = Array.length m.(0) in
for r = 0 to pred rows do
if cols <= !lead then
raise Exit;
let i = ref r in
while m.(!i).(!lead) = 0 do
incr i;
if rows = !i then begin
i := r;
incr lead;
if cols = !lead then
raise Exit;
end
done;
swap_rows m !i r;
let lv = m.(r).(!lead) in
m.(r) <- Array.map (fun v -> v / lv) m.(r);
for i = 0 to pred rows do
if i <> r then
let lv = m.(i).(!lead) in
m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i);
done;
incr lead;
done
with Exit -> ()
;;
let () =
let m =
[| [| 1; 2; -1; -4 |];
[| 2; 3; -1; -11 |];
[| -2; 0; -3; 22 |]; |]
in
rref m;
Array.iter (fun row ->
Array.iter (fun v ->
Printf.printf " %d" v
) row;
print_newline()
) 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
|
#Lasso
|
Lasso
|
//e
define e => 2.7182818284590452
//π
define pi => 3.141592653589793
e
pi
9.0->sqrt
1.64->log
1.64->log10
1.64->exp
1.64->abs
1.64->floor
1.64->ceil
1.64->pow(10.0)
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#SenseTalk
|
SenseTalk
|
removeLines "foobar.txt", 1, 2
to handle removeLines fileName, startingLine, linesToRemove
If there is no file fileName then
put !"No such file: [[the folder & fileName]]"
Return
End if
set endingLine to startingLine + linesToRemove - 1
If endingLine is more than number of lines in file fileName then
put !"Cannot delete lines past the end of the file ([[number of lines in file fileName]] lines)"
Return
End If
delete lines startingLine to endingLine of file fileName
end removeLines
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
Import["filename","String"]
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#VBScript
|
VBScript
|
Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
'testing the function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Rust
|
Rust
|
use regex::Regex;
fn main() {
let s = "I am a string";
if Regex::new("string$").unwrap().is_match(s) {
println!("Ends with string.");
}
println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
}
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
!print concat chars "Hello"
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#TXR
|
TXR
|
(rename-path "input.txt" "output.txt")
;; Windows (MinGW based port)
(rename-path "C:\\input.txt" "C:\\output.txt")
;; Unix; Windows (Cygwin port)
(rename-path "/input.txt" "/output.txt"))
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#UNIX_Shell
|
UNIX Shell
|
mv input.txt output.txt
mv /input.txt /output.txt
mv docs mydocs
mv /docs /mydocs
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Scala
|
Scala
|
object ReverseWords extends App {
"""| ---------- Ice and Fire ------------
|
| fire, in end will world the say Some
| ice. in say Some
| desire of tasted I've what From
| fire. favor who those with hold I
|
| ... elided paragraph last ...
|
| Frost Robert ----------------------- """
.stripMargin.lines.toList.map{_.split(" ")}.map{_.reverse}
.map(_.mkString(" "))
.foreach{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
|
#Visual_Basic
|
Visual Basic
|
Function ROT13(ByVal a As String) As String
Dim i As Long
Dim n As Integer, e As Integer
ROT13 = a
For i = 1 To Len(a)
n = Asc(Mid$(a, i, 1))
Select Case n
Case 65 To 90
e = 90
n = n + 13
Case 97 To 122
e = 122
n = n + 13
Case Else
e = 255
End Select
If n > e Then
n = n - 26
End If
Mid$(ROT13, i, 1) = Chr$(n)
Next i
End Function
|
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
|
#uBasic.2F4tH
|
uBasic/4tH
|
Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
' Initialize array
For i = 12 To 0 Step -1
@(i) = Pop()
Next
' Calculate and print numbers
Print 1999, : Proc _FNroman (1999)
Print 2014, : Proc _FNroman (2014)
Print 1666, : Proc _FNroman (1666)
Print 3888, : Proc _FNroman (3888)
End
_FNroman Param (1) ' ( n --)
Local (1) ' Define b@
' Try all numbers in array
For b@ = 12 To 0 Step -1
Do While a@ > @(b@) - 1 ' Several occurences of same number?
GoSub ((b@ + 1) * 10) ' Print roman digit
a@ = a@ - @(b@) ' Decrement number
Loop
Next
Print ' Terminate line
Return
' Print roman digits
10 Print "I"; : Return
20 Print "IV"; : Return
30 Print "V"; : Return
40 Print "IX"; : Return
50 Print "X"; : Return
60 Print "XL"; : Return
70 Print "L"; : Return
80 Print "XC"; : Return
90 Print "C"; : Return
100 Print "CD"; : Return
110 Print "D"; : Return
120 Print "CM"; : Return
130 Print "M"; : Return
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Lambdatalk
|
Lambdatalk
|
{S.map {lambda {_} ha} {S.serie 1 10}}
-> ha ha ha ha ha ha ha ha ha ha
or
{S.replace \s
by
in {S.map {lambda {_} ha}
{S.serie 1 10}}}
-> hahahahahahahahahaha
or
{def repeat
{lambda {:w :n}
{if {< :n 0}
then
else :w{repeat :w {- :n 1}}}}}
-> repeat
{repeat ha 10}
-> hahahahahahahahahahaha
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Swift
|
Swift
|
func addsub(x: Int, y: Int) -> (Int, Int) {
return (x + y, x - y)
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Tcl
|
Tcl
|
proc addsub {x y} {
list [expr {$x+$y}] [expr {$x-$y}]
}
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(args)
every write(!noDups(args))
end
procedure noDups(L)
every put(newL := [], notDup(set(),!L))
return newL
end
procedure notDup(cache, a)
if not member(cache, a) then {
insert(cache, a)
return a
}
end
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#zkl
|
zkl
|
fcn recamanW{ // -->iterator -->(n,a,True if a is a dup)
Walker.tweak(fcn(rn,rp,d){
n,p,a := rn.value, rp.value, p - n;
if(a<=0 or d.find(a)) a+=2*n;
d.incV(a); rp.set(a);
return(rn.inc(),a,d[a]>1);
}.fp(Ref(0),Ref(0),Dictionary()) )
}
|
http://rosettacode.org/wiki/Reduced_row_echelon_form
|
Reduced row echelon form
|
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this 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
|
#Octave
|
Octave
|
A = [ 1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22];
refA = rref(A);
disp(refA);
|
http://rosettacode.org/wiki/Real_constants_and_functions
|
Real constants and functions
|
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest 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
|
#Liberty_BASIC
|
Liberty BASIC
|
print exp( 1) ' e not available
print 4 *atn( 1) ' pi not available
x =12.345: y =1.23
print sqr( x), x^0.5 ' square root- NB the unusual name
print log( x) ' natural logarithm base e
print log( x) /2.303 ' base 10 logarithm
print log( x) /log( y) ' arbitrary base logarithm
print exp( x) ' exponential
print abs( x) ' absolute value
print floor( x) ' floor
print ceiling( x) ' ceiling
print x^y ' power
end
function floor( x)
if x >0 then
floor =int( x)
else
if x <>int( x) then floor =int( x) -1 else floor =int( x)
end if
end function
function ceiling( x)
if x <0 then
ceiling =int( x)
else
ceiling =int( x) +1
end if
end function
|
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.
|
#Sidef
|
Sidef
|
func remove_lines(file, beg, len) {
var lines = file.open_r.lines;
lines.splice(beg, len).len == len || warn "Too few lines";
file.open_w.print(lines.join)
}
remove_lines(File(__FILE__), 2, 3);
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
fid = fopen('filename','r');
[str,count] = fread(fid, [1,inf], 'uint8=>char'); % s will be a character array, count has the number of bytes
fclose(fid);
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Mercury
|
Mercury
|
:- module read_entire_file.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module string.
main(!IO) :-
io.open_input("file.txt", OpenResult, !IO),
(
OpenResult = ok(File),
io.read_file_as_string(File, ReadResult, !IO),
(
ReadResult = ok(FileContents),
io.write_string(FileContents, !IO)
;
ReadResult = error(_, IO_Error),
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
)
;
OpenResult = error(IO_Error),
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
).
|
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
|
#Vlang
|
Vlang
|
fn rep(s string) int {
for x := s.len / 2; x > 0; x-- {
if s.starts_with(s[x..]) {
return x
}
}
return 0
}
const m = '
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1'
fn main() {
for s in m.fields() {
n := rep(s)
if n > 0 {
println("$s $n rep-string ${s[..n]}")
} else {
println("$s not a rep-string")
}
}
}
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Sather
|
Sather
|
class MAIN is
-- we need to implement the substitution
regex_subst(re:REGEXP, s, sb:STR):STR is
from, to:INT;
re.match(s, out from, out to);
if from = -1 then return s; end;
return s.head(from) + sb + s.tail(s.size - to);
end;
main is
s ::= "I am a string";
re ::= REGEXP::regexp("string$", true);
if re.match(s) then
#OUT + "'" + s + "'" + " ends with 'string'\n";
end;
if ~REGEXP::regexp("^You", false).match(s) then
#OUT + "'" + s + "'" + " does not begin with 'You'\n";
end;
#OUT + regex_subst(re, s, "integer") + "\n";
#OUT + regex_subst(REGEXP::regexp("am +a +st", true), s, "get the ") + "\n";
end;
end;
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Scala
|
Scala
|
val Bottles1 = "(\\d+) bottles of beer".r // syntactic sugar
val Bottles2 = """(\d+) bottles of beer""".r // using triple-quotes to preserve backslashes
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer") // standard
val Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups
|
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
|
#E
|
E
|
pragma.enable("accumulator")
def reverse(string) {
return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Vedit_macro_language
|
Vedit macro language
|
// In current directory
File_Rename("input.txt", "output.txt")
File_Rename("docs", "mydocs")
// In the root directory
File_Rename("/input.txt", "/output.txt")
File_Rename("/docs", "/mydocs")
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
'Current Directory
IO.Directory.Move("docs", "mydocs")
IO.File.Move("input.txt", "output.txt")
'Root
IO.Directory.Move("\docs", "\mydocs")
IO.File.Move("\input.txt", "\output.txt")
'Root, platform independent
IO.Directory.Move(IO.Path.DirectorySeparatorChar & "docs", _
IO.Path.DirectorySeparatorChar & "mydocs")
IO.File.Move(IO.Path.DirectorySeparatorChar & "input.txt", _
IO.Path.DirectorySeparatorChar & "output.txt")
|
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
|
#Scheme
|
Scheme
|
(for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
(string-split
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------"
#/[ \r]*\n[ \r]*/))
|
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
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Private Function rot13(ByVal str As String) As String
Dim newChars As Char(), i, j As Integer, original, replacement As String
original = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
replacement = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
newChars = str.ToCharArray()
For i = 0 To newChars.Length - 1
For j = 0 To 51
If newChars(i) = original(j) Then
newChars(i) = replacement(j)
Exit For
End If
Next
Next
Return New String(newChars)
End Function
End Module
|
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
|
#UNIX_Shell
|
UNIX Shell
|
roman() {
local values=( 1000 900 500 400 100 90 50 40 10 9 5 4 1 )
local roman=(
[1000]=M [900]=CM [500]=D [400]=CD
[100]=C [90]=XC [50]=L [40]=XL
[10]=X [9]=IX [5]=V [4]=IV
[1]=I
)
local nvmber=""
local num=$1
for value in ${values[@]}; do
while (( num >= value )); do
nvmber+=${roman[value]}
((num -= value))
done
done
echo $nvmber
}
for test in 1999 24 944 1666 2008; do
printf "%d = %s\n" $test $(roman $test)
done
|
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
|
#langur
|
langur
|
"ha" x 5
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Lasso
|
Lasso
|
'ha'*5 // hahahahaha
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#TXR
|
TXR
|
@(define func (x y z))
@ (bind w "discarded")
@ (bind (x y z) ("a" "b" "c"))
@(end)
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/sh
funct1() {
a=$1
b=`expr $a + 1`
echo $a $b
}
values=`funct1 5`
set $values
x=$1
y=$2
echo "x=$x"
echo "y=$y"
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#IDL
|
IDL
|
non_repeated_values = array[uniq(array, sort( array))]
|
http://rosettacode.org/wiki/Reduced_row_echelon_form
|
Reduced row echelon form
|
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this 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
|
#PARI.2FGP
|
PARI/GP
|
matrref(M)=
{
my(s=matsize(M),t=s[1]);
for(i=1,s[2],
if(M[t,i]==0, next);
M[t,] /= M[t,i];
for(j=1,t-1,
M[j,] -= M[j,i]*M[t,]
);
for(j=t+1,s[1],
M[j,] -= M[j,i]*M[t,]
);
if(t--<1,break)
);
M;
}
addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");
|
http://rosettacode.org/wiki/Real_constants_and_functions
|
Real constants and functions
|
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest 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
|
#Lingo
|
Lingo
|
the floatPrecision = 8
-- e (base of the natural logarithm)
put exp(1)
-- 2.71828183
-- pi
put PI
-- 3.14159265
-- square root
put sqrt(2.0)
-- 1.41421356
-- logarithm (any base allowed)
x = 100
put log(x) -- calculate log for base e
-- 4.60517019
put log(x)/log(10) -- calculate log for base 10
-- 2.00000000
-- exponential (ex)
put exp(3)
-- 20.08553692
-- absolute value (a.k.a. "magnitude")
put abs(-1)
-- 1
-- floor (largest integer less than or equal to this number--not the same as truncate or int)
n = 23.536
put bitOr(n, 0) -- calculates floor
-- 23
-- ceiling (smallest integer not less than this number--not the same as round up)
n = 23.536
-- calculates ceil
floor = bitOr(n, 0)
if (floor >= n) then put floor
else put floor+1
-- 24
-- power
put power(2, 8)
-- 256.00000000
|
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
|
#LiveCode
|
LiveCode
|
e: exp(1)
pi: pi
square root: sqrt(x)
logarithm: log(x)
exponential (ex): exp(x)
absolute value: abs(x)
floor: floor(x)
ceiling: ceil(x)
power: x^y
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#Snobol4
|
Snobol4
|
* Remove lines from a file
* Function to remove a chunk of lines from a file, will go backward, too, if numlines < 0
define("remlines(filename,startline,numlines)row,rowcount,lastline,swap")
:(remlines_end)
remlines
input(.inp1,1,filename) :f(freturn)
output(.tmp1,2,"/tmp/Removem") :f(freturn)
rowcount = 0
lastline = (ge(numlines,0) startline + numlines - 1, startline + numlines + 1)
ge(numlines,0) :s(remlines2)
swap = lastline
lastline = startline
startline = swap
remlines2
row = inp1 :f(remlines3)
rowcount = rowcount + 1
ge(rowcount,startline) le(rowcount,lastline) :s(remlines2)
tmp1 = row
:(remlines2)
remlines3
endfile(1)
endfile(2)
input(.rmv1,2,"/tmp/Removem") :f(freturn)
output(.fnout1,1,filename) :f(freturn)
remlines4
fnout1 = rmv1 :s(remlines4)
endfile(1)
endfile(2)
:(return)
remlines_end
testfile = "/tmp/foobar.txt"
* Populate test file with 5 rows, 1, 2, 3, 4, and 5
output(.testout,60,testfile) :f(failed)
i = 1
pop1
testout = i
i = lt(i,5) i + 1 :s(pop1)
endfile(60)
* Now remove lines 2, 3, and 4 from test file
remlines(testfile,2,3) :f(failed)
* Print revised file
input(.testprt,70,testfile) :f(failed)
print1
output = testprt :s(print1)
:(end)
failed
output = "Either the main file or the temporary file failed to open"
end
|
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.
|
#Stata
|
Stata
|
* drop lines 20 to 30
drop in 20/30
* keep lines 20 to 30, and remove everything else
keep in 20/30
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Microsoft_Small_Basic
|
Microsoft Small Basic
|
v=File.ReadContents(filename)
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Nanoquery
|
Nanoquery
|
import Nanoquery.IO
contents = new(File, "example.txt").readAll()
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var repString = Fn.new { |s|
var reps = []
if (s.count < 2) return reps
for (c in s) if (c != "0" && c != "1") Fiber.abort("Argument is not a binary string.")
var size = s.count
for (len in 1..(size/2).floor) {
var t = s[0...len]
var n = (size/len).floor
var r = size % len
var u = t * n + t[0...r]
if (u == s) reps.add(t)
}
return reps
}
var strings = [
"1001110011",
"1110111011",
"0010010010",
"1010101010",
"1111111111",
"0100101101",
"0100100",
"101",
"11",
"00",
"1"
]
System.print("The (longest) rep-strings are:\n")
for (s in strings) {
var reps = repString.call(s)
var t = (reps.count > 0) ? reps[-1] : "Not a rep-string"
Fmt.print("$10s -> $s", s, t)
}
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#SenseTalk
|
SenseTalk
|
set text to "This is a story about R2D2 and C3P0 who are best friends."
set pattern to <word start, letter, digit, letter, digit, word end>
put the sixth word of text matches pattern -- (note: the sixth word is "R2D2")
put every occurrence of pattern in text
replace the second occurrence of pattern in text with "Luke"
put text
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Shiny
|
Shiny
|
str: 'I am a string'
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#EchoLisp
|
EchoLisp
|
(define (string-reverse string)
(list->string (reverse (string->list string))))
(string-reverse "ghij")
→ jihg
(string-reverse "un roc lamina l animal cornu")
→ unroc lamina l animal cor nu
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Wren
|
Wren
|
import "/ioutil" for FileUtil
FileUtil.move("input.txt", "output.txt")
FileUtil.move("/input.txt", "/output.txt")
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Yabasic
|
Yabasic
|
if peek$("os") = "windows" then
slash$ = "\\" : com$ = "ren "
else
slash$ = "/" : com$ = "mv "
end if
system(com$ + "input.txt output.txt")
system(com$ + "docs mydocs")
system(com$ + slash$ + "input.txt " + slash$ + "output.txt")
system(com$ + slash$ + "docs " + slash$ + "mydocs")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.