task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Python | Python | import os
os.rename("input.txt", "output.txt")
os.rename("docs", "mydocs")
os.rename(os.sep + "input.txt", os.sep + "output.txt")
os.rename(os.sep + "docs", os.sep + "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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
"---------- 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 -----------------------"
stklen tolist
len for var i
i get spli... |
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... | #PHP | PHP |
<?php
function strInv ($string) {
$str_inv = '' ;
for ($i=0,$s=count($string);$i<$s;$i++){
$str_inv .= implode(' ',array_reverse(explode(' ',$string[$i])));
$str_inv .= '<br>';
}
return $str_inv;
}
$string[] = "---------- Ice and Fire ------------";
$string[] = "";
$string[] = "fire... |
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... | #SQL | SQL |
SELECT translate(
'The quick brown fox jumps over the lazy dog.',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
)
FROM dual;
|
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... | #Simula | Simula | BEGIN
TEXT PROCEDURE TOROMAN(N); INTEGER N;
BEGIN
PROCEDURE P(WEIGHT,LIT); INTEGER WEIGHT; TEXT LIT;
BEGIN
WHILE N >= WEIGHT DO
BEGIN
T :- T & LIT;
N := N - WEIGHT;
END WHILE;
END P;
TEXT T; T :- NOTEXT;
... |
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... | #Zoea | Zoea |
program: roman_decimal
input: 'XIII'
output: 13
|
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... | #Go | Go | fmt.Println(strings.Repeat("ha", 5)) // ==> "hahahahaha" |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Python | Python | def addsub(x, y):
return x + y, x - y |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Quackery | Quackery | Welcome to Quackery.
Enter "leave" to leave the shell.
/O> [ 2dup + unrot * ] is +* ( a b --> a+b a*b )
... 12 23 +*
...
Stack: 35 276
/O> |
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
... | #Factor | Factor | USING: sets ;
V{ 1 2 1 3 2 4 5 } members .
V{ 1 2 3 4 5 } |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #PureBasic | PureBasic | #MAX=500000
Dim a.i(#MAX)
Dim b.b(1)
Dim c.b(1000)
FillMemory(@c(),1000,1,#PB_Byte)
If OpenConsole() : Else : End 1 : EndIf
For n_Count=0 To #MAX
If n_Count=0
a(n_Count)=0
ElseIf a(n_Count-1)-n_Count>0 And b(a(n_Count-1)-n_Count)=0
a(n_Count)=a(n_Count-1)-n_Count
Else
a(n_Count)=a(n_Count-1)+... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #JavaScript | JavaScript | // modifies the matrix in-place
Matrix.prototype.toReducedRowEchelonForm = function() {
var lead = 0;
for (var r = 0; r < this.rows(); r++) {
if (this.columns() <= lead) {
return;
}
var i = r;
while (this.mtx[i][lead] == 0) {
i++;
if (this.rows... |
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 ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "crt/math.bi"
Print M_E '' constant "e" from C runtime library
Print M_PI '' constant "pi" from C runtime library
Print Sqr(2) '' square root function built into FB
Print Log(M_E) '' log to base "e" built into FB
Print log10(10) '' log to base 10 from C runti... |
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... | #Perl | Perl | #!/usr/bin/perl -n -s -i
print unless $. >= $from && $. <= $to; |
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... | #Phix | Phix | without js -- (file i/o)
procedure remove_lines(string filename, integer start, n)
integer fn = open(filename,'r')
if fn!=-1 then
puts(1,"cannot open file!\n")
else
object lines = get_text(fn,GT_LF_STRIPPED)
close(fn)
if n<1 or start<1 or length(lines)<start+n-1 then
... |
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... | #Icon_and_Unicon | Icon and Unicon | every (fs := "") ||:= |reads(1000000) |
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... | #Inform_7 | Inform 7 | Home is a room.
The File of Testing is called "test".
When play begins:
say "[text of the File of Testing]";
end the story. |
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... | #PureBasic | PureBasic | a$="1001110011"+#CRLF$+"1110111011"+#CRLF$+"0010010010"+#CRLF$+"1010101010"+#CRLF$+"1111111111"+#CRLF$+
"0100101101"+#CRLF$+"0100100" +#CRLF$+"101" +#CRLF$+"11" +#CRLF$+"00" +#CRLF$+
"1" +#CRLF$
OpenConsole()
Procedure isRepStr(s1$,s2$)
If Int(Len(s1$)/Len(s2$))>=2 : ProcedureR... |
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
| #Perl | Perl | $string = "I am a string";
if ($string =~ /string$/) {
print "Ends with 'string'\n";
}
if ($string !~ /^You/) {
print "Does not start with 'You'\n";
} |
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
... | #Common_Lisp | Common Lisp | (reverse my-string) |
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.
| #Vlang | Vlang | fn repeat(n int, f fn()) {
for _ in 0.. n {
f()
}
}
fn func() {
println("Example")
}
fn main() {
repeat(4, func)
} |
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.
| #Wren | Wren | var f = Fn.new { |g, n|
for (i in 1..n) g.call(n)
}
var g = Fn.new { |k|
for (i in 1..k) System.write("%(i) ")
System.print()
}
f.call(g, 5) |
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... | #Quackery | Quackery | $ "
import os
if os.path.exists('input.txt'):
os.rename('input.txt', 'output.txt')
" python
$ "
import os
if os.path.exists('docs'):
os.rename('docs', 'mydocs')
" python
$ "
import os
if os.path.exists('/input.txt'):
os.rename('/input.txt', '/output.txt')
" python
$ "
import os
if os.path.exis... |
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... | #Racket | Racket |
#lang racket
(rename-file-or-directory "input.txt" "output.txt")
(rename-file-or-directory "docs" "mydocs")
;; find the filesystem roots, and pick the first one
(define root (first (filesystem-root-list)))
(rename-file-or-directory (build-path root "input.txt")
(build-path root "output... |
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... | #PicoLisp | PicoLisp |
(in "FireIce.txt"
(until (eof)
(prinl (glue " " (flip (split (line) " "))))))
|
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... | #Pike | Pike | string story = #"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
foreach(story/"\n", string line)
write("%s\n", reverse(line/" ")*... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Stata | Stata | function rot13(s) {
u = ascii(s)
i = selectindex(u:>64 :& u:<91)
if (length(i)>0) u[i] = mod(u[i]:-52, 26):+65
i = selectindex(u:>96 :& u:<123)
if (length(i)>0) u[i] = mod(u[i]:-84, 26):+97
return(char(u))
}
rot13("Shall Not Perish")
Funyy Abg Crevfu |
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... | #Smalltalk | Smalltalk | 2013 printRomanOn:Stdout naive:false |
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... | #Zoea_Visual | Zoea Visual |
#!/bin/zsh
function parseroman () {
local max=0 sum i j
local -A conv
conv=(I 1 V 5 X 10 L 50 C 100 D 500 M 1000)
for j in ${(Oas::)1}; do
i=conv[$j]
if (( i >= max )); then
(( sum+=i ))
(( max=i ))
else
(( sum-=i ))
fi
done
echo $sum
}
parseroman MCMXC
parseroman MMVII... |
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... | #Groovy | Groovy | println 'ha' * 5 |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #R | R | addsub <- function(x, y) list(add=(x + y), sub=(x - y)) |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Forth | Forth | \ Increments a2 until it no longer points to the same value as a1
\ a3 is the address beyond the data a2 is traversing.
: skip-dups ( a1 a2 a3 -- a1 a2+n )
dup rot ?do
over @ i @ <> if drop i leave then
cell +loop ;
\ Compress an array of cells by removing adjacent duplicates
\ Returns the new count
: u... |
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... | #Python | Python | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None # Set of results so far
self.n = None # n'th term (counting from zero)
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a,... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #Julia | Julia | julia> matrix = [1 2 -1 -4 ; 2 3 -1 -11 ; -2 0 -3 22]
3x4 Int32 Array:
1 2 -1 -4
2 3 -1 -11
-2 0 -3 22
julia> rref(matrix)
3x4 Array{Float64,2}:
1.0 0.0 0.0 -8.0
0.0 1.0 0.0 1.0
0.0 0.0 1.0 -2.0
|
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 ... | #Free_Pascal | Free Pascal |
e
pi, π // Unicode can also be written in ASCII programs as \u03C0
sqrt[x]
ln[x] // Natural log
log[x] // Log to base 10
exp[x], e^x
abs[x]
floor[x] // Except for complex numbers where there's no good interpretation.
ceil[x] // Except for complex numbers where there's no good interpretation.
x^y
|
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #Frink | Frink |
e
pi, π // Unicode can also be written in ASCII programs as \u03C0
sqrt[x]
ln[x] // Natural log
log[x] // Log to base 10
exp[x], e^x
abs[x]
floor[x] // Except for complex numbers where there's no good interpretation.
ceil[x] // Except for complex numbers where there's no good interpretation.
x^y
|
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #Phixmonti | Phixmonti | "aFile.txt" var fileName
100 var startLine
10 var lineCount
0 var lineNum
fileName "r" fopen var in
fileName "_tmp" chain "w" fopen var out
in 0 > out 0 > and if
true
while
in fgets dup
-1 == if
drop
in fclose out fclose
false
else
line... |
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... | #PicoLisp | PicoLisp | (de deleteLines (File Start Cnt)
(let L (in File (make (until (eof) (link (line)))))
(if (> (+ (dec 'Start) Cnt) (length L))
(quit "Not enough lines")
(out File
(mapc prinl (cut Start 'L))
(mapc prinl (nth L (inc Cnt))) ) ) ) ) |
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... | #J | J | require 'files' NB. not needed for J7 & later
var=: freads 'foo.txt' |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException{
String fileContents = readEntireFile("./foo.txt");
}
private static String readEntireFile(String filename) throws IOException {... |
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... | #Python | Python | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr = """\
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
"""
for line i... |
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
| #Phix | Phix | with javascript_semantics
include builtins\regex.e
requires("1.0.2") -- (needs some recent bugfixes to regex.e for p2js)
string s = "I am a string"
printf(1,"\"%s\" %s with string\n",{s,iff(length(regex(`string$`,s))?"ends":"does not end")})
printf(1,"\"%s\" %s with You\n",{s,iff(length(regex(`^You`,s))?"starts":"does ... |
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
... | #Component_Pascal | Component Pascal |
MODULE BbtReverseString;
IMPORT StdLog;
PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR
top,middle,i: INTEGER;
c: CHAR;
rStr: POINTER TO ARRAY OF CHAR;
BEGIN
NEW(rStr,LEN(str$) + 1);
top := LEN(str$) - 1; middle := (top - 1) DIV 2;
FOR i := 0 TO middle DO
rStr[i] := str[top - i];
r... |
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.
| #XBS | XBS | func rep(callback:function,amount:number,*args:array=[]):null{
repeat amount {
callback(*args);
}
}
rep(func(a,b,c){
log(a+b+c);
},3,1,2,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.
| #XLISP | XLISP | (defun repeat (f n)
(f)
(if (> n 1)
(repeat f (- n 1)) ) )
;; an example to test it:
(repeat (lambda () (print '(hello rosetta code))) 5) |
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... | #Raku | Raku | 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... | #Raven | Raven | `mv /path/to/file/oldfile /path/to/file/newfile` shell |
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... | #PL.2FI | PL/I | rev: procedure options (main); /* 5 May 2014 */
declare (s, reverse) character (50) varying;
declare (i, j) fixed binary;
declare in file;
open file (in) title ('/REV-WRD.DAT,type(text),recsize(5> Nil) {
for(j := words->Size() - 1; j > -1; j-=1;) {
IO.Console->Print(words[... |
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... | #PowerShell | PowerShell |
Function Reverse-Words($lines) {
$lines | foreach {
$array = $PSItem.Split(' ')
$array[($array.Count-1)..0] -join ' '
}
}
$lines =
"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who th... |
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... | #Swift | Swift | func rot13char(c: UnicodeScalar) -> UnicodeScalar {
switch c {
case "A"..."M", "a"..."m":
return UnicodeScalar(UInt32(c) + 13)
case "N"..."Z", "n"..."z":
return UnicodeScalar(UInt32(c) - 13)
default:
return c
}
}
func rot13(str: String) -> String {
return String(map(str.unicodeScalars){ c in C... |
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... | #SNOBOL4 | SNOBOL4 |
* ROMAN(N) - Convert integer N to Roman numeral form.
*
* N must be positive and less than 4000.
*
* An asterisk appears in the result if N >= 4000.
*
* The function fails if N is not an integer.
DEFINE('ROMAN(N)UNITS') :(ROMAN_END)
* Get rightmost digit to UNITS and remove it from N.
* Return ... |
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... | #zsh | zsh |
#!/bin/zsh
function parseroman () {
local max=0 sum i j
local -A conv
conv=(I 1 V 5 X 10 L 50 C 100 D 500 M 1000)
for j in ${(Oas::)1}; do
i=conv[$j]
if (( i >= max )); then
(( sum+=i ))
(( max=i ))
else
(( sum-=i ))
fi
done
echo $sum
}
parseroman MCMXC
parseroman MMVII... |
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... | #Harbour | Harbour | ? Replicate( "Ha", 5 ) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Racket | Racket | #lang racket
(values 4 5)
(define (my-values . return-list)
(call/cc
(lambda (return)
(apply return return-list)))) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Raku | Raku | sub addmul($a, $b) {
$a + $b, $a * $b
}
my ($add, $mul) = addmul 3, 7; |
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
... | #Fortran | Fortran |
program remove_dups
implicit none
integer :: example(12) ! The input
integer :: res(size(example)) ! The output
integer :: k ! The number of unique elements
integer :: i, j
example = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5]
k = 1
res(1) = example(1)
outer: do i=2,size(exam... |
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... | #Quackery | Quackery |
[ stack 0 ] is seennumbers ( --> s )
[ bit seennumbers take
| seennumbers put ] is seen ( n --> )
[ dup 0 < iff
[ drop true ] done
bit seennumbers share
& 0 != ] is seen? ( n --> b )
[ 1+ bit 1 -
seennumbers share
ov... |
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... | #R | R |
visited <- vector('logical', 1e8)
terms <- vector('numeric')
in_a_interval <- function(v) {
visited[[v+1]]
}
add_value <- function(v) {
visited[[v+1]] <<- TRUE
terms <<- append(terms, v)
}
add_value(0)
step <- 1
value <- 0
founddup <- FALSE
repeat {
if ((value-step>0) && (!in_a_interval(value-step)))... |
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... | #Kotlin | Kotlin | // version 1.1.51
typealias Matrix = Array<DoubleArray>
/* changes the matrix to RREF 'in place' */
fun Matrix.toReducedRowEchelonForm() {
var lead = 0
val rowCount = this.size
val colCount = this[0].size
for (r in 0 until rowCount) {
if (colCount <= lead) return
var i = r
... |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #FutureBasic | FutureBasic | window 1
text ,,,,, 60// set tab width
print @"exp:", exp(1)
print @"pi:", pi
print @"sqr:", sqr(2)
print @"log:", log(2)
print @"log2:", log2(2)
print @"log10", log10(2)
print @"abs:", abs(-2)
print @"floor:", int(1.534)
print @"ceil:", val( using"###"; 1.534 )
print @"power:", 1.23 ^ 4
HandleEvent... |
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 ... | #Go | Go | package main
import (
"fmt"
"math"
"math/big"
)
func main() {
// e and pi defined as constants.
// In Go, that means they are not of a specific data type and can be used
// as float32 or float64. Println takes the float64 values.
fmt.Println("float64 values:")
fmt.Println("e:", math... |
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... | #PowerBASIC | PowerBASIC | #DIM ALL
FUNCTION PBMAIN () AS LONG
DIM filespec AS STRING, linein AS STRING
DIM linecount AS LONG, L0 AS LONG, ok AS LONG
filespec = DIR$(COMMAND$(1))
WHILE LEN(filespec)
linecount = 0: ok = 0
OPEN filespec FOR INPUT AS 1
OPEN filespec & ".tmp" FOR OUTPUT AS 2
DO UNT... |
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... | #PowerShell | PowerShell |
function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
|
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... | #JavaScript | JavaScript | var fso=new ActiveXObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var s=f.ReadAll();
f.Close();
try{alert(s)}catch(e){WScript.Echo(s)} |
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... | #jq | jq | jq -R -s . input.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 e... | #Quackery | Quackery | [ false swap
dup size 1 > if
[ [] temp put
dup size factors
-1 split drop
witheach
[ 2dup split drop
dip [ over size swap / ]
dup temp replace
swap of over = if
[ drop not
temp share
conclud... |
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... | #Racket | Racket | #lang racket
(define (rep-string str)
(define len (string-length str))
(for/or ([n (in-range 1 len)])
(and (let loop ([from n])
(or (>= from len)
(let ([m (min (- len from) n)])
(and (equal? (substring str from (+ from m))
(substring str... |
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
| #PHP | PHP | $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n"; |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #PicoLisp | PicoLisp | (let (Pat "a[0-9]z" String "a7z")
(use Preg
(native "@" "regcomp" 'I '(Preg (64 B . 64)) Pat 1) # Compile regex
(when (=0 (native "@" "regexec" 'I (cons NIL (64) Preg) String 0 0 0))
(prinl "String \"" String "\" matches regex \"" Pat "\"") ) ) ) |
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
... | #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
# Reverse a string in place
sub StrRev(s: [uint8]): (r: [uint8]) is
r := s;
var e := s;
while [e] != 0 loop
e := @next e;
end loop;
e := @prev e;
while e > s loop
var c := [s];
[s] := [e];
[e] := c;
s := @ne... |
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.
| #Yabasic | Yabasic | sub myFunc ()
print "Sure looks like a function in here..."
end sub
sub rep (func$, times)
for count = 1 to times
execute(func$)
next
end sub
rep("myFunc", 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.
| #Z80_Assembly | Z80 Assembly |
ld b,&05 ;load the decrement value into b
ld hl,myFunc ;load the address of "myFunc" into HL
call repeatProcedure
forever:
jp forever ;trap the program counter here
repeatProcedure: ;input: b = times to repeat, hl = which procedure to repeat
call trampoline
; the "ret" in myFunc will bring you here
djnz repeat... |
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... | #REALbasic | REALbasic | Sub Renamer()
Dim f As FolderItem, r As FolderItem
f = GetFolderItem("input.txt")
'Changing a FolderItem's Name attribute renames the file or directory.
If f.Exists Then f.Name = "output.txt"
'Files and directories are handled almost identically in RB.
f = GetFolderItem("docs")
If f.Exists... |
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... | #REBOL | REBOL | rename %input.txt %output.txt
rename %docs/ %mydocs/
; Unix. Note that there's no path specification used for the
; new name. "Rename" is not "move".
rename %/input.txt %output.txt
rename %/docs/ %mydocs/
; DOS/Windows:
rename %/c/input.txt %output.txt
rename %/c/docs/ %mydocs/
; Because REBOL treats data ac... |
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... | #PureBasic | PureBasic | a$ = "---------- Ice and Fire ------------" +#CRLF$+
" " +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
"ice. in say Some " +#CRLF$+
"desire of tasted I've what From " +#CRLF$+
"fire. favor who those with hold... |
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... | #Tcl | Tcl | proc rot13 line {
string map {
a n b o c p d q e r f s g t h u i v j w k x l y m z
n a o b p c q d r e s f t g u h v i w j x k y l z m
A N B O C P D Q E R F S G T H U I V J W K X L Y M Z
N A O B P C Q D R E S F T G U H V I W J X K Y L Z M
} $line
}
set tx "Hello, World !"
puts "$... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #SPL | SPL | a2r(a)=
r = ""
n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]]
> i, 1..13
> a!<n[i,2]
r += n[i,1]
a -= n[i,2]
<
<
<= r
.
t = [1990,2008,1666]
> i, 1..#.size(t,1)
#.output(t[i]," = ",a2r(t[i]))
< |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Haskell | Haskell | concat $ replicate 5 "ha" |
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... | #HicEst | HicEst | CHARACTER out*20
EDIT(Text=out, Insert="ha", DO=5) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Raven | Raven | define multiReturn use $v
$v each
3 multiReturn |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #ReScript | ReScript | let addsub = (x, y) => {
(x + y, x - y)
}
let (sum, difference) = addsub(33, 12)
Js.log2("33 + 12 = ", sum)
Js.log2("33 - 12 = ", difference) |
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
... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub removeDuplicates(a() As Integer, b() As Integer)
Dim lb As Integer = LBound(a)
Dim ub As Integer = UBound(a)
If ub = -1 Then Return '' empty array
Redim b(lb To ub)
b(lb) = a(lb)
Dim count As Integer = 1
Dim unique As Boolean
For i As Integer = lb + 1 To ub
unique = True
... |
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... | #Raku | Raku | my @recamans = 0, {
state %seen;
state $term;
$term++;
my $this = $^previous - $term;
$this = $previous + $term unless ($this > 0) && !%seen{$this};
%seen{$this} = True;
$this
} … *;
put "First fifteen terms of Recaman's sequence: ", @recamans[^15];
say "First duplicate at term: a[{ @recamans.f... |
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... | #Lua | Lua | function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lea... |
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 ... | #Groovy | Groovy | println ((-22).abs()) |
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 ... | #Haskell | Haskell | exp 1 -- Euler number
pi -- pi
sqrt x -- square root
log x -- natural logarithm
exp x -- exponential
abs x -- absolute value
floor x -- floor
ceiling x -- ceiling
x ** y -- power (e.g. floating-point exponentiation)
x ^ y -- power (e.g. integer exponentiation, nonnegative y only)
x ^^... |
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... | #PureBasic | PureBasic |
; Contents of file 'input.txt' before deletion of lines :
;
; cat
; dog
; giraffe
; lion
; mouse
; pig
; tiger
; zebra
EnableExplicit
#Output$ = "output.txt"; insert path to temporary output file
Procedure RemoveLines(Input$, StartLine, NbLines)
Protected lineCount = 0
Protected endline = StartLine + NbLin... |
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... | #Jsish | Jsish | var contents = File.read("filename") |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Julia | Julia | read("/devel/myfile.txt", String) # read file into a string |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Raku | Raku | for <1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1> {
if /^ (.+) $0+: (.*$) <?{ $0.substr(0,$1.chars) eq $1 }> / {
my $rep = $0.chars;
say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2);
}
else {
say "$_ (no repeat)";
}
} |
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
| #PowerShell | PowerShell | "I am a string" -match '\bstr' # true
"I am a string" -replace 'a\b','no' # I am no 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
| #PureBasic | PureBasic | String$ = "<tag>some text consisting of Roman letters spaces and numbers like 12</tag>"
regex$ = "<([a-z]*)>[a-z,A-Z,0-9, ]*</\1>"
regex_replace$ = "letters[a-z,A-Z,0-9, ]*numbers[a-z,A-Z,0-9, ]*"
If CreateRegularExpression(1, regex$) And CreateRegularExpression(2, regex_replace$)
If MatchRegularExpres... |
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
... | #Crystal | Crystal | # version 0.21.1
strings = ["asdf", "as⃝df̅"]
strings.each do |s|
puts "#{s} -> #{s.reverse}"
end |
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.
| #zkl | zkl | fcn repeat(f,n){ do(n){ f() } }
repeat("ho ".print,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 s... | #REXX | REXX | /*REXX program renames a file & a directory (in current dir & in root).*/
trace off /*suppress error messages, bad RC*/
do 2 /* [↓] perform this code twice. */
'RENAME' "input.txt output.txt" /*rename a particular DOS file. */
'MOVE' "\doc... |
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... | #Ring | Ring |
rename("input.txt", "output.txt")
rename("docs", "mydocs")
rename("/input.txt", "/output.txt")
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); t... | #Python | Python | text = '''\
---------- 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 line in text.split('\n'): print(' '.join(line.split()[::-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... | #TI-83_BASIC | TI-83 BASIC | :"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str0
:".→Str2
:For(N,1,length(Str1
:If inString(Str0,sub(Str1,N,1
:Then
:inString(Str0,sub(Str1,N,1
:Ans+13-26(Ans>13
:Str2+sub(Str0,Ans,1→Str2
:Else
:Str2+sub(Str1,N,1→Str2
:End
:End
:sub(Str2,2,length(Str2)-1→Str1 |
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... | #SQL | SQL |
--
-- This only works under Oracle and has the limitation of 1 to 3999
SQL> SELECT to_char(1666, 'RN') urcoman, to_char(1666, 'rn') lcroman FROM dual;
URCOMAN LCROMAN
--------------- ---------------
MDCLXVI 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 re... | #Icon_and_Unicon | Icon and Unicon | procedure main(args)
write(repl(integer(!args) | 5))
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.