task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Reduced_row_echelon_form
|
Reduced row echelon form
|
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this 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
|
#C.2B.2B
|
C++
|
#include <algorithm> // for std::swap
#include <cstddef>
#include <cassert>
// Matrix traits: This describes how a matrix is accessed. By
// externalizing this information into a traits class, the same code
// can be used both with native arrays and matrix classes. To use the
// default implementation of the traits class, a matrix type has to
// provide the following definitions as members:
//
// * typedef ... index_type;
// - The type used for indexing (e.g. size_t)
// * typedef ... value_type;
// - The element type of the matrix (e.g. double)
// * index_type min_row() const;
// - returns the minimal allowed row index
// * index_type max_row() const;
// - returns the maximal allowed row index
// * index_type min_column() const;
// - returns the minimal allowed column index
// * index_type max_column() const;
// - returns the maximal allowed column index
// * value_type& operator()(index_type i, index_type k)
// - returns a reference to the element i,k, where
// min_row() <= i <= max_row()
// min_column() <= k <= max_column()
// * value_type operator()(index_type i, index_type k) const
// - returns the value of element i,k
//
// Note that the functions are all inline and simple, so the compiler
// should completely optimize them away.
template<typename MatrixType> struct matrix_traits
{
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const& A)
{ return A.min_row(); }
static index_type max_row(MatrixType const& A)
{ return A.max_row(); }
static index_type min_column(MatrixType const& A)
{ return A.min_column(); }
static index_type max_column(MatrixType const& A)
{ return A.max_column(); }
static value_type& element(MatrixType& A, index_type i, index_type k)
{ return A(i,k); }
static value_type element(MatrixType const& A, index_type i, index_type k)
{ return A(i,k); }
};
// specialization of the matrix traits for built-in two-dimensional
// arrays
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]>
{
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns])
{ return 0; }
static index_type max_row(T const (&)[rows][columns])
{ return rows-1; }
static index_type min_column(T const (&)[rows][columns])
{ return 0; }
static index_type max_column(T const (&)[rows][columns])
{ return columns-1; }
static value_type& element(T (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
static value_type element(T const (&A)[rows][columns],
index_type i, index_type k)
{ return A[i][k]; }
};
// Swap rows i and k of a matrix A
// Note that due to the reference, both dimensions are preserved for
// built-in arrays
template<typename MatrixType>
void swap_rows(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
// check indices
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
// divide row i of matrix A by v
template<typename MatrixType>
void divide_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
// in matrix A, add v times row k to row i
template<typename MatrixType>
void add_multiple_row(MatrixType& A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
// convert A to reduced row echelon form
template<typename MatrixType>
void to_reduced_row_echelon_form(MatrixType& A)
{
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
{
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0)
{
++i;
if (i > mt.max_row(A))
{
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
{
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
// test code
#include <iostream>
int main()
{
double M[3][4] = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } };
to_reduced_row_echelon_form(M);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
std::cout << M[i][j] << '\t';
std::cout << "\n";
}
return EXIT_SUCCESS;
}
|
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
|
#C.23
|
C#
|
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine(Math.E); //E
Console.WriteLine(Math.PI); //PI
Console.WriteLine(Math.Sqrt(10)); //Square Root
Console.WriteLine(Math.Log(10)); // Logarithm
Console.WriteLine(Math.Log10(10)); // Base 10 Logarithm
Console.WriteLine(Math.Exp(10)); // Exponential
Console.WriteLine(Math.Abs(10)); //Absolute value
Console.WriteLine(Math.Floor(10.0)); //Floor
Console.WriteLine(Math.Ceiling(10.0)); //Ceiling
Console.WriteLine(Math.Pow(2, 5)); // Exponentiation
}
}
|
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.
|
#Go
|
Go
|
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
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.
|
#Crystal
|
Crystal
|
content = File.read("input.txt")
puts content
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#D
|
D
|
import std.file: read, readText;
void main() {
// To read a whole file into a dynamic array of unsigned bytes:
auto data = cast(ubyte[])read("unixdict.txt");
// To read a whole file into a validated UTF-8 string:
string txt = readText("unixdict.txt");
}
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#jq
|
jq
|
def is_rep_string:
# if self is a rep-string then return [n, prefix]
# where n is the number of full occurrences of prefix
def _check(prefix; n; sofar):
length as $length
| if length <= (sofar|length) then [n, prefix]
else (sofar+prefix) as $sofar
| if startswith($sofar) then _check(prefix; n+1; $sofar)
elif ($sofar|length) > $length and
startswith($sofar[0:$length]) then [n, prefix]
else [0, prefix]
end
end
;
[range (1; length/2 + 1) as $i
| .[0:$i] as $prefix
| _check($prefix; 1; $prefix)
| select( .[0] > 1 ) ]
;
|
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
|
#Julia
|
Julia
|
function repstring(r::AbstractString)
n = length(r)
replst = String[]
for m in 1:n÷2
s = r[1:chr2ind(r, m)]
if (s ^ cld(n, m))[1:chr2ind(r, n)] != r continue end
push!(replst, s)
end
return replst
end
tests = ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1",
"\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"]
for r in tests
replst = repstring(r)
if isempty(replst)
println("$r is not a rep-string.")
else
println("$r is a rep-string of ", join(replst, ", "), ".")
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun main(args: Array<String>) {
val s1 = "I am the original string"
val r1 = Regex("^.*string$")
if (s1.matches(r1)) println("`$s1` matches `$r1`")
val r2 = Regex("original")
val s3 = "replacement"
val s2 = s1.replace(r2, s3)
if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
}
|
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
|
#Brat
|
Brat
|
p "olleh".reverse #Prints "hello"
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#PureBasic
|
PureBasic
|
Prototype.i fun(x.i)
Procedure.i quark(z.i)
Debug "Quark "+Str(z) : ProcedureReturn z-1
EndProcedure
Procedure rep(q.fun,n.i)
Repeat : n=q(n) : Until n=0
EndProcedure
rep(@quark(),3)
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Python
|
Python
|
#!/usr/bin/python
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#MAXScript
|
MAXScript
|
-- Here
renameFile "input.txt" "output.txt"
-- Root
renameFile "/input.txt" "/output.txt"
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Mercury
|
Mercury
|
:- module rename_file.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module dir.
main(!IO) :-
rename_file("input.txt", "output.txt", !IO),
rename_file("docs", "mydocs", !IO),
rename_file("/input.txt", "/output.txt", !IO),
rename_file("/docs", "/mydocs", !IO).
:- pred rename_file(string::in, string::in, io::di, io::uo) is det.
rename_file(OldName, NewName, !IO) :-
io.rename_file(OldName, NewName, Result, !IO),
(
Result = ok
;
Result = error(Error),
print_io_error(Error, !IO)
).
:- pred print_io_error(io.error::in, io::di, io::uo) is det.
print_io_error(Error, !IO) :-
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.nl(Stderr, !IO),
io.set_exit_status(1, !IO).
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Logo
|
Logo
|
do.until [
make "line readlist
print reverse :line
] [word? :line]
bye
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Lua
|
Lua
|
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
local this = {}
for word in line:gmatch("%S+") do
table.insert(this, 1, word)
end
lines[#lines + 1] = table.concat(this, " ")
end
print(table.concat(lines, "\n"))
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#Rust
|
Rust
|
fn rot13(string: &str) -> String {
string.chars().map(|c| {
match c {
'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char,
'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char,
_ => c
}
}).collect()
}
fn main () {
assert_eq!(rot13("abc"), "nop");
}
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#REXX
|
REXX
|
roman: procedure
arg number
/* handle only 1 to 3999, else return ? */
if number >= 4000 | number <= 0 then return "?"
romans = " M CM D CD C XC L XL X IX V IV I"
arabic = "1000 900 500 400 100 90 50 40 10 9 5 4 1"
result = ""
do i = 1 to words(romans)
do while number >= word(arabic,i)
result = result || word(romans,i)
number = number - word(arabic,i)
end
end
return result
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#True_BASIC
|
True BASIC
|
FUNCTION romtodec(roman$)
LET num = 0
LET prenum = 0
FOR i = LEN(roman$) TO 1 STEP -1
LET x$ = (roman$)[i:i+1-1]
LET n = 0
IF x$ = "M" THEN LET n = 1000
IF x$ = "D" THEN LET n = 500
IF x$ = "C" THEN LET n = 100
IF x$ = "L" THEN LET n = 50
IF x$ = "X" THEN LET n = 10
IF x$ = "V" THEN LET n = 5
IF x$ = "I" THEN LET n = 1
IF n < prenum THEN LET num = num-n ELSE LET num = num+n
LET prenum = n
NEXT i
LET romtodec = num
END FUNCTION
!Testing
PRINT "MCMXCIX = "; romToDec("MCMXCIX") !1999
PRINT "MDCLXVI = "; romToDec("MDCLXVI") !1666
PRINT "XXV = "; romToDec("XXV") !25
PRINT "CMLIV = "; romToDec("CMLIV") !954
PRINT "MMXI = "; romToDec("MMXI") !2011
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
|
#Elena
|
Elena
|
import system'routines;
import extensions;
import extensions'text;
public program()
{
var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter())
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function [a,b,c]=foo(d)
a = 1-d;
b = 2+d;
c = a+b;
end;
[x,y,z] = foo(5)
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Maxima
|
Maxima
|
f(a, b) := [a * b, a + b]$
[u, v]: f(5, 6);
[30, 11]
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Common_Lisp
|
Common Lisp
|
(remove-duplicates '(1 3 2 9 1 2 3 8 8 1 0 2))
> (9 3 8 1 0 2)
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#JavaScript
|
JavaScript
|
(() => {
const main = () => {
console.log(
'First 15 Recaman:\n' +
recamanUpto(i => 15 === i)
);
console.log(
'\n\nFirst duplicated Recaman:\n' +
last(recamanUpto(
(_, set, rs) => set.size !== rs.length
))
);
const setK = new Set(enumFromTo(0, 1000));
console.log(
'\n\nNumber of Recaman terms needed to generate' +
'\nall integers from [0..1000]:\n' +
(recamanUpto(
(_, setR) => isSubSetOf(setK, setR)
).length - 1)
);
};
// RECAMAN --------------------------------------------
// recamanUpto :: (Int -> Set Int > [Int] -> Bool) -> [Int]
const recamanUpto = p => {
let
i = 1,
r = 0, // First term of series
rs = [r];
const seen = new Set(rs);
while (!p(i, seen, rs)) {
r = nextR(seen, i, r);
seen.add(r);
rs.push(r);
i++;
}
return rs;
}
// Next Recaman number.
// nextR :: Set Int -> Int -> Int
const nextR = (seen, i, n) => {
const back = n - i;
return (0 > back || seen.has(back)) ? (
n + i
) : back;
};
// GENERIC --------------------------------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
// isSubsetOf :: Ord a => Set a -> Set a -> Bool
const isSubSetOf = (a, b) => {
for (let x of a) {
if (!b.has(x)) return false;
}
return true;
};
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
// last :: [a] -> a
const last = xs =>
0 < xs.length ? xs.slice(-1)[0] : undefined;
// MAIN ------------------------------------------------
return main();
})();
|
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
|
#Common_Lisp
|
Common Lisp
|
(defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(column-count (second dimensions))
(lead 0))
(labels ((find-pivot (start lead)
(let ((i start))
(loop
:while (zerop (aref matrix i lead))
:do (progn
(incf i)
(when (= i row-count)
(setf i start)
(incf lead)
(when (= lead column-count)
(return-from convert-to-row-echelon-form matrix))))
:finally (return (values i lead)))))
(swap-rows (r1 r2)
(loop
:for c :upfrom 0 :below column-count
:do (rotatef (aref matrix r1 c) (aref matrix r2 c))))
(divide-row (r value)
(loop
:for c :upfrom 0 :below column-count
:do (setf (aref matrix r c)
(/ (aref matrix r c) value)))))
(loop
:for r :upfrom 0 :below row-count
:when (<= column-count lead)
:do (return matrix)
:do (multiple-value-bind (i nlead) (find-pivot r lead)
(setf lead nlead)
(swap-rows i r)
(divide-row r (aref matrix r lead))
(loop
:for i :upfrom 0 :below row-count
:when (/= i r)
:do (let ((scale (aref matrix i lead)))
(loop
:for c :upfrom 0 :below column-count
:do (decf (aref matrix i c)
(* scale (aref matrix r c))))))
(incf lead))
:finally (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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <cmath>
#ifdef M_E
static double euler_e = M_E;
#else
static double euler_e = std::exp(1); // standard fallback
#endif
#ifdef M_PI
static double pi = M_PI;
#else
static double pi = std::acos(-1);
#endif
int main()
{
std::cout << "e = " << euler_e
<< "\npi = " << pi
<< "\nsqrt(2) = " << std::sqrt(2.0)
<< "\nln(e) = " << std::log(euler_e)
<< "\nlg(100) = " << std::log10(100.0)
<< "\nexp(3) = " << std::exp(3.0)
<< "\n|-4.5| = " << std::abs(-4.5) // or std::fabs(-4.5); both work in C++
<< "\nfloor(4.5) = " << std::floor(4.5)
<< "\nceiling(4.5) = " << std::ceil(4.5)
<< "\npi^2 = " << std::pow(pi,2.0) << std::endl;
}
|
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.
|
#Groovy
|
Groovy
|
static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
|
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.
|
#Delphi
|
Delphi
|
program ReadAll;
{$APPTYPE CONSOLE}
uses Classes;
var
i: Integer;
lList: TStringList;
begin
lList := TStringList.Create;
try
lList.LoadFromFile('c:\input.txt');
// Write everything at once
Writeln(lList.Text);
// Write one line at a time
for i := 0 to lList.Count - 1 do
Writeln(lList[i]);
finally
lList.Free;
end;
end.
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
local :filecontents !decode!utf-8 !read "file.txt"
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun repString(s: String): MutableList<String> {
val reps = mutableListOf<String>()
if (s.length < 2) return reps
for (c in s) if (c != '0' && c != '1') throw IllegalArgumentException("Not a binary string")
for (len in 1..s.length / 2) {
val t = s.take(len)
val n = s.length / len
val r = s.length % len
val u = t.repeat(n) + t.take(r)
if (u == s) reps.add(t)
}
return reps
}
fun main(args: Array<String>) {
val strings = listOf(
"1001110011",
"1110111011",
"0010010010",
"1010101010",
"1111111111",
"0100101101",
"0100100",
"101",
"11",
"00",
"1"
)
println("The (longest) rep-strings are:\n")
for (s in strings) {
val reps = repString(s)
val size = reps.size
println("${s.padStart(10)} -> ${if (size > 0) reps[size - 1] else "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
|
#langur
|
langur
|
if matching(re/abc/, "somestring") { ... }
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Lasso
|
Lasso
|
local(mytext = 'My name is: Stone, Rosetta
My name is: Hippo, Campus
')
local(regexp = regexp(
-find = `(?m)^My name is: (.*?), (.*?)$`,
-input = #mytext,
-replace = `Hello! I am $2 $1`,
-ignorecase
))
while(#regexp -> find) => {^
#regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim&) + '<br />'
^}
#regexp -> reset(-input = #mytext)
#regexp -> findall
#regexp -> reset(-input = #mytext)
'<br />'
#regexp -> replaceall
|
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
|
#Burlesque
|
Burlesque
|
"Hello, world!"<-
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Quackery
|
Quackery
|
[ stack ] is times.start ( --> s )
protect times.start
[ stack ] is times.count ( --> s )
protect times.count
[ stack ] is times.action ( --> s )
protect times.action
[ ]'[ times.action put
dup times.start put
[ 1 - dup -1 > while
times.count put
times.action share do
times.count take again ]
drop
times.action release
times.start release ] is times ( n --> )
[ times.count share ] is i ( --> n )
[ times.start share i 1+ - ] is i^ ( --> n )
[ 0 times.count replace ] is conclude ( --> )
[ times.start share
times.count replace ] is refresh ( --> )
[ times.count take 1+
swap - times.count put ] is step ( --> s )
[ nested ' times nested
swap join do ] is rosetta-times ( n x --> )
|
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.)
|
#MUMPS
|
MUMPS
|
;Local
S X=$ZF(-1,"rename input.txt output.txt")
S X=$ZF(-1,"rename docs.dir mydocs.dir")
;Root of current device
S X=$ZF(-1,"rename [000000]input.txt [000000]output.txt")
S X=$ZF(-1,"rename [000000]docs.dir [000000]mydocs.dir")
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isFileRenamed(oldFile, newFile) public static returns boolean
fo = File(oldFile)
fn = File(newFile)
fRenamed = fo.renameTo(fn)
return fRenamed
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg files
if files = '' then files = 'input.txt output.txt F docs mydocs D /input.txt /output.txt F /docs /mydocs D'
loop while files.length > 0
parse files of nf ft files
select case(ft.upper())
when 'F' then do
ft = 'File'
end
when 'D' then do
ft = 'Directory'
end
otherwise do
ft = 'File'
end
end
if isFileRenamed(of, nf) then dl = 'renamed'
else dl = 'not renamed'
say ft ''''of'''' dl 'to' nf
end
return
|
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
|
#Maple
|
Maple
|
while (true) do
input := readline("input.txt"):
if input = 0 then break: fi:
input := StringTools:-Trim(input): # remove leading/trailing space
input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
printf("%s\n", input):
od:
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
poem = "---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
lines = StringSplit[poem, "\n"];
wordArray = StringSplit[#] & @ lines ;
reversedWordArray = Reverse[#] & /@ wordArray ;
linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords
|
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
|
#S-BASIC
|
S-BASIC
|
comment
Return the rot13 transformation of s, preserving case and
passing non-alphabetic characters without change
end
function rot13(s = string) = string
var i, k = integer
var ch = char
var normal, rotated = string
normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
rotated = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
for i = 1 to len(s)
ch = mid(s,i,1)
k = instr(1,normal,ch)
if k <> 0 then ch = mid(rotated,k,1)
mid(s,i,1) = ch
next i
end = s
rem - exercise the function
var plain, encoded = string
plain = "The quick brown fox jumps over the lazy red dog."
encoded = rot13(plain)
print "Plain text: "; plain
print "Encoded : "; encoded
print "Decoded : "; rot13(encoded)
end
|
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
|
#Ring
|
Ring
|
arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C" ,"XC", "L", "XL" ,"X", "IX", "V", "IV", "I"]
see "2009 = " + toRoman(2009) + nl
see "1666 = " + toRoman(1666) + nl
see "3888 = " + toRoman(3888) + nl
func toRoman val
result = ""
for i = 1 to 13
while val >= arabic[i]
result = result + roman[i]
val = val - arabic[i]
end
next
return result
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
LOOP roman_number="MCMXC'MMVIII'MDCLXVI"
arab_number=DECODE (roman_number,ROMAN)
PRINT "Roman number ",roman_number," equals ", arab_number
ENDLOOP
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Elixir
|
Elixir
|
String.duplicate("ha", 5)
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Emacs_Lisp
|
Emacs Lisp
|
(apply 'concat (make-list 5 "ha"))
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Mercury
|
Mercury
|
:- module addsub.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, string.
main(!IO) :-
command_line_arguments(Args, !IO),
filter_map(to_int, Args, CleanArgs),
(length(CleanArgs, 2) ->
X = det_index1(CleanArgs,1),
Y = det_index1(CleanArgs,2),
addsub(X, Y, S, D),
format("%d + %d = %d\n%d - %d = %d\n",
[i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO)
;
write_string("Please pass two integers on the command line.\n", !IO)
).
:- pred addsub(int::in, int::in, int::out, int::out) is det.
addsub(X, Y, S, D) :-
S = X + Y,
D = X - Y.
:- end_module addsub.
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#min
|
min
|
(over over / '* dip) :muldiv
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Crystal
|
Crystal
|
ary = [1, 1, 2, 2, "a", [1, 2, 3], [1, 2, 3], "a"]
p ary.uniq
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#jq
|
jq
|
# Let R[n] be the Recaman sequence, n >= 0, so R[0]=0.
# Input: a number, $required, specifying the required range of integers, [1 .. $required]
# to be covered by R[0] ... R[.n]
# $capture: the number of elements of the sequence to retain.
# Output: an object as described below.
# Note that .a|length will be equal to $capture.
#
def recaman_required($capture):
. as $required
| {
n: 0,
current: 0, # R[.n]
previous: null, # R[.n-1]
a: [0], # only maintained up to a[$capture-1]
used: { "0": true }, # hash for checking whether a value has already occurred
found: { "0": true }, # hash for checking how many in [0 .. $required] inclusive have been found
nfound: 1, # .found|length
foundDup: null, # the first duplicated entry in the sequence
foundDupAt: null # .foundDup == R[.foundDupAt]
}
| until ((.n >= $capture) and .foundDup and (.nfound > $required);
.n += 1
| .current -= .n
| if (.current < 1 or .used[.current|tostring]) then .current = .current + 2*.n else . end
| (.current|tostring) as $s
| .used[$s] as $alreadyUsed
| if .n < $capture then .a += [.current] else . end
| if ($alreadyUsed|not)
then .used[$s] = true
| if (.current >= 0 and .current <= $required)
then .found[$s] = true | .nfound+=1
else . end
else .
end
| if (.foundDup|not) and $alreadyUsed
then .foundDup = .current
| .foundDupAt = .n
else .
end );
1000 as $required
| 15 as $capture
| $required | recaman_required($capture)
| "The first \($capture) terms of Recaman's sequence are: \(.a)",
"The first duplicated term is a[\(.foundDupAt)] = \(.foundDup)",
"Terms up to a[\(.n)] are needed to generate 0 to \($required) inclusive."
|
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.
|
#Julia
|
Julia
|
function recaman()
a = Vector{Int}([0])
used = Dict{Int, Bool}(0 => true)
used1000 = Set(0)
founddup = false
termcount = 1
while length(used1000) <= 1000
nextterm = a[termcount] - termcount
if nextterm < 1 || haskey(used, nextterm)
nextterm += termcount + termcount
end
push!(a, nextterm)
if !haskey(used, nextterm)
used[nextterm] = true
if 1 <= nextterm <= 1000
push!(used1000, nextterm)
end
elseif !founddup
println("The first duplicated term is a[$(termcount + 1)] = $nextterm.")
founddup = true
end
if termcount == 14
println("The first 15 terms of the Recaman sequence are $a")
end
termcount += 1
end
println("Terms up to $(termcount - 1) are needed to generate 0 to 1000.")
end
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
|
#D
|
D
|
import std.stdio, std.algorithm, std.array, std.conv;
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
if (M.empty)
return;
immutable nrows = M.length;
immutable ncols = M[0].length;
size_t lead;
foreach (immutable r; 0 .. nrows) {
if (ncols <= lead)
return;
{
size_t i = r;
while (M[i][lead] == 0) {
i++;
if (nrows == i) {
i = r;
lead++;
if (ncols == lead)
return;
}
}
swap(M[i], M[r]);
}
M[r][] /= M[r][lead];
foreach (j, ref mj; M)
if (j != r)
mj[] -= M[r][] * mj[lead];
lead++;
}
}
void main() {
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}
|
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
|
#Chef
|
Chef
|
(Math/E); //e
(Math/PI); //pi
(Math/sqrt x); //square root--cube root also available (cbrt)
(Math/log x); //natural logarithm--log base 10 also available (log10)
(Math/exp x); //exponential
(Math/abs x); //absolute value
(Math/floor x); //floor
(Math/ceil x); //ceiling
(Math/pow x y); //power
|
http://rosettacode.org/wiki/Real_constants_and_functions
|
Real constants and functions
|
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest 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
|
#Clojure
|
Clojure
|
(Math/E); //e
(Math/PI); //pi
(Math/sqrt x); //square root--cube root also available (cbrt)
(Math/log x); //natural logarithm--log base 10 also available (log10)
(Math/exp x); //exponential
(Math/abs x); //absolute value
(Math/floor x); //floor
(Math/ceil x); //ceiling
(Math/pow x y); //power
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#Haskell
|
Haskell
|
import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#E
|
E
|
<file:foo.txt>.getText()
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Elixir
|
Elixir
|
defmodule FileReader do
# Read in the file
def read(path) do
case File.read(path) do
{:ok, body} ->
IO.inspect body
{:error,reason} ->
:file.format_error(reason)
end
end
# Open the file path, then read in the file
def bit_read(path) do
case File.open(path) do
{:ok, file} ->
# :all can be replaced with :line, or with a positive integer to specify the number of characters to read.
IO.read(file,:all)
|> IO.inspect
{:error,reason} ->
:file.format_error(reason)
end
end
end
|
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
|
#LFE
|
LFE
|
(defun get-reps (text)
(lists:filtermap
(lambda (x)
(case (get-rep text (lists:split x text))
('() 'false)
(x `#(true ,x))))
(lists:seq 1 (div (length text) 2))))
(defun get-rep
((text `#(,head ,tail))
(case (string:str text tail)
(1 head)
(_ '()))))
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Lua
|
Lua
|
test = "My name is Lua."
pattern = ".*name is (%a*).*"
if test:match(pattern) then
print("Name found.")
end
sub, num_matches = test:gsub(pattern, "Hello, %1!")
print(sub)
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module CheckIt {
declare global ObjRegEx "VBscript.RegExp"
Function RegEx.Replace$(from$, what$) {
Method ObjRegEx, "Replace", from$, what$ as response$
=response$
}
Function RegEx.Test(what$) {
Method ObjRegEx, "Test", what$ as response
=response
}
Print Type$(ObjRegEx)
With ObjRegEx, "Global", True, "Pattern" as pattern$
pattern$="Mona Lisa"
Print RegEx.Test("The Mona Lisa is in the Louvre.")=true
Print RegEx.Replace$("The Mona Lisa is in the Louvre.", "La Gioconda")
Pattern$ = " {2,}"
Print "Myer Ken, Vice President, Sales and Services"
\\ Removing some spaces
Print RegEx.Replace$("Myer Ken, Vice President, Sales and Services", " ")
pattern$="(\d{3})-(\d{3})-(\d{4})"
Method ObjRegEx, "Execute", "555-123-4567, 555-943-6717" as MyMatches
Print Type$(MyMatches) ' it is a IMatchCollection2
With MyMatches, "Count" as count, "Item" as List$()
For i=0 to Count-1 : Print List$(i) : Next i
Print RegEx.Replace$("555-123-4567, 555-943-6717", "($1) $2-$3")
Pattern$ = "(\S+), (\S+)"
Print RegEx.Replace$("Myer, Ken", "$2 $1")
Method ObjRegEx, "Execute", "Myer, Ken" as MyMatches
Rem : DisplayFunctions(MyMatches)
\\ we can use Enumerator
With MyMatches, "_NewEnum" as New Matches
Rem : DisplayFunctions(Matches)
With Matches, "Value" as New item$
While Matches {
Print Item$
}
\\ Or just using the list$()
For i=0 to Count-1 : Print List$(i) : Next i
declare ObjRegEx Nothing
End
Sub DisplayFunctions(x)
Local cc=param(x), ec=each(cc)
while ec {
Print eval$(ec) ' print every function/property of object x
}
End Sub
}
Checkit
\\ internal has no pattern. There is a like operator (~) for strings which use pattern matching (using VB6 like). We can use Instr() and RInstr() for strings.
Module Internal {
what$="Mona Lisa"
Document a$="The Mona Lisa is in the Louvre."
Find a$, what$
Read FindWhere
If FindWhere<>0 then Read parNo, parlocation
\\ replace in place
Insert FindWhere, Len(what$) a$="La Gioconda"
Report a$
n$="The Mona Lisa is in the Louvre, not the Mona Lisa"
Report Replace$("Mona Lisa", "La Gioconda", n$, 1, 1) ' replace from start only one
dim a$()
a$()=Piece$("Myer, Ken",", ")
Print a$(1)+", "+a$(0)="Ken, Myer"
}
Internal
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
const char *sa = "abcdef";
const char *su = "as⃝df̅"; /* Should be in your native locale encoding. Mine is UTF-8 */
int is_comb(wchar_t c)
{
if (c >= 0x300 && c <= 0x36f) return 1;
if (c >= 0x1dc0 && c <= 0x1dff) return 1;
if (c >= 0x20d0 && c <= 0x20ff) return 1;
if (c >= 0xfe20 && c <= 0xfe2f) return 1;
return 0;
}
wchar_t* mb_to_wchar(const char *s)
{
wchar_t *u;
size_t len = mbstowcs(0, s, 0) + 1;
if (!len) return 0;
u = malloc(sizeof(wchar_t) * len);
mbstowcs(u, s, len);
return u;
}
wchar_t* ws_reverse(const wchar_t* u)
{
size_t len, i, j;
wchar_t *out;
for (len = 0; u[len]; len++);
out = malloc(sizeof(wchar_t) * (len + 1));
out[len] = 0;
j = 0;
while (len) {
for (i = len - 1; i && is_comb(u[i]); i--);
wcsncpy(out + j, u + i, len - i);
j += len - i;
len = i;
}
return out;
}
char *mb_reverse(const char *in)
{
size_t len;
char *out;
wchar_t *u = mb_to_wchar(in);
wchar_t *r = ws_reverse(u);
len = wcstombs(0, r, 0) + 1;
out = malloc(len);
wcstombs(out, r, len);
free(u);
free(r);
return out;
}
int main(void)
{
setlocale(LC_CTYPE, "");
printf("%s => %s\n", sa, mb_reverse(sa));
printf("%s => %s\n", su, mb_reverse(su));
return 0;
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#R
|
R
|
f1 <- function(...){print("coucou")}
f2 <-function(f,n){
lapply(seq_len(n),eval(f))
}
f2(f1,4)
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Racket
|
Racket
|
#lang racket/base
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket
(for ((_ n)) (f)))
(define (repeat2 f n) ; This is a bit more "functional programmingy"
(when (positive? n) (f) (repeat2 f (sub1 n))))
(display "...")
(repeat (λ () (display " and over")) 5)
(display "...")
(repeat2 (λ () (display " & over")) 5)
(newline)
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#NewLISP
|
NewLISP
|
(rename-file "./input.txt" "./output.txt")
(rename-file "./docs" "./mydocs")
(rename-file "/input.txt" "/output.txt")
(rename-file "/docs" "/mydocs")
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Nim
|
Nim
|
import os
moveFile("input.txt", "output.txt")
moveFile("docs", "mydocs")
moveFile(DirSep & "input.txt", DirSep & "output.txt")
moveFile(DirSep & "docs", DirSep & "mydocs")
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function testReverseWords
testStr = {'---------- Ice and Fire ------------' ; ...
'' ; ...
'fire, in end will world the say Some' ; ...
'ice. in say Some' ; ...
'desire of tasted I''ve what From' ; ...
'fire. favor who those with hold I' ; ...
'' ; ...
'... elided paragraph last ...' ; ...
'' ; ...
'Frost Robert -----------------------' };
for k = 1:length(testStr)
fprintf('%s\n', reverseWords(testStr{k}))
end
end
function strOut = reverseWords(strIn)
strOut = strtrim(strIn);
if ~isempty(strOut)
% Could use strsplit() instead of textscan() in R2013a or later
words = textscan(strOut, '%s');
words = words{1};
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
end
end
|
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
|
#S-lang
|
S-lang
|
variable old = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
variable new = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
define rot13(s) {
s = strtrans(s, old, new);
return s;
}
define rot13_stream(s) {
variable ln;
while (-1 != fgets(&ln, s))
fputs(rot13(ln), stdout);
}
if (__argc > 1) {
variable arg, fp;
foreach arg (__argv[[1:]]) {
fp = fopen(arg, "r");
rot13_stream(fp);
}
}
else
rot13_stream(stdin);
|
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
|
#Ruby
|
Ruby
|
Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
def roman(num)
return Symbols[num] if Symbols.has_key?(num)
Subtractors.each do |cutPoint, subtractor|
return roman(cutPoint) + roman(num - cutPoint) if num > cutPoint
return roman(subtractor) + roman(num + subtractor) if num >= cutPoint - subtractor and num < cutPoint
end
end
[1990, 2008, 1666].each do |i|
puts "%4d => %s" % [i, roman(i)]
end
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/bash
roman_to_dec() {
local rnum=$1
local n=0
local prev=0
for ((i=${#rnum}-1;i>=0;i--))
do
case "${rnum:$i:1}" in
M) a=1000 ;;
D) a=500 ;;
C) a=100 ;;
L) a=50 ;;
X) a=10 ;;
V) a=5 ;;
I) a=1 ;;
esac
if [[ $a -lt $prev ]]
then
let n-=a
else
let n+=a
fi
prev=$a
done
echo "$rnum = $n"
}
roman_to_dec MCMXC
roman_to_dec MMVIII
roman_to_dec MDCLXVI
|
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
|
#Erlang
|
Erlang
|
repeat(X,N) ->
lists:flatten(lists:duplicate(N,X)).
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Nemerle
|
Nemerle
|
using System;
using System.Console;
using Nemerle.Assertions;
module MultReturn
{
MinMax[T] (ls : list[T]) : T * T
where T : IComparable
requires ls.Length > 0 otherwise throw ArgumentException("An empty list has no extreme values.")
{
def greaterOf(a, b) { if (a.CompareTo(b) > 0) a else b }
def lesserOf(a, b) { if (a.CompareTo(b) < 0) a else b }
(ls.FoldLeft(ls.Head, lesserOf), ls.FoldLeft(ls.Head, greaterOf)) // packing tuple
}
Main() : void
{
def nums = [1, 34, 12, -5, 4, 0];
def (min, max) = MinMax(nums); // unpacking tuple
WriteLine($"Min of nums = $min; max of nums = $max");
}
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols nobinary
-- =============================================================================
class RReturnMultipleVals public
properties constant
L = 'L'
R = 'R'
K_lipsum = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
K_1024 = 1024
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method RReturnMultipleVals() public
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
arg = Rexx(args)
parse arg nv_ sv_ .
if \nv_.datatype('n') then nv_ = K_1024
if sv_ = '' then sv_ = K_lipsum
lcl = RReturnMultipleVals()
rvr = lcl.getPair(nv_, sv_) -- multiple values returned as a string. Use PARSE to extract values
parse rvr val1 val2
say 'Results extracted from a NetRexx string:'
say val1',' val2
say
rvr = lcl.getPairFromRexx(nv_, sv_) -- values returned in a NetRexx indexed string
say 'Results extracted from a NetRexx "indexed string":'
say rvr[L]',' rvr[R]
say
rvp = lcl.getPairFromPair(nv_, sv_) -- values returned in a bespoke object
say 'Results extracted from a composite object:'
say rvp.getLeftVal',' rvp.getRightVal
say
rvl = lcl.getPairFromList(nv_, sv_) -- values returned in a Java Collection "List" object
say 'Results extracted from a Java Colections "List" object:'
say rvl.get(0)',' rvl.get(1)
say
rvm = lcl.getPairFromMap(nv_, sv_) -- values returned in a Java Collection "Map" object
say 'Results extracted from a Java Colections "Map" object:'
say rvm.get(L)',' rvm.get(R)
say
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- returns the values in a NetRexx string.
-- Caller can the power of PARSE to extract the results
method getPair(nv_, sv_) public returns Rexx
return nv_ sv_
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Return the values as members of a NetRexx indexed string
method getPairFromRexx(nv_, sv_) public returns Rexx
rval = ''
rval[L] = nv_
rval[R] = sv_
return rval
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Return a bespoke object.
-- Permits any number and type of value to be returned
method getPairFromPair(nv_, sv_) public returns RReturnMultipleVals.Pair
rset = RReturnMultipleVals.Pair(nv_, sv_)
return rset
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Exploit Java Collections classes to assemble a collection of results.
-- This example uses java.util.List
method getPairFromList(nv_, sv_) public returns java.util.List
rset = ArrayList()
rset.add(nv_)
rset.add(sv_)
return rset
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- This example uses java.util.Map
method getPairFromMap(nv_, sv_) public returns java.util.Map
rset = HashMap()
rset.put(L, nv_)
rset.put(R, sv_)
return rset
-- =============================================================================
class RReturnMultipleVals.Pair dependent
properties indirect
leftVal
rightVal
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method Pair(nv_ = parent.K_1024, sv_ = parent.K_lipsum) public
setLeftVal(nv_)
setRightVal(sv_)
return
|
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).
|
#D
|
D
|
void main() {
import std.stdio, std.algorithm;
[1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]
.sort()
.uniq
.writeln;
}
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#Kotlin
|
Kotlin
|
// Version 1.2.60
fun main(args: Array<String>) {
val a = mutableListOf(0)
val used = mutableSetOf(0)
val used1000 = mutableSetOf(0)
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.size < 1001) {
var next = a[n - 1] - n
if (next < 1 || used.contains(next)) next += 2 * n
val alreadyUsed = used.contains(next)
a.add(next)
if (!alreadyUsed) {
used.add(next)
if (next in 0..1000) used1000.add(next)
}
if (n == 14) {
println("The first 15 terms of the Recaman's sequence are: $a")
}
if (!foundDup && alreadyUsed) {
println("The first duplicated term is a[$n] = $next")
foundDup = true
}
if (used1000.size == 1001) {
println("Terms up to a[$n] are needed to generate 0 to 1000")
}
n++
}
}
|
http://rosettacode.org/wiki/Reduced_row_echelon_form
|
Reduced row echelon form
|
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this will probably be a two-dimensional array).
Built-in functions or this pseudocode (from Wikipedia) may be used:
function ToReducedRowEchelonForm(Matrix M) is
lead := 0
rowCount := the number of rows in M
columnCount := the number of columns in M
for 0 ≤ r < rowCount do
if columnCount ≤ lead then
stop
end if
i = r
while M[i, lead] = 0 do
i = i + 1
if rowCount = i then
i = r
lead = lead + 1
if columnCount = lead then
stop
end if
end if
end while
Swap rows i and r
If M[r, lead] is not 0 divide row r by M[r, lead]
for 0 ≤ i < rowCount do
if i ≠ r do
Subtract M[i, lead] multiplied by row r from row i
end if
end for
lead = lead + 1
end for
end function
For testing purposes, the RREF of this matrix:
1 2 -1 -4
2 3 -1 -11
-2 0 -3 22
is:
1 0 0 -8
0 1 0 1
0 0 1 -2
|
#Euphoria
|
Euphoria
|
function ToReducedRowEchelonForm(sequence M)
integer lead,rowCount,columnCount,i
sequence temp
lead = 1
rowCount = length(M)
columnCount = length(M[1])
for r = 1 to rowCount do
if columnCount <= lead then
exit
end if
i = r
while M[i][lead] = 0 do
i += 1
if rowCount = i then
i = r
lead += 1
if columnCount = lead then
exit
end if
end if
end while
temp = M[i]
M[i] = M[r]
M[r] = temp
M[r] /= M[r][lead]
for j = 1 to rowCount do
if j != r then
M[j] -= M[j][lead]*M[r]
end if
end for
lead += 1
end for
return M
end function
? ToReducedRowEchelonForm(
{ { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } })
|
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
|
#COBOL
|
COBOL
|
E *> e
PI *> Pi
SQRT(n) *> Sqaure root
LOG(n) *> Natural logarithm
LOG10(n) *> Logarithm (base 10)
EXP(n) *> e to the nth power
ABS(n) *> Absolute value
INTEGER(n) *> While not a proper floor function, it is implemented in the same way.
*> There is no ceiling function. However, it could be implemented like so:
ADD 1 TO N
MOVE INTEGER(N) TO Result
*> There is no pow function, although the COMPUTE verb does have an exponention operator.
COMPUTE Result = N ** 2
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main() # remove lines
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail # open to read
every put(F := [],|read(f)) # file to list
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null # mark delete
f := open(fn,"w") | fail # open to rewrite
every write(\!F) # write non-nulls
close(f)
return # done
end
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Emacs_Lisp
|
Emacs Lisp
|
(setq my-variable (with-temp-buffer
(insert-file-contents "foo.txt")
(buffer-string)))
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Erlang
|
Erlang
|
{ok, B} = file:read_file("myfile.txt").
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#Maple
|
Maple
|
repstr? := proc( s :: string )
local per := StringTools:-Period( s );
if 2 * per <= length( s ) then
true, s[ 1 .. per ]
else
false, ""
end if
end proc:
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
RepStringQ[strin_String]:=StringCases[strin,StartOfString~~Repeated[x__,{2,\[Infinity]}]~~y___~~EndOfString/;StringMatchQ[x,StartOfString~~y~~___]:>x, Overlaps -> All]
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#M4
|
M4
|
regexp(`GNUs not Unix', `\<[a-z]\w+')
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Maple
|
Maple
|
#Examples from Maple Help
StringTools:-RegMatch("^ab+bc$", "abbbbc");
StringTools:-RegMatch("^ab+bc$", "abbbbcx");
StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2");
StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#C.23
|
C#
|
static string ReverseString(string input)
{
char[] inputChars = input.ToCharArray();
Array.Reverse(inputChars);
return new string(inputChars);
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Raku
|
Raku
|
sub repeat (&f, $n) { f() xx $n };
sub example { say rand }
repeat(&example, 3);
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Objeck
|
Objeck
|
use IO;
bundle Default {
class FileExample {
function : Main(args : String[]) ~ Nil {
File->Rename("input.txt", "output.txt");
File->Rename("docs", "mydocs");
File->Rename("/input.txt", "/output.txt");
File->Rename("/docs", "/mydocs");
}
}
}
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#MAXScript
|
MAXScript
|
-- MAXScript : Reverse words in a string : N.H. 2019
--
(
text = stringstream "---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------\n"
clearListener()
seek text 0
while eof text == false do
(
nextLine = (readLine text)
if nextLine == "" then
(
print ""
continue
) -- end of if
revLine = ""
eachWord = filterString nextLine " "
for k = eachWord.count to 1 by -1 do
(
revLine = revLine + eachWord[k]
-- Only add space between words not at the end of line
if k != 1 then revLine = revLine + " "
) -- end of for k
print revLine
) -- end of while eof
)
|
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
|
#Scala
|
Scala
|
scala> def rot13(s: String) = s map {
| case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar
| case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar
| case c => c
| }
rot13: (s: String)String
scala> rot13("7 Cities of Gold.")
res61: String = 7 Pvgvrf bs Tbyq.
scala> rot13(res61)
res62: String = 7 Cities of Gold.
|
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
|
#Run_BASIC
|
Run BASIC
|
[loop]
input "Input value:";val$
print roman$(val$)
goto [loop]
' ------------------------------
' Roman numerals
' ------------------------------
FUNCTION roman$(val$)
a2r$ = "M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1"
v = val(val$)
for i = 1 to 13
r$ = word$(a2r$,i,",")
a = val(word$(r$,2,":"))
while v >= a
roman$ = roman$ + word$(r$,1,":")
v = v - a
wend
next i
END FUNCTION
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#VBA
|
VBA
|
Option Explicit
Sub Main_Romans_Decode()
Dim Arr(), i&
Arr = Array("III", "XXX", "CCC", "MMM", "VII", "LXVI", "CL", "MCC", "IV", "IX", "XC", "ICM", "DCCCXCIX", "CMI", "CIM", "MDCLXVI", "MCMXC", "MMXVII")
For i = 0 To UBound(Arr)
Debug.Print Arr(i) & " >>> " & lngConvert(CStr(Arr(i)))
Next
End Sub
Function Convert(Letter As String) As Long
Dim Romans(), DecInt(), Pos As Integer
Romans = Array("M", "D", "C", "L", "X", "V", "I")
DecInt = Array(1000, 500, 100, 50, 10, 5, 1)
Pos = -1
On Error Resume Next
Pos = Application.Match(Letter, Romans, 0) - 1
On Error GoTo 0
If Pos <> -1 Then Convert = DecInt(Pos)
End Function
Function lngConvert(strRom As String) 'recursive function
Dim i As Long, iVal As Integer
If Len(strRom) = 1 Then
lngConvert = Convert(strRom)
Else
iVal = Convert(Mid(strRom, 1, 1))
If iVal < Convert(Mid(strRom, 2, 1)) Then iVal = iVal * (-1)
lngConvert = iVal + lngConvert(Mid(strRom, 2, Len(strRom) - 1))
End If
End Function
|
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
|
#ERRE
|
ERRE
|
PROCEDURE REPEAT_STRING(S$,N%->REP$)
LOCAL I%
REP$=""
FOR I%=1 TO N% DO
REP$=REP$+S$
END FOR
END PROCEDURE
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Nim
|
Nim
|
proc addsub(x, y: int): (int, int) =
(x + y, x - y)
var (a, b) = addsub(12, 15)
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Objeck
|
Objeck
|
class Program {
function : Main(args : String[]) ~ Nil {
a := IntHolder->New(3); b := IntHolder->New(7);
Addon(a,b);
a->Get()->PrintLine(); b->Get()->PrintLine();
}
function : Addon(a : IntHolder, b : IntHolder) ~ Nil {
a->Set(a->Get() + 2); b->Set(b->Get() + 13);
}
}
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Delphi
|
Delphi
|
program RemoveDuplicateElements;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
i: Integer;
lIntegerList: TList<Integer>;
const
INT_ARRAY: array[1..7] of Integer = (1, 2, 2, 3, 4, 5, 5);
begin
lIntegerList := TList<Integer>.Create;
try
for i in INT_ARRAY do
if not lIntegerList.Contains(i) then
lIntegerList.Add(i);
for i in lIntegerList do
Writeln(i);
finally
lIntegerList.Free;
end;
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.
|
#Lua
|
Lua
|
local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt)
if not alreadyUsed then
used[nxt] = true
if 0<=nxt and nxt<=1000 then
used1000[nxt] = true
end
end
if n==14 then
io.write("The first 15 terms of the Recaman sequence are:")
for k=0,#a do
io.write(" "..a[k])
end
print()
end
if not foundDup and alreadyUsed then
print("The first duplicated term is a["..n.."] = "..nxt)
foundDup = true
end
if #used1000 == 1001 then
print("Terms up to a["..n.."] are needed to generate 0 to 1000")
end
n = n + 1
end
|
http://rosettacode.org/wiki/Reduced_row_echelon_form
|
Reduced row echelon form
|
Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this will probably be a two-dimensional array).
Built-in functions or this pseudocode (from Wikipedia) may be used:
function ToReducedRowEchelonForm(Matrix M) is
lead := 0
rowCount := the number of rows in M
columnCount := the number of columns in M
for 0 ≤ r < rowCount do
if columnCount ≤ lead then
stop
end if
i = r
while M[i, lead] = 0 do
i = i + 1
if rowCount = i then
i = r
lead = lead + 1
if columnCount = lead then
stop
end if
end if
end while
Swap rows i and r
If M[r, lead] is not 0 divide row r by M[r, lead]
for 0 ≤ i < rowCount do
if i ≠ r do
Subtract M[i, lead] multiplied by row r from row i
end if
end for
lead = lead + 1
end for
end function
For testing purposes, the RREF of this matrix:
1 2 -1 -4
2 3 -1 -11
-2 0 -3 22
is:
1 0 0 -8
0 1 0 1
0 0 1 -2
|
#Factor
|
Factor
|
USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
|
http://rosettacode.org/wiki/Real_constants_and_functions
|
Real constants and functions
|
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest 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
|
#Common_Lisp
|
Common Lisp
|
(exp 1) ; e (Euler's number)
pi ; pi constant
(sqrt x) ; square root: works for negative reals and complex
(log x) ; natural logarithm: works for negative reals and complex
(log x 10) ; logarithm base 10
(exp x) ; exponential
(abs x) ; absolute value: result exact if input exact: (abs -1/3) -> 1/3.
(floor x) ; floor: restricted to real, two valued (second value gives residue)
(ceiling x) ; ceiling: restricted to real, two valued (second value gives residue)
(expt x y) ; power
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2
Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
|
#J
|
J
|
removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
|
http://rosettacode.org/wiki/Read_entire_file
|
Read entire file
|
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.
|
#Euphoria
|
Euphoria
|
function load_file(sequence filename)
integer fn,c
sequence data
fn = open(filename,"r") -- "r" for text files, "rb" for binary files
if (fn = -1) then return {} end if -- failed to open the file
data = {} -- init to empty sequence
c = getc(fn) -- prime the char buffer
while (c != -1) do -- while not EOF
data &= c -- append each character
c = getc(fn) -- next char
end while
close(fn)
return data
end function
|
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
|
#Modula-2
|
Modula-2
|
MODULE RepStrings;
FROM InOut IMPORT Write, WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Copy, Length;
(* Find the length of the longest rep-string given a string.
If there is no rep-string, the result is 0. *)
PROCEDURE repLength(s: ARRAY OF CHAR): CARDINAL;
VAR strlen, replen, i, j: CARDINAL;
ok: BOOLEAN;
BEGIN
strlen := Length(s);
FOR replen := strlen DIV 2 TO 1 BY -1 DO
ok := TRUE;
i := 0;
WHILE ok AND (i < replen) DO
j := i + replen;
WHILE (i+j < strlen) AND (s[i] = s[j]) DO
j := j + replen;
END;
ok := ok AND (i+j >= strlen);
INC(i);
END;
IF ok THEN RETURN replen; END;
END;
RETURN 0;
END repLength;
(* Store the longest rep-string in the given buffer. *)
PROCEDURE repString(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR len: CARDINAL;
BEGIN
len := repLength(in);
Copy(in, 0, len, out);
out[len] := CHR(0);
END repString;
(* Display the longest rep-string given a string *)
PROCEDURE rep(s: ARRAY OF CHAR);
VAR buf: ARRAY [0..63] OF CHAR;
BEGIN
WriteString(s);
WriteString(": ");
repString(s, buf);
WriteString(buf);
WriteLn();
END rep;
(* Test cases *)
BEGIN
rep("1001110011");
rep("1110111011");
rep("0010010010");
rep("1010101010");
rep("1111111111");
rep("0100101101");
rep("0100100");
rep("101");
rep("11");
rep("00");
rep("1");
END RepStrings.
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]]
StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#MAXScript
|
MAXScript
|
samples = #("Some string 123","Example text 123","string",\
"ThisString Will Not Match","A123,333,string","123451")
samples2 = #("I am a string","Me too.")
regex = dotnetobject "System.Text.RegularExpressions.Regex" ".*\bstring*"
regex2 = dotnetobject "System.Text.RegularExpressions.Regex" "\ba\b"
clearlistener()
format "Pattern is : %\n" (regex.toString())
for i in samples do
(
if regex.ismatch(i) then
(
format "The string \"%\" matches the pattern\n" i
)
else
(
format "The string \"%\" doesn't match the pattern\n" i
)
)
-- replacement
format "Pattern is : %\n" (regex2.toString())
for i in samples2 do
(
if regex2.ismatch(i) then
(
local replaced = regex2.replace i "another"
format "The string \"%\" matched the pattern, so it was replaced: \"%\"\n" i replaced
)
else
(
format "The string \"%\" does not match the pattern\n" i
)
)
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s;
std::getline(std::cin, s);
std::reverse(s.begin(), s.end()); // modifies s
std::cout << s << std::endl;
return 0;
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Red
|
Red
|
Red[]
myrepeat: function [fn n] [loop n [do fn]]
myrepeat [print "hello"] 3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.