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/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.
| #REXX | REXX | /*REXX program executes a named procedure a specified number of times. */
parse arg pN # . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #= 1 /*assume once if not specified. */
if pN\=='' then call repeats pN, # ... |
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... | #Objective-C | Objective-C | NSFileManager *fm = [NSFileManager defaultManager];
// Pre-OS X 10.5
[fm movePath:@"input.txt" toPath:@"output.txt" handler:nil];
[fm movePath:@"docs" toPath:@"mydocs" handler:nil];
// OS X 10.5+
[fm moveItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];
[fm moveItemAtPath:@"docs" toPath:@"mydocs" error:NULL... |
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... | #MiniScript | MiniScript | lines = ["==========================================",
"| ---------- Ice and Fire ------------ |",
"| |",
"| fire, in end will world the say Some |",
"| ice. in say Some |",
"| desire of tasted I've what From |",
"| fire. 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... | #Scheme | Scheme | (define (rot13 str)
(define (rot13-char c)
(integer->char (+ (char->integer c)
(cond ((and (char>=? c #\a) (char<? c #\n))
13)
((and (char>=? c #\A) (char<? c #\N))
13)
((and (ch... |
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... | #Rust | Rust | struct RomanNumeral {
symbol: &'static str,
value: u32
}
const NUMERALS: [RomanNumeral; 13] = [
RomanNumeral {symbol: "M", value: 1000},
RomanNumeral {symbol: "CM", value: 900},
RomanNumeral {symbol: "D", value: 500},
RomanNumeral {symbol: "CD", value: 400},
RomanNumeral {symbol: "C", v... |
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... | #VBScript | VBScript | ' Roman numerals Encode - Visual Basic - 18/04/2019
Function toRoman(ByVal value)
Dim arabic
Dim roman
Dim i, result
arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
For i = 0 To 12
... |
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... | #Euphoria | Euphoria |
sequence s = ""
for i = 1 to 5 do s &= "ha" end for
puts(1,s)
hahahahaha
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #OCaml | OCaml | let addsub x y =
x + y, x - y |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | }
for item in [ 1 10 1 :hi :hello :hi :hi ]:
@item
!. keys set{ |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
VECTOR VALUES ELEMF = $2HA(,I2,4H) = ,I2*$
DIMENSION A(100)
A(0) = 0
PRINT COMMENT $ FIRST 15 ELEMENTS$
PRINT FORMAT ELEMF,0,0
THROUGH EL, FOR I=1, 1, I.GE.15
EL PRINT FORMAT ELEMF,I,NEXT.(I)
... |
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... | #Fortran | Fortran | module Rref
implicit none
contains
subroutine to_rref(matrix)
real, dimension(:,:), intent(inout) :: matrix
integer :: pivot, norow, nocolumn
integer :: r, i
real, dimension(:), allocatable :: trow
pivot = 1
norow = size(matrix, 1)
nocolumn = size(matrix, 2)
allocate(trow(nocol... |
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 ... | #Crystal | Crystal | x = 3.25
y = 4
puts x.abs # absolute value
puts x.floor # floor
puts x.ceil # ceiling
puts x ** y # power
puts
include Math # without including
puts E # puts Math::E -- exponential constant
puts PI # puts Math::PI -- Archimedes circle constant
puts TAU ... |
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... | #Java | Java |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
//Enter name of the file here
String filename="foobar.txt";
//Enter starting line here
int startline=1;
//Enter number of lines he... |
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... | #F.23 | F# | // read entire file into variable using default system encoding or with specified encoding
open System.IO
let data = File.ReadAllText(filename)
let utf8 = File.ReadAllText(filename, System.Text.Encoding.UTF8) |
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... | #Factor | Factor | USING: io.encodings.ascii io.encodings.binary io.files ;
! to read entire file as binary
"foo.txt" binary file-contents
! to read entire file as lines of text
"foo.txt" ascii file-lines |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
/* REXX ***************************************************************
* 11.05.2013 Walter Pachl
**********************************************************************/
runSample(arg)
return
/**
* Test for rep-strings
* @param s_str a s... |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #MIRC_Scripting_Language | MIRC Scripting Language | alias regular_expressions {
var %string = This is a string
var %re = string$
if ($regex(%string,%re) > 0) {
echo -a Ends with string.
}
%re = \ba\b
if ($regsub(%string,%re,another,%string) > 0) {
echo -a Result 1: %string
}
%re = \b(another)\b
echo -a Result 2: $regsubex(%string,%re,yet \1)
} |
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
... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>Write $Reverse("Hello, World")
dlroW ,olleH |
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.
| #Ring | Ring |
Func Main
times(5,:test)
Func Test
see "Message from the test function!" + nl
Func Times nCount, F
for x = 1 to nCount
Call F()
next
|
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.
| #Ruby | Ruby | 4.times{ puts "Example" } # idiomatic way
def repeat(proc,num)
num.times{ proc.call }
end
repeat(->{ puts "Example" }, 4) |
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... | #OCaml | OCaml |
let () =
Sys.rename "input.txt" "output.txt";
Sys.rename "docs" "mydocs";
Sys.rename "/input.txt" "/output.txt";
Sys.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... | #Octave | Octave |
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... | #Modula-2 | Modula-2 |
MODULE ReverseWords;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM Strings IMPORT
Assign, Concat, Append;
CONST
NL = CHR(10);
Sp = ' ';
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 ... |
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... | #sed | sed | y/abcdefghijklmnopqrstuvwxyz/nopqrstuvwxyzabcdefghijklm/
y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/NOPQRSTUVWXYZABCDEFGHIJKLM/ |
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... | #Scala | Scala | val romanDigits = Map(
1 -> "I", 5 -> "V",
10 -> "X", 50 -> "L",
100 -> "C", 500 -> "D",
1000 -> "M",
4 -> "IV", 9 -> "IX",
40 -> "XL", 90 -> "XC",
400 -> "CD", 900 -> "CM")
val romanDigitsKeys = romanDigits.keysIterator.toList sortBy (x => -x)
def toRoman(n: Int): String = romanDigitsKeys find (_ >... |
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... | #Vedit_macro_language | Vedit macro language | // Main program for testing the function
//
do {
Get_Input(10, "Enter a roman numeral: ", NOCR+STATLINE)
Call("Roman_to_Arabic")
Reg_Type(10) Message(" = ") Num_Type(#1)
} while(#1)
Return
// Convert Roman numeral into numeric value
// in: @10 = Roman numeral
// out: #1 = numeric value
//
:Roman_to_Ar... |
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... | #Explore | Explore | > String.replicate 5 "ha";;
val it : string = "hahahahaha" |
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... | #F.23 | F# | > String.replicate 5 "ha";;
val it : string = "hahahahaha" |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Oforth | Oforth | import: date
: returnFourValues 12 13 14 15 ;
: returnOneObject [ 12, 13, 14, 15, [16, 17 ], Date now, 1.2, "abcd" ] ;
"Showing four values returned on the parameter stack:" println
returnFourValues .s clr
"\nShowing one object containing four values returned on the parameter stack:" println
returnOneObject .s c... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #ooRexx | ooRexx |
r = addsub(3, 4)
say r[1] r[2]
::routine addsub
use arg x, y
return .array~of(x + y, x - y)
|
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #E | E | [1,2,3,2,3,4].asSet().getElements() |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[f]
f[s_List] := Block[{a = s[[-1]], len = Length@s},
Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70]
g = Nest[f, {0}, 70];
Take[g, 15]
p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]]
p = Flatten[Position[g, #]] & /@ p;
TakeSmallestBy[p, Last, 1][[1]] |
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... | #Microsoft_Small_Basic | Microsoft Small Basic | ' Recaman's sequence - smallbasic - 05/08/2015
nn=15
TextWindow.WriteLine("Recaman's sequence for the first " + nn + " numbers:")
recaman()
TextWindow.WriteLine(Text.GetSubTextToEnd(recaman,2))
nn="firstdup"
recaman()
TextWindow.WriteLine("The first duplicated term is a["+n+"]="+a[n])
Sub ... |
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... | #FreeBASIC | FreeBASIC | #include once "matmult.bas"
sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
dim as integer k
for k = 0 to ubound(M.m, 2)
swap M.m(j, k), M.m(i, k)
next k
end sub
function rowech(byval M as Matrix) as Matrix
dim as uinteger lead = 0, rowCount = 1+ubound(M.m, 1), colCount = 1+ub... |
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 ... | #D | D | import std.math ; // need to import this module
E // Euler's number
PI // pi constant
sqrt(x) // square root
log(x) // natural logarithm
log10(x) // logarithm base 10
log2(x) // logarithm base 2
exp(x) // exponential
abs(x) // absolute value (= magnitude for complex)
floor(x) // floor
ceil(x) // c... |
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 ... | #Delphi | Delphi | Pi; // π (Pi)
LogN(BASE, x) // log of x for a specified base
Log2(x) // log of x for base 2
Log10(x) // log of x for base 10
Floor(x); // floor
Ceil(x); // ceiling
Power(x, y); // power |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #jq | jq | jq -s -R -r --arg start START --arg number NUMBER -f remove.jq INFILE |
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... | #Julia | Julia | #!/usr/bin/env julia
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end... |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Fantom | Fantom |
class ReadString
{
public static Void main (Str[] args)
{
Str contents := File(args[0].toUri).readAllStr
echo ("contents: $contents")
}
}
|
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Forth | Forth | s" foo.txt" slurp-file ( str len ) |
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... | #NGS | NGS | tests = [
'1001110011'
'1110111011'
'0010010010'
'1010101010'
'1111111111'
'0100101101'
'0100100'
'101'
'11'
'00'
'1'
]
F is_repeated(s:Str) (s.len()/2..0).first(F(x) s.starts_with(s[x..null]))
{
tests.each(F(test) {
local r = is_repeated(test)
echo("${test} ${if r "has repetition of length ${r} (i.... |
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... | #Nim | Nim | import strutils
proc isRepeated(text: string): int =
for x in countdown(text.len div 2, 0):
if text.startsWith(text[x..text.high]): return x
const matchstr = """1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1"""
for line in matchstr.split():
let ln = isRepeated(line)
... |
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
| #MUMPS | MUMPS | REGEXP
NEW HI,W,PATTERN,BOOLEAN
SET HI="Hello, world!",W="world"
SET PATTERN=".E1"""_W_""".E"
SET BOOLEAN=HI?@PATTERN
WRITE "Source string - '"_HI_"'",!
WRITE "Partial string - '"_W_"'",!
WRITE "Pattern string created is - '"_PATTERN_"'",!
WRITE "Match? ",$SELECT(BOOLEAN:"YES",'BOOLEAN:"No"),!
;
SET BOOLEAN=$... |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.regex.
st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman'
rx1 = 'f.e.*?'
sbx = 'foo'
rx1ef = '(?i)'rx1 -- use embedded flag expression == Pattern.CASE_INSENSITIVE
-- using String's matches & replaceAll
mcm ... |
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
... | #Ceylon | Ceylon |
shared void run() {
while(true) {
process.write("> ");
String? text = process.readLine();
if (is String text) {
print(text.reversed);
}
else {
break;
}
}
}
|
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.
| #Rust | Rust | fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
} |
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.
| #Scala | Scala | def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)
repeat(3) { 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... | #OpenEdge.2FProgress | OpenEdge/Progress | OS-RENAME "input.txt" "output.txt".
OS-RENAME "docs" "mydocs".
OS-RENAME "/input.txt" "/output.txt".
OS-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... | #PARI.2FGP | PARI/GP | system("mv input.txt output.txt");
system("mv /input.txt /output.txt");
system("mv docs mydocs");
system("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... | #Nanoquery | Nanoquery | def reverse_words(string)
tokens = split(string, " ")
if len(tokens) = 0
return ""
end
ret_str = ""
for i in range(len(tokens) - 1, 0)
ret_str += tokens[i] + " "
end
return ret_str.substring(0, len(ret_str) - 1)
end
data = "----... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var char: ch is ' ';
begin
ch := getc(IN);
while not eof(IN) do
if (ch >= 'a' and ch <= 'm') or (ch >= 'A' and ch <= 'M') then
ch := chr(ord(ch) + 13);
elsif (ch >= 'n' and ch <= 'z') or (ch >= 'N' and ch <= 'Z') then
... |
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... | #Scheme | Scheme | (define (to-roman n)
(format "~@r" n)) |
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... | #Wren | Wren | import "/fmt" for Fmt
var decode = Fn.new { |r|
if (r == "") return 0
var n = 0
var last = "0"
for (c in r) {
var k
if (c == "I") {
k = 1
} else if (c == "V") {
k = (last == "I") ? 3 : 5
} else if (c == "X") {
k = (last == "I") ? 8 : ... |
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... | #Factor | Factor | : repeat-string ( str n -- str' ) swap <repetition> concat ;
"ha" 5 repeat-string print |
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... | #Forth | Forth | : place-n { src len dest n -- }
0 dest c!
n 0 ?do src len dest +place loop ;
s" ha" pad 5 place-n
pad count type \ hahahahaha |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #OxygenBasic | OxygenBasic |
'============
class vector4
'============
float w,x,y,z
method values(float fw,fx,fy,fz)
this <= fw, fx, fy, fz
end method
method values(vector4 *v)
this <= v.w, v.x, v.y, v.z
end method
method values() as vector4
return this
end method
method ScaledValues(float fw,fx,fy,fz) as vector4
static vector4 v
v ... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #PARI.2FGP | PARI/GP | foo(x)={
[x^2, x^3]
}; |
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
... | #ECL | ECL |
inNumbers := DATASET([{1},{2},{3},{4},{1},{1},{7},{8},{9},{9},{0},{0},{3},{3},{3},{3},{3}], {INTEGER Field1});
DEDUP(SORT(inNumbers,Field1));
|
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... | #Nim | Nim | import sequtils, sets, strutils
iterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] =
var a = 0
yield (0, a, false)
var known = [0].toHashSet
for n in 1..<num:
var next = a - n
if next <= 0 or next in known:
next = a + n
a = next
yield (n, a, a in known)
... |
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... | #Objeck | Objeck | use Collection.Generic;
class RecamanSequence {
function : Main(args : String[]) ~ Nil {
GenerateSequence();
}
function : native : GenerateSequence() ~ Nil {
a := Vector->New()<IntHolder>;
a->AddBack(0);
used := Set->New()<IntHolder>;
used->Insert(0);
used1000 := Set->New()<IntHold... |
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... | #Go | Go | package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
... |
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 ... | #DWScript | DWScript | ? 1.0.exp()
# value: 2.7182818284590455
? 0.0.acos() * 2
# value: 3.141592653589793
? 2.0.sqrt()
# value: 1.4142135623730951
? 2.0.log()
# value: 0.6931471805599453
? 5.0.exp()
# value: 148.4131591025766
? (-5).abs()
# value: 5
? 1.2.floor()
# value: 1
? 1.2.ceil()
# value: 2
? 10 ** 6
# value: 1000000 |
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 ... | #E | E | ? 1.0.exp()
# value: 2.7182818284590455
? 0.0.acos() * 2
# value: 3.141592653589793
? 2.0.sqrt()
# value: 1.4142135623730951
? 2.0.log()
# value: 0.6931471805599453
? 5.0.exp()
# value: 148.4131591025766
? (-5).abs()
# value: 5
? 1.2.floor()
# value: 1
? 1.2.ceil()
# value: 2
? 10 ** 6
# value: 1000000 |
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... | #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()... |
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... | #Fortran | Fortran | program read_file
implicit none
integer :: n
character(:), allocatable :: s
open(unit=10, file="read_file.f90", action="read", &
form="unformatted", access="stream")
inquire(unit=10, size=n)
allocate(character(n) :: s)
read(10) s
close(10)
print "(A)", s
end program |
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... | #Objeck | Objeck | class RepString {
function : Main(args : String[]) ~ Nil {
strings := ["1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1"];
each(i : strings) {
string := strings[i];
repstring := RepString(string);
if(repstring->Size() > 0) {
... |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #NewLISP | NewLISP | (regex "[bB]+" "AbBBbABbBAAAA") -> ("bBBb" 1 4) |
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
| #Nim | Nim | import re
var s = "This is a string"
if s.find(re"string$") > -1:
echo "Ends with string."
s = s.replace(re"\ a\ ", " another ")
echo s |
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
... | #Clipper | Clipper | FUNCTION Reverse(sIn)
LOCAL sOut := "", i
FOR i := Len(sIn) TO 1 STEP -1
sOut += Substr(sIn, i, 1)
NEXT
RETURN sOut |
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.
| #Scheme | Scheme |
(import (scheme base)
(scheme write))
(define (repeat proc n)
(do ((i 0 (+ 1 i))
(res '() (cons (proc) res)))
((= i n) res)))
;; example returning an unspecified value
(display (repeat (lambda () (display "hi\n")) 4)) (newline)
;; example returning a number
(display (repeat (lambda () (+ 1 ... |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: myRepeat (in integer: times, in proc: aProcedure) is func
local
var integer: n is 0;
begin
for n range 1 to times do
aProcedure;
end for;
end func;
const proc: main is func
begin
myRepeat(3, writeln("Hello!"));
end func; |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Pascal | Pascal | var
f : file ; // Untyped file
begin
// as current directory
AssignFile(f,'input.doc');
Rename(f,'output.doc');
// as root directory
AssignFile(f,'\input.doc');
Rename(f,'\output.doc');
// rename a directory
AssignFile(f,'docs');
Rename(f,'mydocs');
//rename a directory off the roo... |
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... | #Perl | Perl | use File::Copy qw(move);
use File::Spec::Functions qw(catfile rootdir);
# here
move 'input.txt', 'output.txt';
move 'docs', 'mydocs';
# root dir
move (catfile rootdir, 'input.txt'), (catfile rootdir, 'output.txt');
move (catfile rootdir, 'docs'), (catfile rootdir, '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... | #Nial | Nial |
# Define a function to convert a list of strings to a single string.
join is rest link (' ' eachboth link)
iterate (write join reverse (' ' string_split)) \
\
\
'------------ Eldorado ----------' \
'' \
'... here omitted lines ...' \
'' \
'Mountains the "Over' \
'Moon, the Of' \
'Shadow, the of Va... |
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... | #Nim | Nim | import strutils
let 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 -----------------------"""
proc reversed*[T](a: openArray[T], first, last: int):... |
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... | #Sidef | Sidef | # Returns a copy of 's' with rot13 encoding.
func rot13(s) {
s.tr('A-Za-z', 'N-ZA-Mn-za-m');
}
# Perform rot13 on standard input.
STDIN.each { |line| print rot13(line) } |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "stdio.s7i";
include "wrinum.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 3999 do
writeln(str(ROMAN, number));
end for;
end func; |
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... | #XLISP | XLISP | (defun decode (r)
(define roman '((#\m 1000) (#\d 500) (#\c 100) (#\l 50) (#\x 10) (#\v 5) (#\i 1)))
(defun to-arabic (rn rs a)
(cond
((null rn) a)
((eqv? (car rn) (caar rs)) (to-arabic (cdr rn) roman (if (and (not (eqv? (car rn) (cadr rn))) (< (cadar rs) (to-arabic (cdr rn) roma... |
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... | #Fortran | Fortran | program test_repeat
write (*, '(a)') repeat ('ha', 5)
end program test_repeat |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Perl | Perl | sub foo {
my ($a, $b) = @_;
return $a + $b, $a * $b;
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Phix | Phix | function stuff()
return {"PI",'=',3.1415926535}
end function
{string what, integer op, atom val} = stuff()
|
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
... | #Elena | Elena | import extensions;
import system'collections;
import system'routines;
public program()
{
var nums := new int[]{1,1,2,3,4,4};
auto unique := new Map<int, int>();
nums.forEach:(n){ unique[n] := n };
console.printLine(unique.MapValues.asEnumerable())
} |
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... | #Perl | Perl | use bignum;
$max = 1000;
$remaining += $_ for 1..$max;
my @recamans = 0;
my $previous = 0;
while ($remaining > 0) {
$term++;
my $this = $previous - $term;
$this = $previous + $term unless $this > 0 and !$seen{$this};
push @recamans, $this;
$dup = $term if !$dup and defined $seen{$this};
$remaini... |
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... | #Groovy | Groovy | enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def ... |
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 ... | #Elena | Elena | import system'math;
import extensions;
public program()
{
console.printLine(E_value); //E
console.printLine(Pi_value); //PI
console.printLine(10.sqrt()); //Square Root
console.printLine(10.ln()); //Logarithm
console.printLine(10.log10()); // Base 10 Logarith... |
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 ... | #Elixir | Elixir | defmodule Real_constants_and_functions do
def main do
IO.puts :math.exp(1) # e
IO.puts :math.pi # pi
IO.puts :math.sqrt(16) # square root
IO.puts :math.log(10) # natural logarithm
IO.puts :math.log10(10) # base 10 logarithm
... |
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... | #Lasso | Lasso | #!/usr/bin/lasso9
local(
orgfilename = $argv -> second,
file = file(#orgfilename),
regexp = regexp(-find = `(?m)$`),
content = #regexp -> split(-input = #file -> readstring) -> asarray,
start = integer($argv -> get(3) || 1),
range = integer($argv -> get(4) || 1)
)
stdout(#content)
#file -> copyto(#or... |
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... | #Liberty_BASIC | Liberty BASIC |
call removeLines "foobar.txt", 1, 2
end
sub removeLines filename$, start, count
open filename$ for input as #in
open filename$ + ".tmp" for output as #out
lineCounter = 1
firstAfterIgnored = start + count
while not(eof(#in))
line input #in, s$
if lineCounter < start or lineCounte... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Open "input.txt" For Input Encoding "ascii" As #1
Dim fileLen As LongInt = Lof(1) '' get file length in bytes
Dim buffer As String = Space(fileLen) '' allocate a string of size 'fileLen' bytes
Get #1, 1, buffer '' read all data from start of file into the buffer
Print buffer '' print to console
buf... |
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... | #Frink | Frink |
a = read["file:yourfile.txt"]
b = read["file:yourfile.txt", "UTF-8"]
|
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... | #Oforth | Oforth | : repString(s)
| sz i |
s size dup ->sz 2 / 1 -1 step: i [
s left(sz i - ) s right(sz i -) == ifTrue: [ s left(i) return ]
]
null ; |
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... | #PARI.2FGP | PARI/GP | rep(v)=for(i=1,#v\2,for(j=i+1,#v,if(v[j]!=v[j-i],next(2)));return(i));0;
v=["1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"];
for(i=1,#v,print(v[i]" "rep(Vec(v[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
| #Objeck | Objeck |
use RegEx;
bundle Default {
class RegExTest {
function : Main(args : String[]) ~ Nil {
string := "I am a string";
# exact match
regex := RegEx->New(".*string");
if(regex->MatchExact(".*string")) {
"ends with 'string'"->PrintLine();
};
# replace all
regex := Re... |
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
| #Objective-C | Objective-C | NSString *str = @"I am a string";
NSString *regex = @".*string$";
// Note: the MATCHES operator matches the entire string, necessitating the ".*"
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([pred evaluateWithObject:str]) {
NSLog(@"ends with 'string'");
} |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Clojure | Clojure |
(defn reverse-string [s]
"Returns a string with all characters in reverse"
(apply str (reduce conj '() s)))
|
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Sidef | Sidef | func repeat(f, n) {
{ f() } * n;
}
func example {
say "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.
| #Standard_ML | Standard ML | fun repeat (_, 0) = ()
| repeat (f, n) = (f (); repeat (f, n - 1))
fun testProcedure () =
print "test\n"
val () = repeat (testProcedure, 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... | #Phix | Phix | without js -- (file i/o)
?rename_file("input.txt","output.txt")
?rename_file("docs","mydocs")
?rename_file("C:\\Copy.txt","Copy.xxx")
?rename_file("C:\\docs","C:\\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... | #Phixmonti | Phixmonti | _platform "windows" == if "\\" "ren " else "/" "mv " endif
var com var slash
com "input.txt output.txt" chain cmd
com "docs mydocs" chain cmd
com slash chain "input.txt " chain slash chain "output.txt" chain cmd
com slash chain "docs " chain slash chain "mydocs" chain cmd |
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... | #Objeck | Objeck | use Collection;
class Reverselines {
function : Main(args : String[]) ~ Nil {
lines := List->New();
lines->AddBack("---------- Ice and Fire ------------");
lines->AddBack("");
lines->AddBack("fire, in end will world the say Some");
lines->AddBack("ice. in say Some");
lines->AddBack("desire o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.