task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Perl | Perl | sub rot13 {
shift =~ tr/A-Za-z/N-ZA-Mn-za-m/r;
}
print rot13($_) while (<>); |
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... | #Oforth | Oforth | [ [1000,"M"], [900,"CM"], [500,"D"], [400,"CD"], [100,"C"], [90,"XC"], [50,"L"], [40,"XL"], [10,"X"], [9,"IX"], [5,"V"], [4,"IV"], [1,"I"] ] const: Romans
: roman(n)
| r |
StringBuffer new
Romans forEach: r [ while(r first n <=) [ r second << n r first - ->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... | #PureBasic | PureBasic | Procedure romanDec(roman.s)
Protected i, n, lastval, arabic
For i = Len(roman) To 1 Step -1
Select UCase(Mid(roman, i, 1))
Case "M"
n = 1000
Case "D"
n = 500
Case "C"
n = 100
Case "L"
n = 50
Case "X"
n = 10
Case "V"
n = 5
... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #VBA | VBA |
Option Explicit
Sub Main()
Dim p As String
p = length_encoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
Debug.Print p
Debug.Print length_decoding(p)
End Sub
Private Function length_encoding(S As String) As String
Dim F As String, r As String, a As String, n As Long, c As Lon... |
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... | #AppleScript | AppleScript | set str to "ha"
set final_string to ""
repeat 5 times
set final_string to final_string & str
end repeat |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Clojure | Clojure | (defn quot-rem [m n] [(quot m n) (rem m n)])
; The following prints 3 2.
(let [[q r] (quot-rem 11 3)]
(println q)
(println r)) |
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... | #Ada | Ada | with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed;
procedure Rep_String is
function Find_Largest_Rep_String(S:String) return String is
L: Natural := S'Length;
begin
for I in reverse 1 .. L/2 loop
declare
use Ada.Strings.Fixed;
T: String := S(S'First .. S'First + I-1); -- the first ... |
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
| #Ada | Ada | with Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;
procedure Regex is
package Pat renames Gnat.Regpat;
procedure Search_For_Pattern(Compiled_Expression: Pat.Pattern_Matcher;
Search_In: String;
First, Last: out Positive;
... |
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
... | #8th | 8th |
"abc" s:rev
|
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Erlang | Erlang |
-module( rendezvous ).
-export( [task/0] ).
task() ->
Printer_pid = erlang:spawn( fun() -> printer(1, 5) end ),
Reserve_printer_pid = erlang:spawn( fun() -> printer(2, 5) end ),
Monitor_pid = erlang:spawn( fun() -> printer_monitor(Printer_pid, Reserve_printer_pid) end ),
erlang:spawn( fun() -> pri... |
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.
| #AutoHotkey | AutoHotkey | repeat("fMsgBox",3)
return
repeat(f, n){
loop % n
%f%()
}
fMsgBox(){
MsgBox hello
} |
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... | #AutoHotkey | AutoHotkey | FileMove, oldname, newname |
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... | #AutoIt | AutoIt | $ awk 'BEGIN{system("mv input.txt output.txt")}'
$ awk 'BEGIN{system("mv docs mydocs")}'
$ awk 'BEGIN{system("mv /input.txt /output.txt")}'
$ awk 'BEGIN{system("mv docs mydocs")}' |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Tcl | Tcl | package require ripemd160
puts [ripemd::ripemd160 -hex "Rosetta Code"] |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Wren | Wren | import "/crypto" for Ripemd160
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"Th... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Modula-2 | Modula-2 | MODULE ResistorMesh;
FROM RConversions IMPORT RealToStringFixed;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
CONST S = 10;
TYPE Node = RECORD
v : LONGREAL;
fixed : INTEGER;
END;
PROCEDURE SetBoundary(VAR m : ARRAY OF ARRAY OF Node);
BEGIN
m[1][1].v := 1.0;
m[1][1].fixed := 1;
m[6][7].... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Scala | Scala | class DynamicTest extends Dynamic
{
def foo()=println("this is foo")
def bar()=println("this is bar")
def applyDynamic(name: String)(args: Any*)={
println("tried to handle unknown method "+name)
if(!args.isEmpty)
println(" it had arguments: "+args.mkString(","))
}
}
object DynamicTest {
def m... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Sidef | Sidef | class Example {
method foo {
say "this is foo"
}
method bar {
say "this is bar"
}
method AUTOLOAD(_, name, *args) {
say ("tried to handle unknown method %s" % name);
if (args.len > 0) {
say ("it had arguments: %s" % args.join(', '));
}
}
}
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... | #COBOL | COBOL |
program-id. rev-word.
data division.
working-storage section.
1 text-block.
2 pic x(36) value "---------- Ice and Fire ------------".
2 pic x(36) value " ".
2 pic x(36) value "fire, in end will world the say Some".
2 pic x(... |
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... | #Phix | Phix | function rot13(string s)
integer ch
for i=1 to length(s) do
ch = upper(s[i])
if ch>='A' and ch<='Z' then
s[i] += iff(ch<='M',+13,-13)
end if
end for
return s
end function
?rot13("abjurer NOWHERE.")
|
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... | #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION encodeRoman RETURNS CHAR (
i_i AS INT
):
DEF VAR cresult AS CHAR.
DEF VAR croman AS CHAR EXTENT 7 INIT [ "M", "D", "C", "L", "X", "V", "I" ].
DEF VAR idecimal AS INT EXTENT 7 INIT [ 1000, 500, 100, 50, 10, 5, 1 ].
DEF VAR ipos AS INT INIT 1.
DO WHILE i_i > 0:
I... |
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... | #Python | Python | _rdecode = dict(zip('MDCLXVI', (1000, 500, 100, 50, 10, 5, 1)))
def decode( roman ):
result = 0
for r, r1 in zip(roman, roman[1:]):
rd, rd1 = _rdecode[r], _rdecode[r1]
result += -rd if rd < rd1 else rd
return result + _rdecode[roman[-1]]
if __name__ == '__main__':
for r in 'MCMXC MMV... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Vedit_macro_language | Vedit macro language | :RL_ENCODE:
BOF
While (!At_EOF) {
if (At_EOL) { Line(1) Continue } // skip newlines
#1 = Cur_Char // #1 = character
Match("(.)\1*", REGEXP) // count run length
#2 = Chars_Matched // #2 = run length
if (#2 > 127) { #2 = 127 } // can be ma... |
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... | #Applesoft_BASIC | Applesoft BASIC | FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT
? "X" SPC(20) "X" |
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... | #Arturo | Arturo | print repeat "ha" 5 |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #CLU | CLU | % Returning multiple values (along with type parameterization)
% was actually invented with CLU.
% Do note that the procedure is actually returning multiple
% values; it's not returning a tuple and unpacking it.
% That doesn't exist in CLU.
% For added CLU-ness, this function is fully general, requiring
% only tha... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #CMake | CMake | # Returns the first and last characters of string.
function(firstlast string first last)
# f = first character.
string(SUBSTRING "${string}" 0 1 f)
# g = last character.
string(LENGTH "${string}" length)
math(EXPR index "${length} - 1")
string(SUBSTRING "${string}" ${index} 1 g)
# Return both characte... |
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... | #ALGOL_68 | ALGOL 68 | # procedure to find the longest rep-string in a given string #
# the input string is not validated to contain only "0" and "1" characters #
PROC longest rep string = ( STRING input )STRING:
BEGIN
STRING result := "";
# ensure the string we are working on has a lower-bound of 1 ... |
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
| #ALGOL_68 | ALGOL 68 | INT match=0, no match=1, out of memory error=2, other error=3;
STRING str := "i am a string";
# Match: #
STRING m := "string$";
INT start, end;
IF grep in string(m, str, start, end) = match THEN printf(($"Ends with """g""""l$, str[start:end])) FI;
# Replace: #
IF sub in string(" a ", " another ",str) = match ... |
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
... | #ACL2 | ACL2 | (reverse "hello") |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #F.23 | F# | open System
type PrinterCommand = Print of string
// a message is a command and a facility to return an exception
type Message = Message of PrinterCommand * AsyncReplyChannel<Exception option>
// thrown if we have no more ink (and neither has our possible backup printer)
exception OutOfInk
type Printer(id, ?bac... |
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.
| #AWK | AWK |
# syntax: GAWK -f REPEAT.AWK
BEGIN {
for (i=0; i<=3; i++) {
f = (i % 2 == 0) ? "even" : "odd"
@f(i) # indirect function call
}
exit(0)
}
function even(n, i) {
for (i=1; i<=n; i++) {
printf("inside even %d\n",n)
}
}
function odd(n, i) {
for (i=1; i<=n; i++) {
printf("i... |
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.
| #Batch_File | Batch File |
@echo off
:_main
setlocal
call:_func1 _func2 3
pause>nul
exit/b
:_func1
setlocal enabledelayedexpansion
for /l %%i in (1,1,%2) do call:%1
exit /b
:_func2
setlocal
echo _func2 has been executed
exit /b
|
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... | #AWK | AWK | $ awk 'BEGIN{system("mv input.txt output.txt")}'
$ awk 'BEGIN{system("mv docs mydocs")}'
$ awk 'BEGIN{system("mv /input.txt /output.txt")}'
$ awk 'BEGIN{system("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... | #BaCon | BaCon | RENAME "input.txt" TO "output.txt"
RENAME "/input.txt" TO "/output.txt"
RENAME "docs" TO "mydocs"
RENAME "/docs" TO "/mydocs"
|
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #zkl | zkl | var MsgHash=Import("zklMsgHash");
MsgHash.RIPEMD160("Rosetta Code") |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Nim | Nim | const S = 10
type
NodeKind = enum nodeFree, nodeA, nodeB
Node = object
v: float
fixed: NodeKind
Mesh[H, W: static int] = array[H, array[W, Node]]
func setBoundary(m: var Mesh) =
m[1][1].v = 1.0
m[1][1].fixed = nodeA
m[6][7].v = -1.0
m[6][7].fixed = nodeB
func calcDiff[H, W: static... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Slate | Slate | define: #shell &builder: [lobby newSubSpace].
_@shell didNotUnderstand: message at: position
"Form a command string and execute it."
[
position > 0
ifTrue: [resend]
ifFalse:
[([| :command |
message selector isUnarySelector ifTrue:
[command ; message selector.
message optionals pairsDo:
[... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Smalltalk | Smalltalk | Object subclass: CatchThemAll [
foo [ 'foo received' displayNl ]
bar [ 'bar received' displayNl ]
doesNotUnderstand: aMessage [
('message "' , (aMessage selector asString) , '"') displayNl.
(aMessage arguments) do: [ :a |
'argument: ' display. a printNl.
]
]
]
|a| a := Ca... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #SuperCollider | SuperCollider | Ingorabilis {
tell {
"I told you so".postln;
}
find {
"I found nothing".postln
}
doesNotUnderstand { |selector ... args|
"Method selector '%' not understood by %\n".postf(selector, this.class);
"Giving you some good arguments in the following".postln;
args.do { |x| x.postln };
"And now I delegate... |
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... | #CoffeeScript | CoffeeScript | 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 -----------------------'
reverseString = (s) ->
s.split('\n').map((l) -> l.split(/... |
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... | #PHP | PHP | echo str_rot13('foo'), "\n"; |
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... | #Oz | Oz | declare
fun {Digit X Y Z K}
unit([X] [X X] [X X X] [X Y] [Y] [Y X] [Y X X] [Y X X X] [X Z])
.K
end
fun {ToRoman X}
if X == 0 then ""
elseif X < 0 then raise toRoman(negativeInput X) end
elseif X >= 1000 then "M"#{ToRoman X-1000}
elseif X >= 100 then {Digit &C &D &M X d... |
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... | #QBasic | QBasic | FUNCTION romToDec (roman$)
num = 0
prenum = 0
FOR i = LEN(roman$) TO 1 STEP -1
x$ = MID$(roman$, i, 1)
n = 0
IF x$ = "M" THEN n = 1000
IF x$ = "D" THEN n = 500
IF x$ = "C" THEN n = 100
IF x$ = "L" THEN n = 50
IF x$ = "X" THEN n = 10
IF x$ = "V"... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Wren | Wren | import "/pattern" for Pattern
var p = Pattern.new("/u") // match any upper case letter
var encode = Fn.new { |s|
if (s == "") return s
var e = ""
var curr = s[0]
var count = 1
var i = 1
while (i < s.count) {
if (s[i] == curr) {
count = count + 1
} else {
... |
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... | #AutoHotkey | AutoHotkey | MsgBox % Repeat("ha",5)
Repeat(String,Times)
{
Loop, %Times%
Output .= String
Return Output
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #COBOL | COBOL |
identification division.
program-id. multiple-values.
environment division.
configuration section.
repository.
function multiples
function all intrinsic.
REPLACE ==:linked-items:== BY ==
01 a usage binary-long.
01 b pic x(10).
01... |
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
... | #11l | 11l | V items = [‘1’, ‘2’, ‘3’, ‘a’, ‘b’, ‘c’, ‘2’, ‘3’, ‘4’, ‘b’, ‘c’, ‘d’]
V unique = Array(Set(items))
print(unique) |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetProper... |
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... | #APL | APL | rep ← ⊢ (⊢(/⍨)(⊂⊣)≡¨(≢⊣)⍴¨⊢) ⍳∘(⌊0.5×≢)↑¨⊂ |
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... | #AppleScript | AppleScript | ------------------------REP-CYCLES-------------------------
-- repCycles :: String -> [String]
on repCycles(xs)
set n to length of xs
script isCycle
on |λ|(cs)
xs = takeCycle(n, cs)
end |λ|
end script
filter(isCycle, tail(inits(take(quot(n, 2), xs))))
end repCycles
--... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #6502_Assembly | 6502 Assembly | LDA #<foo
sta $00
LDA #>foo
sta $01
jsr PrintBytecode
foo:
;do stuff
rts
PrintBytecode:
ldy #0
lda $01 ;high byte of starting address of the source
jsr PrintHex
;unimplemented routine that separates the "nibbles" of the accumulator,
; adds $30 or $37 to each depending on if it's 0-9 or A-F respectively, which... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #Clojure | Clojure |
; Use source function for source code.
(source println)
; Use meta function for filenames and line numbers (and other metadata)
(meta #'println) |
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
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
expReg="[A-Z]{1,2}[0-9][0-9A-Z]? +[0-9][A-Z]{2}"
flag compile = REG_EXTENDED
flag match=0
número de matches=10, T1=0
{flag compile,expReg} reg compile(T1) // compile regular expression, pointed whit T1
{flag match,número de matches,T1,"We are at SN12 7NY for this cours... |
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
| #AppleScript | AppleScript | try
find text ".*string$" in "I am a string" with regexp
on error message
return message
end try
try
change "original" into "modified" in "I am the original string" with regexp
on error message
return message
end try |
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
... | #Action.21 | Action! | PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j
i=1 j=src(0) dst(0)=j
WHILE j>0
DO
dst(j)=src(i)
i==+1 j==-1
OD
RETURN
PROC Test(CHAR ARRAY src)
CHAR ARRAY dst(40)
Reverse(src,dst)
PrintF("'%S' -> '%S'%E",src,dst)
RETURN
PROC Main()
Test("Hello World!")
Test("123456789")
Test("!noitcA ir... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Go | Go | package main
import (
"errors"
"fmt"
"strings"
"sync"
)
var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`
var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the ai... |
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.
| #BQN | BQN | •Show {2+𝕩}⍟3 1
_repeat_ ← {(𝕘>0)◶⊢‿(𝔽_𝕣_(𝕘-1)𝔽)𝕩}
•Show {2+𝕩} _repeat_ 3 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.
| #C | C | #include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)(); //or just f()
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
|
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... | #BASIC | BASIC | NAME "input.txt" AS "output.txt"
NAME "\input.txt" AS "\output.txt"
NAME "docs" AS "mydocs"
NAME "\docs" AS "\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... | #Batch_File | Batch File | ren input.txt output.txt
ren \input.txt output.txt
ren docs mydocs
ren \docs mydocs |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Octave | Octave | N = 10;
NN = N*N;
G = sparse(NN, NN);
node = 0;
for row=1:N;
for col=1:N;
node++;
if row > 1
G(node, node)++;
G(node, node - N) = -1;
end
if row < N;
G(node, node)++;
G(node, node + N) = -1;
end
if col > 1
G(node, node)++;
G(node, node - 1) = -1;
end
if col < N;
G(node, ... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Tcl | Tcl | package require TclOO
# First create a simple, conventional class and object
oo::class create Example {
method foo {} {
puts "this is foo"
}
method bar {} {
puts "this is bar"
}
}
Example create example
# Modify the object to have a custom ‘unknown method’ interceptor
oo::objdefine exa... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #UNIX_Shell | UNIX Shell | function handle_error {
status=$?
# 127 is: command not found
if [[ $status -ne 127 ]]; then
return
fi
lastcmd=$(history | tail -1 | sed 's/^ *[0-9]* *//')
read cmd args <<< "$lastcmd"
echo "you tried to call $cmd"
}
# Trap errors.
trap 'handle_error' ERR |
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... | #Common_Lisp | Common Lisp | (defun split-and-reverse (str)
(labels
((iter (s lst)
(let ((s2 (string-trim '(#\space) s)))
(if s2
(let ((word-end (position #\space s2)))
(if (and word-end (< (1+ word-end) (length s2)))
(iter (subseq s2 (1+ word-end))
(con... |
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... | #Picat | Picat | go =>
S = "Big fjords vex quick waltz nymph!",
println(S),
println(rot13(S)),
println(rot13(rot13(S))),
nl.
% Rot 13 using a map
rot13(S) = S2 =>
lower(Lower),
upper(Upper),
M = create_map(Lower, Upper),
% If a char is not in a..zA..z then show it as it is.
S2 := [M.get(C,C) : C in S].
create_ma... |
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... | #PARI.2FGP | PARI/GP | oldRoman(n)={
while(n>999999,
n-=1000000;
print1("((((I))))")
);
if(n>499999,
n-=500000;
print1("I))))")
);
while(n>99999,
n-=100000;
print1("(((I)))")
);
if(n>49999,
n-=50000;
print1("I)))")
);
while(n>9999,
n-=10000;
print1("((I))")
);
if(n>4999,
n-=50... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Quackery | Quackery | [ 2dup <
if
[ dip
[ 2 * - ]
dup ]
nip dup
rot + swap ] is roman ( t p n --> t p )
[ 1 roman ] is I ( t p --> t p )
[ 5 roman ] is V ( t p --> t p )
[ 10 roman ] is X ( t p --> t p )
[ 50 roman ] is L ( t p --> t p )
[ 1... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
proc Compress(S); \Compress string using run-length encoding, & display it
char S;
int I, C0, C, N;
[I:= 0;
C0:= S(I); I:= I+1;
repeat ChOut(0, C0);
N:= 0;
re... |
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... | #AutoIt | AutoIt | #include <String.au3>
ConsoleWrite(_StringRepeat("ha", 5) & @CRLF) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Common_Lisp | Common Lisp | (defun return-three ()
3) |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Cowgol | Cowgol | include "cowgol.coh";
# In Cowgol, subroutines can simply define multiple output parameters.
sub MinMax(arr: [uint8], len: intptr): (min: uint8, max: uint8) is
min := 255;
max := 0;
while len > 0 loop
len := len - 1;
var cur := [arr];
if min > cur then min := cur; end if;
i... |
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
... | #360_Assembly | 360 Assembly | * Remove duplicate elements - 18/10/2015
REMDUP CSECT
USING REMDUP,R15 set base register
SR R6,R6 i=0
LA R8,1 k=1
LOOPK C R8,N do k=1 to n
BH ELOOPK
LR R1,R8 k
SLA R1,... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #D | D | import std.stdio;
struct S {
bool b;
void foo() {}
private void bar() {}
}
class C {
bool b;
void foo() {}
private void bar() {}
}
void printProperties(T)() if (is(T == class) || is(T == struct)) {
import std.stdio;
import std.traits;
writeln("Properties of ", T.stringof,... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Elena | Elena | import system'routines;
import system'dynamic;
import extensions;
class MyClass
{
prop int X;
prop string Y;
}
public program()
{
var o := new MyClass
{
this X := 2;
this Y := "String";
};
MyClass.__getProperties().forEach:(p)
{
console.printLine("o.",p,"=",ca... |
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... | #Arturo | Arturo | repeated?: function [text][
loop ((size text)/2)..0 'x [
if prefix? text slice text x (size text)-1 [
(x>0)? -> return slice text 0 x-1
-> return false
]
]
return false
]
strings: {
1001110011
1110111011
0010010010
1010101010
1111111111
... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #Factor | Factor | USE: see
\ integer see ! class
nl
\ dip see ! word |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64 (getsource.bas)
Sub Proc()
Print __Function__ & " is defined in " & __Path__ & "\" & __File__ & " at line " & ( __line__ - 1)
End Sub
Proc()
Sleep |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #Go | Go | package main
import (
"fmt"
"path"
"reflect"
"runtime"
)
func someFunc() {
fmt.Println("someFunc called")
}
func main() {
pc := reflect.ValueOf(someFunc).Pointer()
f := runtime.FuncForPC(pc)
name := f.Name()
file, line := f.FileLine(pc)
fmt.Println("Name of function :", nam... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #J | J | mean=:+/ %#
5!:5 <'mean'
+/ % #
5!:6 <'mean'
(+/) % #
4!:4 <'mean'
_1
4!:4 <'names'
2
2 { 4!:3 ''
┌────────────────────────────────────────────┐
│/Applications/j64-804/system/main/stdlib.ijs│
└────────────────────────────────────────────┘ |
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
| #Argile | Argile | use std, regex
(: matching :)
if "some matchable string" =~ /^some" "+[a-z]*" "+string$/
echo string matches
else
echo string "doesn't" match
(: replacing :)
let t = strdup "some allocated string"
t =~ s/a/"4"/g
t =~ s/e/"3"/g
t =~ s/i/"1"/g
t =~ s/o/"0"/g
t =~ s/s/$/g
print t
free t
(: flushing regex allocat... |
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
| #Arturo | Arturo | s: "This is a string"
if contains? s {/string$/} -> print "yes, it ends with 'string'"
replace 's {/[as]/} "x"
print 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
... | #ActionScript | ActionScript | function reverseString(string:String):String
{
var reversed:String = new String();
for(var i:int = string.length -1; i >= 0; i--)
reversed += string.charAt(i);
return reversed;
}
function reverseStringCQAlternative(string:String):String
{
return string.split('').reverse().join('');
} |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Julia | Julia | mutable struct Printer
inputpath::Channel{String}
errorpath::Channel{String}
inkremaining::Int32
reserve::Printer
name::String
function Printer(ch1, ch2, ink, name)
this = new()
this.inputpath = ch1
this.errorpath = ch2
this.inkremaining = ink
this.name = ... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Nim | Nim | import asyncdispatch, options, strutils
type
Printer = ref object
inkLevel, id: int
backup: Option[Printer]
OutOfInkException = object of IOError
proc print(p: Printer, line: string){.async.} =
if p.inkLevel <= 0:
if p.backup.isNone():
raise newException(OutOfInkException, "out of ink")
else... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Oz | Oz | declare
class Printer
attr ink:5
feat id backup
meth init(id:ID backup:Backup<=unit)
self.id = ID
self.backup = Backup
end
meth print(Line)=Msg
if @ink == 0 then
if self.backup == unit then
raise outOfInk end
else
... |
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.
| #C.23 | C# | using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 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.
| #C.2B.2B | C++ | template <typename Function>
void repeat(Function f, unsigned int n) {
for(unsigned int i=n; 0<i; i--)
f();
} |
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... | #BBC_BASIC | BBC BASIC | *RENAME input.txt output.txt
*RENAME \input.txt \output.txt
*RENAME docs. mydocs.
*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... | #Bracmat | Bracmat | ren$("input.txt"."output.txt") { 'ren' is based on standard C function 'rename()' }
ren$(docs.mydocs) { No quotes needed: names don't contain dots or colons. }
ren$("d:\\input.txt"."d:\\output.txt") { Backslash is escape character, so we need to escape it. }
ren$(@"d:\docs".@"d:\mydocs") ... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Perl | Perl | use strict;
use warnings;
my ($w, $h) = (9, 9);
my @v = map([ (0) x ($w + 1) ], 0 .. $h); # voltage
my @f = map([ (0) x ($w + 1) ], 0 .. $h); # fixed condition
my @d = map([ (0) x ($w + 1) ], 0 .. $h); # diff
my @n; # neighbors
for my $i (0 .. $h) {
push @{$n[$i][$_]}, [$i, $_ - 1] for 1 .. $w;
push @{$n[$i][$_]}... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Wren | Wren | import "io" for Stdin, Stdout
class Test {
construct new() {}
foo() { System.print("Foo called.") }
bar() { System.print("Bar called.") }
missingMethod(m) {
System.print(m)
System.write("Try and continue anyway y/n ? ")
Stdout.flush()
var reply = Stdin.readLine()
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #zkl | zkl | class C{ fcn __notFound(name){println(name," not in ",self); bar}
fcn bar{vm.arglist.println("***")}
} |
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... | #D | D | void main() {
import std.stdio, std.string, std.range, std.algorithm;
immutable 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 ----------------... |
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... | #PicoLisp | PicoLisp | (de rot13-Ch (C)
(if
(or
(member C '`(apply circ (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZ")))
(member C '`(apply circ (chop "abcdefghijklmnopqrstuvwxyz"))) )
(get @ 14)
C ) ) |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Pascal | Pascal | <@ DEFUDOLITLIT>_RO|__Transformer|<@ DEFKEYPAR>__NationalNumericID|2</@><@ LETRESCS%NNMPAR>...|1</@></@>
<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@> |
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... | #QB64 | QB64 |
SCREEN _NEWIMAGE(400, 600, 32)
CLS
Main:
'------------------------------------------------
' CALLS THE romToDec FUNCTION WITH THE ROMAN
' NUMERALS AND RETURNS ITS DECIMAL EQUIVELENT.
'
PRINT "ROMAN NUMERAL TO DECIMAL CONVERSION"
PRINT: PRINT
PRINT "MDCCIV = "; romToDec("MDCCIV") '1704
PRINT "MC... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #zkl | zkl | const MAX_LEN=250, MIN_LEN=3;
fcn compress(text){ // !empty byte/text stream -->Data (byte stream)
sink:=Data(); cnt:=Ref(0);
write:='wrap(c,n){ // helper function
while(n>MAX_LEN){
sink.write(1); sink.write(MAX_LEN); sink.write(c);
n-=MAX_LEN;
}
if(n>MIN_LEN){ sink.write(1); sink.w... |
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... | #AWK | AWK | function repeat( str, n, rep, i )
{
for( ; i<n; i++ )
rep = rep str
return rep
}
BEGIN {
print repeat( "ha", 5 )
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #D | D | import std.stdio, std.typecons, std.algorithm;
mixin template ret(string z) {
mixin({
string res;
auto r = z.split(" = ");
auto m = r[0].split(", ");
auto s = m.join("_");
res ~= "auto " ~ s ~ " = " ~ r[1] ~ ";";
foreach(i, n; m){
res ~= "auto " ~ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.