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/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Simula | Simula | TEXT PROCEDURE ROT13(INP); TEXT INP;
BEGIN
CHARACTER PROCEDURE ROT13CHAR(C); CHARACTER C;
ROT13CHAR :=
CHAR(
RANK(C) +
(IF C >= 'A' AND C <= 'M' THEN 13 ELSE
IF C >= 'a' AND C <= 'm' THEN 13 ELSE
... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #SenseTalk | SenseTalk | function RomanNumeralsEncode number
put [
(1, "I"),
(4, "IV"),
(5, "V"),
(9, "IX"),
(10, "X"),
(40, "XL"),
(50, "L"),
(90, "XC"),
(100, "C"),
(400, "CD"),
(500, "D"),
(900, "CM"),
(1000, "M")
] into values
repeat for index = each item of (the number of items in values)..1
put item ind... |
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 decima... | #XPL0 | XPL0 | string 0; \use zero-terminated strings
code CrLf=9, IntOut=11;
func Roman(Str); \Convert Roman numeral string to decimal value
char Str;
int I, Val, Val0, Sum;
[I:= 0; Sum:= 0; Val0:= 5000;
loop [case Str(I) of
^M: Val:= 1000;
^D: Val:= 500;
^C:... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Free_Pascal | Free Pascal | strUtils.dupeString('ha', 5) |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' A character is essentially a string of length 1 in FB though there is a built-in function, String,
' which creates a string by repeating a character a given number of times.
' To avoid repeated concatenation (a slow operation) when the string to be repeated has a length
' greater than one, we in... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PHP | PHP | function addsub($x, $y) {
return array($x + $y, $x - $y);
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Picat | Picat | main =>
[A,B,C] = fun(10),
println([A,B,C]).
fun(N) = [2*N-1,2*N,2*N+1]. |
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
... | #Elixir | Elixir | defmodule RC do
# Set approach
def uniq1(list), do: MapSet.new(list) |> MapSet.to_list
# Sort approach
def uniq2(list), do: Enum.sort(list) |> Enum.dedup
# Go through the list approach
def uniq3(list), do: uniq3(list, [])
defp uniq3([], res), do: Enum.reverse(res)
defp uniq3([h|t], res) do
if ... |
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... | #Phix | Phix | with javascript_semantics
bool found_duplicate = false
sequence a = {0}, used = {} -- (grows to 1,942,300 entries)
integer all_used = 0, n = 1, next, prev = 0
while n<=15 or not found_duplicate or all_used<1000 do
next = prev - n
if next<1 or (next<=length(used) and used[next]) then
next = prev + 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 wil... | #Haskell | Haskell | import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r : rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
wh... |
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 ... | #Elm | Elm | e -- e
pi -- pi
sqrt x -- square root
logBase 3 9 -- logarithm (any base)
e^x -- exponential
abs x -- absolute value
floor x -- floor
ceiling x -- ceiling
2 ^ 3 -- 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 ... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(math_constants).
-export([main/0]).
main() ->
io:format("~p~n", [math:exp(1)] ), % e
io:format("~p~n", [math:pi()] ), % pi
io:format("~p~n", [math:sqrt(16)] ), % square root
io:format("~p~n", [math:log(10)] ), % natural logarithm
io:format("~p~n", [math:log10(10)] ),... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Lua | Lua | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
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... | #FutureBasic | FutureBasic | _window = 1
begin enum 1
_scrollView
_textView
end enum
void local fn BuildWindow
CGRect r = {0,0,550,400}
window _window, @"Read Entire File", r
scrollview _scrollView, r
ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable )
textview _textView,, _scrollView
end fn
local fn ... |
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... | #Gambas | Gambas | Public Sub Form_Open()
Dim sFile As String
sFile = File.Load(User.home &/ "file.txt")
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 e... | #Perl | Perl | foreach (qw(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1)) {
print "$_\n";
if (/^(.+)\1+(.*$)(?(?{ substr($1, 0, length $2) eq $2 })|(?!))/) {
print ' ' x length $1, "$1\n\n";
} else {
print " (no repeat)\n\n";
}
} |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Phix | Phix | function list_reps(string r)
sequence replist = {}
integer n = length(r)
for m=1 to floor(n/2) do
string s = r[1..m]
if join(repeat(s,floor(n/m)+1),"")[1..n]=r then
replist = append(replist,s)
end if
end for
return replist
end function
constant tests = {"1001110011",
... |
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
| #OCaml | OCaml | #load "str.cma";;
let str = "I am a string";;
try
ignore(Str.search_forward (Str.regexp ".*string$") str 0);
print_endline "ends with 'string'"
with Not_found -> ()
;; |
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
| #Ol | Ol |
; matching:
(define regex (string->regex "m/aa(bb|cc)dd/"))
(print (regex "aabbddx")) ; => true
(print (regex "aaccddx")) ; => true
(print (regex "aabcddx")) ; => false
; substitute part of a string:
(define regex (string->regex "s/aa(bb|cc)dd/HAHAHA/"))
(print (regex "aabbddx")) ; => HAHAHAx
(print (regex "aaccddx... |
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
... | #CLU | CLU | reverse = proc (s: string) returns (string)
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
array[char]$addl(rslt,c)
end
return(string$ac2s(rslt))
end reverse
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, reverse... |
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.
| #Stata | Stata | function repeat(f,n) {
for (i=1; i<=n; i++) (*f)()
}
function hello() {
printf("Hello\n")
}
repeat(&hello(),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.
| #Swift | Swift | func repeat(n: Int, f: () -> ()) {
for _ in 0..<n {
f()
}
}
repeat(4) { println("Example") } |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #PHP | PHP | <?php
rename('input.txt', 'output.txt');
rename('docs', 'mydocs');
rename('/input.txt', '/output.txt');
rename('/docs', '/mydocs');
?> |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #PicoLisp | PicoLisp | (call 'mv "input.txt" "output.txt")
(call 'mv "docs" "mydocs")
(call 'mv "/input.txt" "/output.txt")
(call 'mv "/docs" "/mydocs") |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Pike | Pike | int main(){
mv("input.txt", "output.txt");
mv("/input.txt", "/output.txt");
mv("docs", "mydocs");
mv("/docs", "/mydocs");
} |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #OCaml | OCaml | #load "str.cma"
let input = ["---------- Ice and Fire ------------";
"";
"fire, in end will world the say Some";
"ice. in say Some";
"desire of tasted I've what From";
"fire. favor who those with hold I";
"";
"... elided paragraph last ...";
"";
"F... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Slate | Slate | #!/usr/local/bin/slate
ch@(String Character traits) rot13
[| value |
upper ::= ch isUppercase.
value := ch toLowercase as: Integer.
(value >= 97) /\ [value < 110]
ifTrue: [value += 13]
ifFalse: [(value > 109) /\ [value <= 122]
ifTrue: [value -= 13]].
upper
ifTrue: [(value as: Strin... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #SETL | SETL | examples := [2008, 1666, 1990];
for example in examples loop
print( roman_numeral(example) );
end loop;
proc roman_numeral( n );
R := [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
roman := '';
... |
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 decima... | #XQuery | XQuery |
xquery version "3.1";
declare function local:decode-roman-numeral($roman-numeral as xs:string) {
$roman-numeral
=> upper-case()
=> for-each(
function($roman-numeral-uppercase) {
analyze-string($roman-numeral-uppercase, ".")/fn:match
! map { "M": 1000, "D": 500, "C": 10... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Frink | Frink |
println[repeat["ha", 5]]
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PicoLisp | PicoLisp | (de addsub (X Y)
(list (+ X Y) (- X Y)) ) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Pike | Pike | array(int) addsub(int x, int y)
{
return ({ x+y, x-y });
}
[int z, int w] = addsub(5,4); |
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
... | #Erlang | Erlang | List = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5].
UniqueList = gb_sets:to_list(gb_sets:from_list(List)).
% Alternatively the builtin:
Unique_list = lists:usort( List ).
|
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... | #PHP | PHP | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$already... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
tM := [[ 1, 2, -1, -4],
[ 2, 3, -1,-11],
[ -2, 0, -3, 22]]
showMat(rref(tM))
end
procedure rref(M)
lead := 1
rCount := *\M | stop("no Matrix?")
cCount := *(M[1]) | 0
every r := !rCount do {
i := r
while M[i,lead] = 0 do {
... |
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 ... | #ERRE | ERRE | PROGRAM R_C_F
FUNCTION CEILING(X)
CEILING=INT(X)-(X-INT(X)>0)
END FUNCTION
FUNCTION FLOOR(X)
FLOOR=INT(X)
END FUNCTION
BEGIN
PRINT(EXP(1)) ! e not available
PRINT(π) ! pi is available or ....
PRINT(4*ATN(1)) ! .... equal to
X=12.345
Y=1.23
... |
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 ... | #F.23 | F# | open System
let main _ =
Console.WriteLine(Math.E); // e
Console.WriteLine(Math.PI); // Pi
Console.WriteLine(Math.Sqrt(10.0)); // Square Root
Console.WriteLine(Math.Log(10.0)); // Logarithm
Console.WriteLine(Math.Log10(10.0)); // Base 10 Logarithm
Console.WriteL... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. O... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #NewLISP | NewLISP |
(context 'ABC)
(define (remove-lines-from-a-file filename start num)
(setf new-content "")
(setf row-counter 0)
(setf start-delete-row start)
(setf end-delete-row (+ start num -1))
(setf file-content (read-file filename))
(setf max-rows (length (parse file-content "\n" 0)))
(cond
... |
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... | #GAP | GAP | InputTextFile("input.txt");
s := ReadAll(f);; # two semicolons to hide the result, which may be long
CloseStream(f); |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Genie | Genie | [indent=4]
/*
Read entire file, in Genie
valac readEntireFile.gs
./readEntireFile [filename]
*/
init
fileName:string
fileContents:string
fileName = (args[1] is null) ? "readEntireFile.gs" : args[1]
try
FileUtils.get_contents(fileName, out fileContents)
except exc:Error
... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def repstr /# s n -- s #/
"" swap
for drop
over chain
endfor
nip
enddef
def repString /# s -- s #/
len dup var sz
2 / 1 swap 2 tolist for
var i
1 i slice var chunk
chunk sz i / 1 + repstr
1 sz slice nip over
== if c... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Picat | Picat | go =>
Strings = [
"1001110011", % 10011
"1110111011", % 1110
"0010010010", % 001
"1010101010", % 1010
"1111111111", % 11111
"0100101101", % no solution
"0100100",... |
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
| #ooRexx | ooRexx | /* Rexx */
/* Using the RxRegExp Regular Expression built-in utility class */
st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman'
rx1 = '[Ff]?e' -- unlike most regex engines, RxRegExp uses '?' instead of '.' to match any single character
sbx = 'foo'
myRE = .RegularExpression~new()
myRE~parse(rx1, MINIMAL... |
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
... | #COBOL | COBOL | FUNCTION REVERSE('QWERTY') |
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.
| #Tcl | Tcl | proc repeat {command count} {
for {set i 0} {$i < $count} {incr i} {
uplevel 1 $command
}
}
proc example {} {puts "This is an example"}
repeat example 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.
| #uBasic.2F4tH | uBasic/4tH | Proc _Repeat (_HelloWorld, 5) : End
_Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return
_HelloWorld Print "Hello world!" : Return |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Pop11 | Pop11 | sys_file_move('inputs.txt', 'output.txt');
sys_file_move('docs', 'mydocs');
sys_file_move('/inputs.txt', '/output.txt');
sys_file_move(/'docs', '/mydocs'); |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #PowerShell | PowerShell | Rename-Item input.txt output.txt
# The Rename-item has the alias ren
ren input.txt output.txt |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Oforth | Oforth | : revWords(s)
s words reverse unwords ;
: reverseWords
"---------- Ice and Fire ------------" revWords println
" " revWords println
"fire, in end will world the say Some" revWords println
"ice. in say Some " revWords println
"desire of tasted I'... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Pascal | Pascal | program Reverse_words(Output);
{$H+}
const
nl = chr(10); // Linefeed
sp = chr(32); // Space
TXT =
'---------- Ice and Fire -----------'+nl+
nl+
'fire, in end will world the say Some'+nl+
'ice. in say Some'+nl+
'desire of tasted I''ve what From'+nl+
'fire. favor who those with hold I'+nl+
nl+
'..... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Smalltalk | Smalltalk | "1. simple approach"
rot13 := [ :string |
string collect: [ :each | | index |
index := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
indexOf: each ifAbsent: [ 0 ]. "Smalltalk uses 1-based indexing"
index isZero
ifTrue: [ each ]
ifFalse: [ 'nopqrstuvwxyzabcdefghijklmNOP... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Shen | Shen |
(define encodeGlyphs
ACC 0 _ -> ACC
ACC N [Glyph Value | Rest] -> (encodeGlyphs (@s ACC Glyph) (- N Value) [Glyph Value | Rest]) where (>= N Value)
ACC N [Glyph Value | Rest] -> (encodeGlyphs ACC N Rest)
)
(define encodeRoman
N -> (encodeGlyphs "" N ["M" 1000 "CM" 900 "D" 500 "CD" 400 "C" 100 "XC" 90 "L" 50... |
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 decima... | #Yabasic | Yabasic | romans$ = "MDCLXVI"
decmls$ = "1000,500,100,50,10,5,1"
sub romanDec(s$)
local i, n, prev, res, decmls$(1)
n = token(decmls$, decmls$(), ",")
for i = len(s$) to 1 step -1
n = val(decmls$(instr(romans$, mid$(s$, i, 1))))
if n < prev n = 0 - n
res = res + n
prev = n
ne... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Gambas | Gambas | Public Sub Main()
Print String$(5, "ha")
End |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PL.2FI | PL/I | define structure 1 h,
2 a (10) float;
declare i fixed binary;
sub: procedure (a, b) returns (type(h));
declare (a, b) float;
declare p type (h);
do i = 1 to 10;
p.a(i) = i;
end;
return (p);
end sub; |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Plain_English | Plain English | To run:
Start up.
Compute a product and a quotient given 15 and 3.
Write "The product is " then the product on the console.
Write "The quotient is " then the quotient on the console.
Wait for the escape key.
Shut down.
A product is a number.
To compute a product and a quotient given a number and another number:
Put... |
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
... | #Euphoria | Euphoria | include sort.e
function uniq(sequence s)
sequence out
s = sort(s)
out = s[1..1]
for i = 2 to length(s) do
if not equal(s[i],out[$]) then
out = append(out, s[i])
end if
end for
return out
end function
constant s = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}
? s
? uniq(s) |
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... | #PL.2FI | PL/I | recaman: procedure options(main);
declare A(0:30) fixed;
/* is X in the first N terms of the Recaman sequence? */
find: procedure(x, n) returns(bit);
declare (x, n, i) fixed;
do i=0 to n-1;
if A(i)=x then return('1'b);
end;
return('0'b);
end find;
/* g... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #J | J | NB.*pivot v Pivot at row, column
NB. form: (row,col) pivot M
pivot=: dyad define
'r c'=. x
col=. c{"1 y
y - (col - r = i.#y) */ (r{y) % r{col
)
NB.*gauss_jordan v Gauss-Jordan elimination (full pivoting)
NB. y is: matrix
NB. x is: optional minimum tolerance, default 1e_15.
NB. If a column below the current pi... |
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 ... | #Factor | Factor | e ! e
pi ! π
sqrt ! square root
log ! natural logarithm
exp ! exponentiation
abs ! absolute value
floor ! greatest whole number smaller than or equal
ceiling ! smallest whole number greater than or equal
truncate ! remove the fractional part (i.e. round towards 0)
r... |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #Fantom | Fantom |
Float.e
Float.pi
9f.sqrt
9f.log // natural logarithm
9f.log10 // logarithm to base 10
9f.exp // exponentiation
(-3f).abs // absolute value, note bracket
3.2f.floor // nearest Int smaller than this number
3.2f.ceil // nearest Int bigger than this number
3.2f.round // nearest Int
3f.pow(2f) // power... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Nim | Nim | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
# Read the whole file, split into lines but keep the ends of line.
var lines = filename.readFile().splitLines(keepEol = true)
# Remove final empty string if any.
if lines[^1].len == 0: lines.setLen(lines.len - 1)
#... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #OCaml | OCaml | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let... |
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... | #Go | Go | import "io/ioutil"
data, err := ioutil.ReadFile(filename)
sv := string(data) |
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... | #Groovy | Groovy | def fileContent = new File("c:\\file.txt").text |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #PicoLisp | PicoLisp | (de repString (Str)
(let Lst (chop Str)
(for (N (/ (length Lst) 2) (gt0 N) (dec N))
(T
(use (Lst X)
(let H (cut N 'Lst)
(loop
(setq X (cut N 'Lst))
(NIL (head X H))
(NIL Lst T) ) ) )
... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #PL.2FI | PL/I | rep: procedure options (main); /* 5 May 2015 */
declare s bit (10) varying;
declare (i, k) fixed binary;
main_loop:
do s = '1001110011'b, '1110111011'b, '0010010010'b, '1010101010'b,
'1111111111'b, '0100101101'b, '0100100'b, '101'b, '11'b, '00'b, '1'b;
k = length(s);
do i = k/2 to 1 by ... |
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
| #Oxygene | Oxygene |
// Match and Replace part of a string using a Regular Expression
//
// Nigel Galloway - April 15th., 2012
//
namespace re;
interface
type
re = class
public
class method Main;
end;
implementation
class method re.Main;
const
myString = 'I think that I am Nigel';
var
r: System.Text.RegularExpress... |
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
... | #CoffeeScript | CoffeeScript | "qwerty".split("").reverse().join "" |
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.
| #Ursa | Ursa | def repeat (function f, int n)
for (set n n) (> n 0) (dec n)
f
end for
end repeat
def procedure ()
out "Hello! " console
end procedure
# outputs "Hello! " 5 times
repeat procedure 5 |
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.
| #VBA | VBA | Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Next i
End Sub
Private Sub Hello()
Debug.Print "Hello"
End Sub
Public Sub main()
Repeat "Hello", 5
End Sub |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Processing | Processing | void setup(){
boolean sketchfile = rename(sketchPath("input.txt"), sketchPath("output.txt"));
boolean sketchfold = rename(sketchPath("docs"), sketchPath("mydocs"));
// sketches will seldom have write permission to root files/folders
boolean rootfile = rename("input.txt", "output.txt");
boolean rootfold = rena... |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #ProDOS | ProDOS | rename input.txt to output.txt
rename docs to mydocs |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Perl | Perl | print join(" ", reverse split), "\n" for <DATA>;
__DATA__
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ---------------------... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Phix | Phix | with javascript_semantics
constant test="""
---------- 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 -----------------------
"""
sequence lines = split(test,'\n')
for i=1 ... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #SNOBOL4 | SNOBOL4 | * # Function using replace( )
define('rot13(s)u1,u2,l1,l2') :(rot13_end)
rot13 &ucase len(13) . u1 rem . u2
&lcase len(13) . l1 rem . l2
rot13 = replace(s,&ucase &lcase,u2 u1 l2 l1) :(return)
rot13_end
* # Function using pattern
define('rot13s(s)c')
alfa = &ucase ... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Sidef | Sidef | func arabic2roman(num, roman='') {
static lookup = [
: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
];
lookup.each { |pair|
while (num >= pair.second) {
roman += pair.first;
nu... |
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 decima... | #zkl | zkl | var romans = L(
L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100),
L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9),
L("V", 5), L("IV", 4), L("I", 1));
fcn toArabic(romanNumber){ // romanNumber needs to be upper case
if (not RegExp("^[CDILMVX]+$").matches(roman... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #GAP | GAP | Concatenation(ListWithIdenticalEntries(10, "BOB "));
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB " |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Glee | Glee | '*' %% 5 |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PowerShell | PowerShell |
function multiple-value ($a, $b) {
[pscustomobject]@{
a = $a
b = $b
}
}
$m = multiple-value "value" 1
$m.a
$m.b
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PureBasic | PureBasic | ;An array, map, or list can be used as a parameter to a procedure and in the
;process contain values to be returned as well.
Procedure example_1(x, y, Array r(1)) ;array r() will contain the return values
Dim r(2) ;clear and resize the array
r(0) = x + y ;return these values in the array
r(1) = x - y
r(2) = x... |
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
... | #F.23 | F# |
set [|1;2;3;2;3;4|]
|
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... | #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT$CH: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PRINT$CH;
PRINT$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT$STR;
/* PRINT NUMBER */
PRINT$NUM: PROCEDURE(N);
DECLARE ... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #Java | Java | import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
/* Matrix class
* Handles elementary Matrix operations:
* Interchange
* Multiply and Add
* Scale
* Reduced Row Echelon Form
*/
class Matrix {
LinkedL... |
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 ... | #Forth | Forth | 1e fexp fconstant e
0e facos 2e f* fconstant pi \ predefined in gforth
fsqrt ( f -- f )
fln ( f -- f ) \ flog for base 10
fexp ( f -- f )
fabs ( f -- f )
floor ( f -- f ) \ round towards -inf
: ceil ( f -- f ) fnegate floor fnegate ; \ not standard, though fround is available
f** ( f e -- f^e ) |
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 ... | #Fortran | Fortran | e ! Not available. Can be calculated EXP(1.0)
pi ! Not available. Can be calculated 4.0*ATAN(1.0)
SQRT(x) ! square root
LOG(x) ! natural logarithm
LOG10(x) ! logarithm to base 10
EXP(x) ! exponential
ABS(x) ! absolute value
FLOOR(x) ! floor - Fortran 90 or later only
CEILING... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Oforth | Oforth | : removeLines(filename, startLine, numLines)
| line b endLine |
ListBuffer new ->b
startLine numLines + 1 - ->endLine
0 File new(filename) forEach: line [
1+ dup between(startLine, endLine) ifFalse: [ b add(line) continue ]
numLines 1- ->numLines
]
drop numLines 0 == ifFalse: [ "Error : ... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Pascal | Pascal | program RemLines;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnd... |
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... | #GUISS | GUISS | Start,Programs,Accessories,Notepad,Menu:File,Open,Doubleclick:Icon:Notes.TXT,Button:OK |
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... | #Haskell | Haskell | do text <- readFile filepath
-- do stuff with text |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #PL.2FM | PL/M | 100H:
DECLARE MAX$REP LITERALLY '32';
DECLARE FALSE LITERALLY '0';
DECLARE TRUE LITERALLY '1';
DECLARE CR LITERALLY '0DH';
DECLARE LF LITERALLY '0AH';
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* PRINTS A BYTE AS A ... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Prolog | Prolog | :- use_module(library(func)).
%% Implementation logic:
test_for_repstring(String, (String, Result, Reps)) :-
( setof(Rep, repstring(String, Rep), Reps)
-> Result = 'no repstring'
; Result = 'repstrings', Reps = []
).
repstring(Codes, R) :-
RepLength = between(1) of (_//2) of length $ Codes,
... |
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
| #Oz | Oz | declare
[Regex] = {Module.link ['x-oz://contrib/regex']}
String = "This is a string"
in
if {Regex.search "string$" String} \= false then
{System.showInfo "Ends with string."}
end
{System.showInfo {Regex.replace String " a " fun {$ _ _} " another " 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
| #Pascal | Pascal |
// Match and Replace part of a string using a Regular Expression
//
// Nigel Galloway - April 11th., 2012
//
program RegularExpr;
uses
RegExpr;
const
myString = 'I think that I am Nigel';
myMatch = '(I am)|(you are)';
var
r : TRegExpr;
myResult : String;
begin
r := TRegExpr.Create;
r.Expression :=... |
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
... | #ColdFusion | ColdFusion | <cfset myString = "asdf" />
<cfset myString = reverse( myString ) /> |
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.
| #Verilog | Verilog | module main;
initial begin
repeat(5) begin
$display("Inside loop");
end
$display("Loop Ended");
end
endmodule |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Repeat(count As Integer, fn As Action(Of Integer))
If IsNothing(fn) Then
Throw New ArgumentNullException("fn")
End If
For i = 1 To count
fn.Invoke(i)
Next
End Sub
Sub Main()
Repeat(3, Sub(x) Console.WriteLine("Example {... |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #PureBasic | PureBasic | RenameFile("input.txt", "output.txt")
RenameFile("docs\", "mydocs\")
RenameFile("/input.txt","/output.txt")
RenameFile("/docs\","/mydocs\") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.