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... | #Java | Java | import java.io.File;
public class FileRenameTest {
public static boolean renameFile(String oldname, String newname) {
// File (or directory) with old name
File file = new File(oldname);
// File (or directory) with new name
File file2 = new File(newname);
// Rename file (or dire... |
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... | #J | J | ([:;@|.[:<;.1 ' ',]);._2]0 :0
---------- 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 -----------------------
)
------------ Fire and Ice ----------
... |
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... | #Java | Java | public class ReverseWords {
static final String[] lines = {
" ----------- Ice and Fire ----------- ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
... |
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... | #Raku | Raku | put .trans: ['A'..'Z','a'..'z'] => ['N'..'Z','A'..'M','n'..'z','a'..'m'] for $*IN.lines |
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... | #PureBasic | PureBasic | #SymbolCount = 12 ;0 based count
DataSection
denominations:
Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12
denomValues:
Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order
EndDataSection
;-setup
Structure romanNumeral
symbol.s
value.i
EndStruct... |
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... | #Simula | Simula | BEGIN
INTEGER PROCEDURE FROMROMAN(S); TEXT S;
BEGIN
PROCEDURE P(INTVAL, NUM); INTEGER INTVAL; TEXT NUM;
BEGIN
INTEGER NLEN;
NLEN := NUM.LENGTH;
WHILE INDEX + NLEN - 1 <= SLEN AND THEN
S.SUB(INDEX, NLEN) = NUM DO
BEGIN
... |
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... | #ColdFusion | ColdFusion |
<cfset word = 'ha'>
<Cfset n = 5>
<Cfoutput>
<Cfloop from="1" to="#n#" index="i">#word#</Cfloop>
</Cfoutput>
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Harbour | Harbour | FUNCTION 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.
| #Haskell | Haskell | 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
... | #Bracmat | Bracmat | 2 3 5 7 11 13 17 19 cats 222 (-100.2) "+11" (1.1) "+7" (7.) 7 5 5 3 2 0 (4.4) 2:?LIST
(A=
( Hashing
= h elm list
. new$hash:?h
& whl
' ( !arg:%?elm ?arg
& ( (h..find)$str$!elm
| (h..insert)$(str$!elm.!elm)
)
)
& :?list
& (h..forall)... |
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... | #CLU | CLU | % Recaman sequence
recaman = cluster is new, fetch
rep = array[int]
new = proc () returns (cvt)
a: rep := rep$predict(0,1000000)
rep$addh(a,0)
return(a)
end new
% Find the N'th element of the Recaman sequence
fetch = proc (a: cvt, n: int) returns (int)
if n > rep$... |
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... | #Comal | Comal | 0010 DIM a#(0:100)
0020 //
0030 // Print the first 15 items
0040 PRINT "First 15 items: ",
0050 FOR i#:=0 TO 14 DO PRINT reca#(i#);
0060 PRINT
0070 //
0080 // Find and print the first repeated item
0090 i#:=15
0100 WHILE NOT find#(i#,reca#(i#)) DO i#:+1
0110 PRINT "First repeated item: A(",i#,") = ",a#(i#)
0120 //
0130... |
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... | #ALGOL_68 | ALGOL 68 | MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
MODE VEC = [0]FIELD;
MODE MAT = [0,0]FIELD;
PROC to reduced row echelon form = (REF MAT m)VOID: (
INT lead col := 2 LWB m;
FOR this row FROM LWB m TO UPB m DO
IF lead col > 2 UPB m THEN return FI;
INT other row := th... |
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 ... | #ALGOL_W | ALGOL W | begin
real t, u;
t := 10;
u := -2.3;
i_w := 4; s_w := 0; r_format := "A"; r_d := 4; r_w := 9; % set output format %
write( " e: ", exp( 1 ) ); % e %
write( " pi: ", pi ); % pi %
write( " root t: ", sqrt( t ) ); % square ... |
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 ... | #ARM_Assembly | ARM Assembly |
/* functions not availables */
|
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... | #D | D | import std.stdio, std.file, std.string;
void main() {
deleteLines("deleteline_test.txt", 1, 2);
}
void deleteLines(string name, int start, int num)
in {
assert(start > 0, "Line counting must start at 1");
} body {
start--;
if (!exists(name) || !isFile(name))
throw new FileException("File n... |
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... | #BASIC | BASIC | DIM f AS STRING
OPEN "file.txt" FOR BINARY AS 1
f = SPACE$(LOF(1))
GET #1, 1, f
CLOSE 1 |
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... | #BBC_BASIC | BBC BASIC | file% = OPENIN("input.txt")
strvar$ = ""
WHILE NOT EOF#file%
strvar$ += CHR$(BGET#file%)
ENDWHILE
CLOSE #file% |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Scala | Scala | object ListMethods extends App {
private val obj = new {
def examplePublicInstanceMethod(c: Char, d: Double) = 42
private def examplePrivateInstanceMethod(s: String) = true
}
private val clazz = obj.getClass
println("All public methods (including inherited):")
clazz.getMethods.foreach(m => print... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Sidef | Sidef | class Example {
method foo { }
method bar(arg) { say "bar(#{arg})" }
}
var obj = Example()
say obj.methods.keys.sort #=> ["bar", "call", "foo", "new"]
var meth = obj.methods.item(:bar) # `LazyMethod` representation for `obj.bar()`
meth(123) # calls obj.bar() |
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... | #F.23 | F# | let isPrefix p (s : string) = s.StartsWith(p)
let getPrefix n (s : string) = s.Substring(0,n)
let repPrefixOf str =
let rec isRepeatedPrefix p s =
if isPrefix p s then isRepeatedPrefix p (s.Substring (p.Length))
else isPrefix s p
let rec getLongestRepeatedPrefix n =
if n = 0 then No... |
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
| #Genie | Genie | [indent=4]
/* Regular expressions, in Genie */
init
var sentence = "This is a sample sentence."
try
var re = new Regex("s[ai]mple")
if re.match(sentence)
print "matched '%s' in '%s'", re.get_pattern(), sentence
var offs = 0
print("replace with 'different': %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
| #Go | Go | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
// Test
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
// Substitute
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modif... |
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
... | #BaCon | BaCon | OPTION UTF8 TRUE
s$ = "asdf"
PRINT REVERSE$(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.
| #Nanoquery | Nanoquery | def repeat(f,n)
for i in range(1, n)
f()
end
end
def procedure()
println "Example"
end
repeat(procedure, 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... | #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject")
fso.MoveFile("input.txt", "output.txt")
fso.MoveFile("c:/input.txt", "c:/output.txt")
fso.MoveFolder("docs", "mydocs")
fso.MoveFolder("c:/docs", "c:/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... | #JavaScript | JavaScript | var strReversed =
"---------- Ice and Fire ------------\n\
\n\
fire, in end will world the say Some\n\
ice. in say Some\n\
desire of tasted I've what From\n\
fire. favor who those with hold I\n\
\n\
... elided paragraph last ...\n\
\n\
Frost Robert -----------------------";
function reverseString(s) {
return s.spli... |
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... | #RapidQ | RapidQ |
function ROT13 (InputTxt as string) as string
dim i as integer, ascVal as byte
Result = ""
for i = 1 to len(InputTxt)
ascVal = asc(InputTxt[i])
select case ascVal
case 65 to 77, 97 to 109
Result = Result + chr$(ascVal + 13)
case 78 to 90, 110 to 122
... |
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... | #Python | Python | import roman
print(roman.toRoman(2022)) |
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... | #SNOBOL4 | SNOBOL4 | * Roman to Arabic
define('arabic(n)s,ch,val,sum,x') :(arabic_end)
arabic s = 'M1000 D500 C100 L50 X10 V5 I1 '
n = reverse(n)
arab1 n len(1) . ch = :f(arab2)
s ch break(' ') . val
val = lt(val,x) (-1 * val)
sum = sum + val; x = val :(arab1)
arab2 arabic = sum ... |
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... | #Common_Lisp | Common Lisp | (defun repeat-string (n string)
(with-output-to-string (stream)
(loop repeat n do (write-string string stream)))) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Icon_and_Unicon | Icon and Unicon | procedure retList() # returns as ordered list
return [1,2,3]
end
procedure retSet() # returns as un-ordered list
insert(S := set(),3,1,2)
return S
end
procedure retLazy() # return as a generator
suspend 1|2|3
end
procedure retTable() # return as a table
T := table()
T["A"] := 1
... |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Brat | Brat | some_array = [1 1 2 1 'redundant' [1 2 3] [1 2 3] 'redundant']
unique_array = some_array.unique |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. RECAMAN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 RECAMAN-SEQUENCE COMP.
02 A PIC 999 OCCURS 99 TIMES INDEXED BY I.
02 N PIC 999 VALUE 0.
01 VARIABLES COMP.
02 ADDC PIC S999.
0... |
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... | #ALGOL_W | ALGOL W | begin
% replaces M with it's reduced row echelon form %
% M should have bounds ( 0 :: rMax, 0 :: cMax ) %
procedure toReducedRowEchelonForm ( real array M ( *, * )
; integer value rMax, cMax
) ;
begi... |
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 ... | #Arturo | Arturo | print ["Euler:" e]
print ["Pi:" pi]
print ["sqrt 2.0:" sqrt 2.0]
print ["ln 100:" ln 100]
print ["log(10) 100:" log 100 10]
print ["exp 3:" exp 3]
print ["abs -1:" abs neg 1]
print ["floor 23.536:" floor 23.536]
print ["ceil 23.536:" ceil 23.536]
print ["2 ^ 8:" 2 ^ 8] |
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... | #Delphi | Delphi |
program Remove_lines_from_a_file_using_TStringDynArray;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IoUtils;
// zero started Index
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(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... | #Blue | Blue | global _start
: syscall ( num:eax -- result:eax ) syscall ;
: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;
: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;
: open ( pathname:edi flags:esi -- fd:eax ) 2 sy... |
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... | #BQN | BQN | •file.Chars "file"
•file.Bytes "file"
# Shorthands:
•FChars "file"
•FBytes "file"
|
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Tcl | Tcl | % info object methods ::oo::class -all -private
<cloned> create createWithNamespace destroy eval new unknown variable varname |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Wren | Wren | #! instance_methods(m, n, o)
#! instance_properties(p, q, r)
class C {
construct new() {}
m() {}
n() {}
o() {}
p {}
q {}
r {}
}
var c = C.new() // create an object of type C
System.print("List of instance methods available for object 'c':")
for (method in c.type.attributes.self["insta... |
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... | #Factor | Factor | USING: formatting grouping kernel math math.ranges qw sequences ;
IN: rosetta-code.rep-string
: (find-rep-string) ( str -- str )
dup dup length 2/ [1,b]
[ <groups> [ head? ] monotonic? ] with find nip dup
[ head ] [ 2drop "N/A" ] if ;
: find-rep-string ( str -- str )
dup length 1 <= [ drop "N/A" ] [... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Forth | Forth | : rep-string ( caddr1 u1 -- caddr2 u2 ) \ u2=0: not a rep-string
2dup dup >r r@ 2/ /string
begin 2over 2over string-prefix? 0= over r@ < and while -1 /string repeat
r> swap - >r 2drop r> ;
: test ( caddr u -- )
2dup type ." has "
rep-string ?dup 0= if drop ." no " else type ." as " then
.... |
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
| #Groovy | Groovy | import java.util.regex.*;
def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
def pepper = "Peter Piper picked a peck of pickled peppers"
println "=== Regular-expression String syntax (/string/) ==="
def woodRE = /[Ww]o\w+d/
def piperRE = /[Pp]\w+r/
assert woodRE instanceof St... |
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
... | #BASIC | BASIC | FUNCTION reverse$(a$)
b$ = ""
FOR i = 1 TO LEN(a$)
b$ = MID$(a$, i, 1) + b$
NEXT i
reverse$ = b$
END FUNCTION |
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.
| #Nim | Nim | proc example =
echo "Example"
# Ordinary procedure
proc repeatProc(fn: proc, n: int) =
for x in 0..<n:
fn()
repeatProc(example, 4)
# Template (code substitution), simplest form of metaprogramming
# that Nim has
template repeatTmpl(n: int, body: untyped): untyped =
for x in 0..<n:
body
# This ge... |
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.
| #Objeck | Objeck | class Repeat {
function : Main(args : String[]) ~ Nil {
Repeat(Example() ~ Nil, 3);
}
function : Repeat(e : () ~ Nil, i : Int) ~ Nil {
while(i-- > 0) {
e();
};
}
function : Example() ~ Nil {
"Example"->PrintLine();
}
} |
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... | #Joy | Joy |
"input.txt" "output.txt" frename
"/input.txt" "/output.txt" frename
"docs" "mydocs" frename
"/docs" "/mydocs" frename.
|
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... | #Jsish | Jsish | /* File rename, in jsish */
try { File.rename('input.txt', 'output.txt', false); } catch (str) { puts(str); }
exec('touch input.txt');
puts("overwrite set true if output.txt exists");
File.rename('input.txt', 'output.txt', true);
try { File.rename('docs', 'mydocs', false); } catch (str) { puts(str); }
try { File.re... |
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... | #jq | jq | split("[ \t\n\r]+") | reverse | join(" ") |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Raven | Raven | define rot13 use $str
$str each chr
dup m/[A-Ma-m]/ if
ord 13 + chr
else
dup m/[N-Zn-z]/ if
ord 13 - chr
$str length list "" join
"12!ABJURER nowhere"
dup print "\nas rot13 is\n" print
rot13
print "\n" print |
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... | #QBasic | QBasic | DIM SHARED arabic(0 TO 12)
DIM SHARED roman$(0 TO 12)
FUNCTION toRoman$ (value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ + roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
toRoman$ = result$
END FUNCTION
FOR i = 0 TO ... |
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... | #SPL | SPL | r2a(r)=
n = [1,5,10,50,100,500,1000]
a,m = 0
> i, #.size(r)..1, -1
v,c = n[#.pos("IVXLCDM",#.mid(r,i))]
? v<m, v = -v
? c>m, m = c
a += v
<
<= a
.
t = ["MMXI","MIM","MCMLVI","MDCLXVI","XXCIII","LXXIIX","IIIIX"]
> i, 1..#.size(t,1)
#.output(t[i]," = ",r2a(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... | #Crystal | Crystal |
puts "ha" * 5
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #J | J | 1 2+3 4
4 6 |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Java | Java | import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
// =============================================================================
public class RReturnMultipleVals {
public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed ... |
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
... | #C | C | #include <stdio.h>
#include <stdlib.h>
struct list_node {int x; struct list_node *next;};
typedef struct list_node node;
node * uniq(int *a, unsigned alen)
{if (alen == 0) return NULL;
node *start = malloc(sizeof(node));
if (start == NULL) exit(EXIT_FAILURE);
start->x = a[0];
start->next = NULL;
for (i... |
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... | #D | D | import std.stdio;
void main() {
int[] a;
bool[int] used;
bool[int] used1000;
bool foundDup;
a ~= 0;
used[0] = true;
used1000[0] = true;
int n = 1;
while (n <= 15 || !foundDup || used1000.length < 1001) {
int next = a[n - 1] - n;
if (next < 1 || (next in used) !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... | #AutoHotkey | AutoHotkey | ToReducedRowEchelonForm(M){
rowCount := M.Count() ; the number of rows in M
columnCount := M.1.Count() ; the number of columns in M
r := lead := 1
while (r <= rowCount) {
if (columnCount < lead)
return M
i := r
while (M[i, lead] = 0) {
i++
i... |
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 ... | #Asymptote | Asymptote | real e = exp(1); // e not available
write("e = ", e);
write("pi = ", pi);
real x = 12.345;
real y = 1.23;
write("sqrt = ", sqrt(2)); // square root
write("ln = ", log(e)); // natural logarithm base e
write("log = ", log10(x)); // base 10 logarithm
write("log1p = ", log1p... |
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... | #ECL | ECL |
IMPORT STD;
RemoveLines(logicalfile, startline, numlines) := FUNCTIONMACRO
EndLine := startline + numlines - 1;
RecCnt := COUNT(logicalfile);
Res := logicalfile[1..startline-1] + logicalfile[endline+1..];
RETURN WHEN(IF(RecCnt < EndLine,logicalfile,Res),
IF(RecCnt < EndLine,STD.System.Log.addW... |
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... | #Bracmat | Bracmat | > Keep cell 0 at 0 as a sentinel value
,[>,] Read into successive cells until EOF
<[<] Go all the way back to the beginning
>[.>] Print successive cells while nonzero |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #zkl | zkl | methods:=List.methods;
methods.println();
List.method(methods[0]).println(); // == .Method(name) == .BaseClass(name) |
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... | #FreeBASIC | FreeBASIC |
Data "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", ""
Function rep(c As String, n As Integer) As String
Dim As String r
For i As Integer = 1 To n
r = r + c
Next i
Return r
End Function
Do
Dim As String p, b = ""... |
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
| #Haskell | Haskell | import Text.Regex
str = "I am a string"
case matchRegex (mkRegex ".*string$") str of
Just _ -> putStrLn $ "ends with 'string'"
Nothing -> return () |
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
... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call :reverse %1 res
echo %res%
goto :eof
:reverse
set str=%~1
set cnt=0
:loop
if "%str%" equ "" (
goto :eof
)
set chr=!str:~0,1!
set str=%str:~1%
set %2=%chr%!%2!
goto loop |
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.
| #OCaml | OCaml | let repeat ~f ~n =
for i = 1 to n do
f ()
done
let func () =
print_endline "Example"
let () =
repeat ~n:4 ~f: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... | #Julia | Julia |
mv("input.txt", "output.txt")
mv("docs", "mydocs")
mv("/input.txt", "/output.txt")
mv("/docs", "/mydocs") |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Kotlin | Kotlin | // version 1.0.6
/* testing on Windows 10 which needs administrative privileges
to rename files in the root */
import java.io.File
fun main(args: Array<String>) {
val oldPaths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs")
val newPaths = arrayOf("output.txt", "mydocs", "c:\\output.txt", "c... |
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... | #Jsish | Jsish | var strReversed =
"---------- Ice and Fire ------------\n
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
\n... elided paragraph last ...\n
Frost Robert -----------------------";
function reverseString(s) {
return s.split('\n').map(
fun... |
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... | #REBOL | REBOL | rebol [
Title: "Rot-13"
URL: http://rosettacode.org/wiki/Rot-13
]
; Test data has upper and lower case characters as well as characters
; that should not be transformed, like numbers, spaces and symbols.
text: "This is a 28-character test!"
print "Using cipher table:"
; I build a set of correspondence l... |
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... | #Quackery | Quackery | [ $ ""
swap 1000 /mod $ "M" rot of rot swap join swap
dup 900 < not if [ 900 - dip [ $ "CM" join ] ]
dup 500 < not if [ 500 - dip [ $ "D" join ] ]
dup 400 < not if [ 400 - dip [ $ "CD" join ] ]
100 /mod $ "C" rot of rot swap join swap
dup 90 < not if [ 90 - dip [ $ "XC" join ... |
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... | #Swift | Swift | extension Int {
init(romanNumerals: String) {
let values = [
( "M", 1000),
("CM", 900),
( "D", 500),
("CD", 400),
( "C", 100),
("XC", 90),
( "L", 50),
("XL", 40),
( "X", 10),
(... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #D | D | import std.stdio, std.array;
void main() {
writeln("ha".replicate(5));
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #JavaScript | JavaScript | //returns array with three values
var arrBind = function () {
return [1, 2, 3]; //return array of three items to assign
};
//returns object with three named values
var objBind = function () {
return {foo: "abc", bar: "123", baz: "zzz"};
};
//keep all three values
var [a, b, c] = arrBind();//assigns a => 1, b =>... |
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
... | #C.23 | C# | int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n); |
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... | #Draco | Draco | proc nonrec find([*] int A; word top; int n) bool:
word i;
bool found;
i := 0;
found := false;
while i < top and not found do
found := A[i] = n;
i := i + 1
od;
found
corp
proc nonrec gen_next([*] int A; word n) int:
int add, sub;
add := A[n-1] + n;
sub := A[n-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... | #Forth | Forth | : array ( n -- ) ( i -- addr)
create cells allot
does> swap cells + ;
100 array sequence
: sequence. ( n -- ) cr 0 ?do i sequence @ . loop ;
: ?unused ( n -- t | n )
100 0 ?do
dup i sequence @ = if unloop exit then
loop drop true ;
: sequence-next ( n -- a[n] )
dup 0= if 0 0 sequence ! exit then ... |
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... | #AutoIt | AutoIt |
Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]]
ToReducedRowEchelonForm($ivMatrix)
Func ToReducedRowEchelonForm($matrix)
Local $clonematrix, $i
Local $lead = 0
Local $rowCount = UBound($matrix) - 1
Local $columnCount = UBound($matrix, 2) - 1
For $r = 0 To $rowCount
If $columnCount =... |
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 ... | #AutoHotkey | AutoHotkey | Sqrt(Number) ; square root
Log(Number) ; logarithm (base 10)
Ln(Number) ; natural logarithm (base e)
Exp(N) ; e to the power N
Abs(Number) ; absolute value
Floor(Number) ; floor
Ceil(Number) ; ceiling
x**y ; x to the power 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 ... | #AWK | AWK | BEGIN {
print sqrt(2) # square root
print log(2) # logarithm base e
print exp(2) # exponential
print 2 ^ -3.4 # power
}
# outputs 1.41421, 0.693147, 7.38906, 0.0947323 |
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... | #Elixir | Elixir | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file ... |
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... | #Erlang | Erlang |
-module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, Ho... |
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... | #Brainf.2A.2A.2A | Brainf*** | > Keep cell 0 at 0 as a sentinel value
,[>,] Read into successive cells until EOF
<[<] Go all the way back to the beginning
>[.>] Print successive cells while nonzero |
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... | #Brat | Brat | include :file
file.read file_name |
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... | #Go | Go | package main
import (
"fmt"
"strings"
)
func rep(s string) int {
for x := len(s) / 2; x > 0; x-- {
if strings.HasPrefix(s, s[x:]) {
return x
}
}
return 0
}
const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`
func main... |
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
| #HicEst | HicEst | CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" /
REAL, PARAMETER :: Regex=128, Count=256
characters_a_m = INDEX(string, "[a-m]", Regex+Count) ! counts 16
vocals_changed = EDIT(Text=string, Option=Regex, Right="[aeiou]", RePLaceby='**', DO=LEN(string) ) ! changes 11
WRITE(ClipBoard) string ! Th*... |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
s := "A simple string"
p := "string$" # regular expression
s ? write(image(s),if ReFind(p) then " matches " else " doesn't match ",image(p))
s[j := ReFind(p,s):ReMatch(p,s,j)] := "replacement"
write(image(s))
end
link regexp # link to IPL regexp |
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
... | #BBC_BASIC | BBC BASIC | PRINT FNreverse("The five boxing wizards jump quickly")
END
DEF FNreverse(A$)
LOCAL B$, C%
FOR C% = LEN(A$) TO 1 STEP -1
B$ += MID$(A$,C%,1)
NEXT
= B$ |
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.
| #Oforth | Oforth | : hello "Hello, World!" println ;
10 #hello times |
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.
| #Ol | Ol |
; sample function
(define (function) (display "+"))
; simple case for 80 times
(for-each (lambda (unused) (function)) (iota 80))
(print) ; print newline
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
; detailed case for 80 times
(let loop ((fnc function) (n 80))
(unless ... |
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... | #Lasso | Lasso | // move file
local(f = file('input.txt'))
#f->moveTo('output.txt')
#f->close
// move directory, just like a file
local(d = dir('docs'))
#d->moveTo('mydocs')
// move file in root file system (requires permissions at user OS level)
local(f = file('//input.txt'))
#f->moveTo('//output.txt')
#f->close
// move director... |
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... | #LFE | LFE |
(file:rename "input.txt" "output.txt")
(file:rename "docs" "mydocs")
(file:rename "/input.txt" "/output.txt")
(file:rename "/docs" "/mydocs")
|
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Julia | Julia | revstring (str) = join(reverse(split(str, " ")), " ") |
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... | #Kotlin | Kotlin | fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")
fun main() {
val s = "Hey you, Bub!"
println(reversedWords(s))
println()
val sl = listOf(
" ---------- Ice and 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... | #Retro | Retro | {{
: rotate ( cb-c ) tuck - 13 + 26 mod + ;
: rotate? ( c-c )
dup 'a 'z within [ 'a rotate ] ifTrue
dup 'A 'Z within [ 'A rotate ] ifTrue ;
---reveal---
: rot13 ( s-s ) dup [ [ @ rotate? ] sip ! ] ^types'STRING each@ ;
}}
"abcdef123GHIJKL" rot13 dup puts cr rot13 puts
"abjurer NOWHERE" rot13 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... | #R | R | as.roman(1666) # MDCLXVI |
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... | #Tailspin | Tailspin |
def digits: [(M:1000"1"), (CM:900"1"), (D:500"1"), (CD:400"1"), (C:100"1"), (XC:90"1"), (L:50"1"), (XL:40"1"), (X:10"1"), (IX:9"1"), (V:5"1"), (IV:4"1"), (I:1"1")];
composer decodeRoman
@: 1;
[ <digit>* ] -> \(@: 0; $... -> @: $@ + $; $@ !\)
rule digit: <value>* (@: $@ + 1;)
rule value: <='$digits($@)::key;'>... |
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... | #DCL | DCL | $ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" )
$ write sys$output f$fao( "!12*d" ) |
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... | #Delphi | Delphi |
function RepeatString(const s: string; count: cardinal): string;
var
i: Integer;
begin
for i := 1 to count do
Result := Result + s;
end;
Writeln(RepeatString('ha',5));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.