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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#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
Case "I"
n = 1
Default
n = 0
EndSelect
If (n < lastval)
arabic - n
Else
arabic + n
EndIf
lastval = n
Next
ProcedureReturn arabic
EndProcedure
If OpenConsole()
PrintN(Str(romanDec("MCMXCIX"))) ;1999
PrintN(Str(romanDec("MDCLXVI"))) ;1666
PrintN(Str(romanDec("XXV"))) ;25
PrintN(Str(romanDec("CMLIV"))) ;954
PrintN(Str(romanDec("MMXI"))) ;2011
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#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 Long, k As Long
r = Left(S, 1)
c = 1
For n = 2 To Len(S)
If r <> Mid(S, n, 1) Then
a = a & c & r
r = Mid(S, n, 1)
c = 1
Else
c = c + 1
End If
Next
length_encoding = a & c & r
End Function
Private Function length_decoding(S As String) As String
Dim F As Long, r As String, a As String
For F = 1 To Len(S)
If IsNumeric(Mid(S, F, 1)) Then
r = r & Mid(S, F, 1)
Else
a = a & String(CLng(r), Mid(S, F, 1))
r = vbNullString
End If
Next
length_decoding = a
End Function
|
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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
Task
Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
Show your output on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 I characters of S
U: String := (1+(L/I)) * T; -- repeat T so often that U'Length >= L
begin -- compare first L characers of U with S
if U(U'First .. U'First + S'Length -1) = S then
return T; -- T is a rep-string
end if;
end;
end loop;
return ""; -- no rep string;
end Find_Largest_Rep_String;
X: String := Ada.Command_Line.Argument(1);
Y: String := Find_Largest_Rep_String(X);
begin
if Y="" then
Ada.Text_IO.Put_Line("No rep-string for """ & X & """");
else
Ada.Text_IO.Put_Line("Longest rep-string for """& X &""": """& Y &"""");
end if;
end Rep_String;
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#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;
Found: out Boolean) is
Result: Pat.Match_Array (0 .. 1);
begin
Pat.Match(Compiled_Expression, Search_In, Result);
Found := not Pat."="(Result(1), Pat.No_Match);
if Found then
First := Result(1).First;
Last := Result(1).Last;
end if;
end Search_For_Pattern;
Word_Pattern: constant String := "([a-zA-Z]+)";
Str: String:= "I love PATTERN matching!";
Current_First: Positive := Str'First;
First, Last: Positive;
Found: Boolean;
begin
-- first, find all the words in Str
loop
Search_For_Pattern(Pat.Compile(Word_Pattern),
Str(Current_First .. Str'Last),
First, Last, Found);
exit when not Found;
Put_Line("<" & Str(First .. Last) & ">");
Current_First := Last+1;
end loop;
-- second, replace "PATTERN" in Str by "pattern"
Search_For_Pattern(Pat.Compile("(PATTERN)"), Str, First, Last, Found);
Str := Str(Str'First .. First-1) & "pattern" & Str(Last+1 .. Str'Last);
Put_Line(Str);
end Regex;
|
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
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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() -> print(Monitor_pid, humpty_dumpty()) end ),
erlang:spawn( fun() -> print(Monitor_pid, mother_goose()) end ).
humpty_dumpty() ->
["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."].
mother_goose() ->
["Old Mother Goose,",
"When she wanted to wander,",
"Would ride through the air,",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon."].
print( Pid, Lines ) ->
io:fwrite( "Print ~p started~n", [erlang:self()] ),
print( Pid, Lines, infinity ).
print( _Pid, [], _Timeout ) -> ok;
print( Pid, [Line | T], Timeout ) ->
print_line( Pid, Line, Timeout ),
print_line_done(),
print( Pid, T, Timeout ).
print_line( Pid, Line, Timeout ) ->
Pid ! {print, Line, erlang:self()},
receive
{print, started} -> ok
after Timeout -> erlang:throw( timeout )
end.
print_line_done() ->
receive
{printer, ok} -> ok;
{printer, out_of_ink} -> erlang:throw( out_of_ink )
end.
printer( N, 0 ) ->
receive
{print, _Line, Pid} -> Pid ! {printer, out_of_ink}
end,
printer( N, 0 );
printer( N, Ink ) ->
receive
{print, Line, Pid} ->
Pid ! {printer, ok},
io:fwrite( "~p: ", [N] ),
[io:fwrite("~c", [X]) || X <- Line],
io:nl()
end,
printer( N, Ink - 1 ).
printer_monitor( Printer, Reserve ) ->
{Line, Pid} = printer_monitor_get_line(),
Result = printer_monitor_print_line( Printer, Line ),
printer_monitor_reserve( Result, Reserve, Line, Pid ),
printer_monitor( Printer, Reserve ).
printer_monitor_get_line() ->
receive
{print, Line, Pid} ->
Pid ! {print, started},
{Line, Pid}
end.
printer_monitor_print_line( Printer_pid, Line ) ->
Printer_pid ! {print, Line, erlang:self()},
receive
{printer, Result} -> Result
end.
printer_monitor_reserve( ok, _Reserve_pid, _Line, Pid ) -> Pid ! {printer, ok};
printer_monitor_reserve( out_of_ink, Reserve_pid, Line, Pid ) -> Reserve_pid ! {print, Line, Pid}.
|
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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#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 Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Wren
|
Wren
|
import "/crypto" for Ripemd160
import "/fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy cog",
"Rosetta Code"
]
for (s in strings) {
var hash = Ripemd160.digest(s)
Fmt.print("$s <== '$0s'", hash, s)
}
|
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].v := -1.0;
m[6][7].fixed := -1;
END SetBoundary;
PROCEDURE CalcDiff(VAR m,d : ARRAY OF ARRAY OF Node) : LONGREAL;
VAR
total,v : LONGREAL;
i,j,n : INTEGER;
BEGIN
total := 0.0;
FOR i:=0 TO S DO
FOR j:=0 TO S DO
v := 0.0;
n := 0;
IF i>0 THEN
v := v + m[i-1][j].v;
INC(n);
END;
IF j>0 THEN
v := v + m[i][j-1].v;
INC(n);
END;
IF i+1<S THEN
v := v + m[i+1][j].v;
INC(n);
END;
IF j+1<S THEN
v := v + m[i][j+1].v;
INC(n);
END;
v := m[i][j].v - v / LFLOAT(n);
d[i][j].v := v;
IF m[i][j].fixed=0 THEN
total := total + v*v;
END;
END;
END;
RETURN total;
END CalcDiff;
PROCEDURE Iter(m : ARRAY OF ARRAY OF Node) : LONGREAL;
VAR
d : ARRAY[0..S] OF ARRAY[0..S] OF Node;
i,j,k : INTEGER;
cur : ARRAY[0..2] OF LONGREAL;
diff : LONGREAL;
BEGIN
FOR i:=0 TO S DO
FOR j:=0 TO S DO
d[i][j] := Node{0.0,0};
END;
END;
diff := 1.0E10;
WHILE diff>1.0E-24 DO
SetBoundary(m);
diff := CalcDiff(m,d);
FOR i:=0 TO S DO
FOR j:=0 TO S DO
m[i][j].v := m[i][j].v - d[i][j].v;
END;
END;
END;
FOR i:=0 TO S DO
FOR j:=0 TO S DO
k:=0;
IF i#0 THEN INC(k) END;
IF j#0 THEN INC(k) END;
IF i<S-1 THEN INC(k) END;
IF j<S-1 THEN INC(k) END;
cur[m[i][j].fixed+1] := cur[m[i][j].fixed+1] + d[i][j].v*LFLOAT(k);
END;
END;
RETURN (cur[2]-cur[0]) / 2.0;
END Iter;
VAR
mesh : ARRAY[0..S] OF ARRAY[0..S] OF Node;
buf : ARRAY[0..32] OF CHAR;
r : LONGREAL;
pos : CARDINAL;
ok : BOOLEAN;
BEGIN
pos := 0;
r := 2.0 / Iter(mesh);
WriteString("R = ");
RealToStringFixed(r, 15,0, buf, pos, ok);
WriteString(buf);
WriteString(" ohms");
WriteLn;
ReadChar;
END ResistorMesh.
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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 main(args: Array[String]): Unit = {
val d=new DynamicTest()
d.foo()
d.bar()
d.grill()
d.ding("dong")
}
}
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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(', '));
}
}
}
var example = Example.new;
example.foo; # prints “this is foo”
example.bar; # prints “this is bar”
example.grill; # prints “tried to handle unknown method grill”
example.ding("dong"); # prints “tried to handle unknown method ding”
# prints “it had arguments: dong”
|
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); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#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(36) value "ice. in say Some ".
2 pic x(36) value "desire of tasted I've what From ".
2 pic x(36) value "fire. favor who those with hold I ".
2 pic x(36) value " ".
2 pic x(36) value "... elided paragraph last ... ".
2 pic x(36) value " ".
2 pic x(36) value "Frost Robert -----------------------".
1 redefines text-block.
2 occurs 10.
3 text-line pic x(36).
1 text-word.
2 wk-len binary pic 9(4).
2 wk-word pic x(36).
1 word-stack.
2 occurs 10.
3 word-entry.
4 word-len binary pic 9(4).
4 word pic x(36).
1 binary.
2 i pic 9(4).
2 pos pic 9(4).
2 word-stack-ptr pic 9(4).
procedure division.
perform varying i from 1 by 1
until i > 10
perform push-words
perform pop-words
end-perform
stop run
.
push-words.
move 1 to pos
move 0 to word-stack-ptr
perform until pos > 36
unstring text-line (i) delimited by all space
into wk-word count in wk-len
pointer pos
end-unstring
add 1 to word-stack-ptr
move text-word to word-entry (word-stack-ptr)
end-perform
.
pop-words.
perform varying word-stack-ptr from word-stack-ptr
by -1
until word-stack-ptr < 1
move word-entry (word-stack-ptr) to text-word
display wk-word (1:wk-len) space with no advancing
end-perform
display space
.
end program rev-word.
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#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:
IF i_i - idecimal[ ipos ] >= 0 THEN
ASSIGN
cresult = cresult + croman[ ipos ]
i_i = i_i - idecimal[ ipos ]
.
ELSE IF ipos < EXTENT( croman ) - 1 AND i_i - ( idecimal[ ipos ] - idecimal[ ipos + 2 ] ) >= 0 THEN
ASSIGN
cresult = cresult + croman[ ipos + 2 ] + croman[ ipos ]
i_i = i_i - ( idecimal[ ipos ] - idecimal[ ipos + 2 ] )
ipos = ipos + 1
.
ELSE
ipos = ipos + 1.
END.
RETURN cresult.
END FUNCTION. /* encodeRoman */
MESSAGE
1990 encodeRoman( 1990 ) SKIP
2008 encodeRoman( 2008 ) SKIP
2000 encodeRoman( 2000 ) SKIP
1666 encodeRoman( 1666 ) SKIP
VIEW-AS ALERT-BOX.
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#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 MMVIII MDCLXVI'.split():
print( r, decode(r) )
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#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 max 127
if (#2 > 1 || #1 > 127) {
Del_Char(#2)
Ins_Char(#2 | 128) // run length (high bit set)
Ins_Char(#1) // character
} else { // single ASCII char
Char // skip
}
}
Return
:RL_DECODE:
BOF
While (!At_EOF) {
#2 = Cur_Char
if (#2 > 127) { // is this run length?
#1 = Cur_Char(1) // #1 = character value
Del_Char(2)
Ins_Char(#1, COUNT, #2 & 127)
} else { // single ASCII char
Char
}
}
Return
|
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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 that its arguments support addition and subtraction in any way
add_sub = proc [T,U,V,W: type] (a: T, b: U) returns (V, W)
signals (overflow)
where T has add: proctype (T,U) returns (V) signals (overflow),
sub: proctype (T,U) returns (W) signals (overflow)
return (a+b, a-b) resignal overflow
end add_sub
% And actually using it
start_up = proc ()
add_sub_int = add_sub[int,int,int,int] % boring, but does what you'd expect
po: stream := stream$primary_output()
% returning two values from the function
sum, diff: int := add_sub_int(33, 12)
% print out both
stream$putl(po, "33 + 12 = " || int$unparse(sum))
stream$putl(po, "33 - 12 = " || int$unparse(diff))
end start_up
|
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 characters.
set("${first}" "${f}" PARENT_SCOPE)
set("${last}" "${g}" PARENT_SCOPE)
endfunction(firstlast)
firstlast("Rosetta Code" begin end)
message(STATUS "begins with ${begin}, ends with ${end}")
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
Task
Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
Show your output on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 #
STRING str = input[ AT 1 ];
# work backwards from half the input string looking for a rep-string #
FOR string length FROM UPB str OVER 2 BY -1 TO 1
WHILE
STRING left substring = str[ 1 : string length ];
# if the left substgring repeated a sufficient number of times #
# (truncated on the right) is equal to the original string, then #
# we have found the longest rep-string #
STRING repeated string = ( left substring
* ( ( UPB str OVER string length ) + 1 )
)[ 1 : UPB str ];
IF str = repeated string
THEN
# found a rep-string #
result := left substring;
FALSE
ELSE
# not a rep-string, keep looking #
TRUE
FI
DO
SKIP
OD;
result
END; # longest rep string #
# test the longest rep string procedure #
main:
(
[]STRING tests = ( "1001110011"
, "1110111011"
, "0010010010"
, "1010101010"
, "1111111111"
, "0100101101"
, "0100100"
, "101"
, "11"
, "00"
, "1"
);
FOR test number FROM LWB tests TO UPB tests
DO
STRING rep string = longest rep string( tests[ test number ] );
print( ( tests[ test number ]
, ": "
, IF rep string = ""
THEN "no rep string"
ELSE "longest rep string: """ + rep string + """"
FI
, newline
)
)
OD
)
|
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 THEN printf(($gl$, str)) FI;
|
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
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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, ?backup:Printer) =
let mutable ink = 5
// the actual printing logic as a private function
let print line =
if ink > 0 then
printf "%d: " id
Seq.iter (printf "%c") line
printf "\n"
ink <- ink - 1
else
match backup with
| Some p -> p.Print line
| None -> raise OutOfInk
// use a MailboxProcessor to process commands asynchronously;
// if an exception occurs, we return it to the calling thread
let agent = MailboxProcessor.Start( fun inbox ->
async {
while true do
let! Message (command, replyChannel) = inbox.Receive()
try
match command with
| Print line -> print line
replyChannel.Reply None
with
| ex -> replyChannel.Reply (Some ex)
})
// public printing method:
// send Print command and propagate exception if one occurs
member x.Print line =
match agent.PostAndReply( fun replyChannel -> Message (Print line, replyChannel) ) with
| None -> ()
| Some ex -> raise ex
open System.Threading
do
let main = new Printer(id=1, backup=new Printer(id=2))
(new Thread(fun () ->
try
main.Print "Humpty Dumpty sat on a wall."
main.Print "Humpty Dumpty had a great fall."
main.Print "All the king's horses and all the king's men"
main.Print "Couldn't put Humpty together again."
with
| OutOfInk -> printfn " Humpty Dumpty out of ink!"
)).Start()
(new Thread(fun () ->
try
main.Print "Old Mother Goose"
main.Print "Would ride through the air"
main.Print "On a very fine gander."
main.Print "Jack's mother came in,"
main.Print "And caught the goose soon,"
main.Print "And mounting its back,"
main.Print "Flew up to the moon."
with
| OutOfInk -> printfn " Mother Goose out of ink!"
)).Start()
Console.ReadLine() |> ignore
|
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("inside odd %d\n",n)
}
}
|
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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#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 int](m,: Mesh[H, W]; d: var Mesh[H, W]): float =
for i in 0..<H:
for j in 0..<W:
var v = 0.0
var n = 0
if i > 0:
v += m[i - 1][j].v
inc n
if j > 0:
v += m[i][j - 1].v
inc n
if i + 1 < m.H:
v += m[i + 1][j].v
inc n
if j + 1 < m.W:
v += m[i][j + 1].v
inc n
v = m[i][j].v - v / n.toFloat
d[i][j].v = v
if m[i][j].fixed == nodeFree:
result += v * v
func iter[H, W: static int](m: var Mesh[H, W]): float =
var
d: Mesh[H, W]
cur: array[NodeKind, float]
diff = 1e10
while diff > 1e-24:
m.setBoundary()
diff = calcDiff(m, d)
for i in 0..<H:
for j in 0..<W:
m[i][j].v -= d[i][j].v
for i in 0..<H:
for j in 0..<W:
var k = 0
if i != 0: inc k
if j != 0: inc k
if i < m.H - 1: inc k
if j < m.W - 1: inc k
cur[m[i][j].fixed] += d[i][j].v * k.toFloat
result = (cur[nodeA] - cur[nodeB]) / 2
when isMainModule:
var mesh: Mesh[S, S]
let r = 2 / mesh.iter()
echo "R = ", r
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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:
[| :key :value |
command ; ' -' ; (key as: String) allButFirst allButLast ; ' ' ; (value as: String)]].
message selector isKeywordSelector ifTrue:
[| keywords args |
keywords: ((message selector as: String) splitWith: $:).
command ; keywords first.
keywords size = 1 ifTrue: "Read a string or array of arguments."
[args: message arguments second.
(args is: String) ifTrue: [command ; ' ' ; args]
ifFalse: [args do: [| :arg | command ; ' ' ; arg]]]]] writingAs: String)
ifNil: [resend] ifNotNilDo: [| :cmd | [Platform run: cmd]]]
].
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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 := CatchThemAll new.
a foo.
a bar.
a weCanDoIt.
a theyCanToo: 'eat' and: 'walk'.
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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 the method to my respected superclass".postln;
super.doesNotUnderstand(selector, args)
}
}
|
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); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#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(/\s/).reverse().join ' ').join '\n'
console.log reverseString(strReversed)
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#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 div 100}#{ToRoman X mod 100}
elseif X >= 10 then {Digit &X &L &C X div 10}#{ToRoman X mod 10}
else {Digit &I &V &X X}
end
end
in
{ForAll {Map [1999 25 944] ToRoman} System.showInfo}
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#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" THEN n = 5
IF x$ = "I" THEN n = 1
IF n < preNum THEN num = num - n ELSE num = num + n
preNum = n
NEXT i
romToDec = num
END FUNCTION
!Testing
PRINT "MCMXCIX = "; romToDec("MCMXCIX") '1999
PRINT "MDCLXVI = "; romToDec("MDCLXVI") '1666
PRINT "XXV = "; romToDec("XXV") '25
PRINT "CMLIV = "; romToDec("CMLIV") '954
PRINT "MMXI = "; romToDec("MMXI") '2011
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#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 {
e = e + count.toString + curr
curr = s[i]
count = 1
}
i = i + 1
}
return e + count.toString + curr
}
var decode = Fn.new { |e|
if (e == "") return e
var letters = Pattern.matchesText(p.findAll(e))
var numbers = p.splitAll(e)[0..-2].map { |s| Num.fromString(s) }.toList
return (0...letters.count).reduce("") { |acc, i| acc + letters[i]*numbers[i] }.join()
}
var strings = [
"AA",
"RROSETTAA",
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
]
for (s in strings) {
System.print("Original text : %(s)")
var e = encode.call(s)
System.print("Encoded text : %(e)")
var d = decode.call(e)
System.print("Decoded text : %(d)")
System.print("Original = decoded : %(s == d)\n")
}
|
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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 c usage float-short.
==
==:record-item:== BY ==
01 master.
05 ma usage binary-long.
05 mb pic x(10).
05 mc usage float-short.
==.
data division.
working-storage section.
:linked-items:
:record-item:
procedure division.
sample-main.
move 41 to a
move "aaaaabbbbb" to b
move function e to c
display "Original: " a ", " b ", " c
call "subprogram" using a b c
display "Modified: " a ", " b ", " c
move multiples() to master
display "Multiple: " ma ", " mb ", " mc
goback.
end program multiple-values.
*> subprogram
identification division.
program-id. subprogram.
data division.
linkage section.
:linked-items:
procedure division using a b c.
add 1 to a
inspect b converting "a" to "b"
divide 2 into c
goback.
end program subprogram.
*> multiples function
identification division.
function-id. multiples.
data division.
linkage section.
:record-item:
procedure division returning master.
move 84 to ma
move "multiple" to mb
move function pi to mc
goback.
end function multiples.
|
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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#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 GetPropertyValues(t, flags)) {
Console.WriteLine(prop);
}
foreach (var field in GetFieldValues(t, flags)) {
Console.WriteLine(field);
}
}
public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
from p in typeof(T).GetProperties(flags)
where p.GetIndexParameters().Length == 0 //To filter out indexers
select (p.Name, p.GetValue(obj, null));
public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
class TestClass
{
private int privateField = 7;
public int PublicNumber { get; } = 4;
private int PrivateNumber { get; } = 2;
}
}
|
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
Task
Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
Show your output on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
Task
Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
Show your output on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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
-- cycleReport :: String -> [String]
on cycleReport(xs)
set reps to repCycles(xs)
if isNull(reps) then
{xs, "(n/a)"}
else
{xs, item -1 of reps}
end if
end cycleReport
---------------------------TEST----------------------------
on run
set samples to {"1001110011", "1110111011", "0010010010", ¬
"1010101010", "1111111111", "0100101101", "0100100", ¬
"101", "11", "00", "1"}
unlines(cons("Longest cycle:" & linefeed, ¬
map(intercalate(" -> "), ¬
map(cycleReport, samples))))
end run
---------------------GENERIC FUNCTIONS---------------------
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- cons :: a -> [a] -> [a]
on cons(x, xs)
{x} & xs
end cons
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- inits :: [a] -> [[a]]
-- inits :: String -> [String]
on inits(xs)
script elemInit
on |λ|(_, i, xs)
items 1 thru i of xs
end |λ|
end script
script charInit
on |λ|(_, i, xs)
text 1 thru i of xs
end |λ|
end script
if class of xs is string then
{""} & map(charInit, xs)
else
{{}} & map(elemInit, xs)
end if
end inits
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText)
script
on |λ|(xs)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to xs as text
set my text item delimiters to dlm
return strJoined
end |λ|
end script
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- isNull :: [a] -> Bool
on isNull(xs)
xs = {}
end isNull
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- quot :: Integral a => a -> a -> a
on quot(n, m)
n div m
end quot
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- tail :: [a] -> [a]
on tail(xs)
if length of xs > 1 then
items 2 thru -1 of xs
else
{}
end if
end tail
-- take :: Int -> [a] -> [a]
on take(n, xs)
if class of xs is string then
if n > 0 then
text 1 thru min(n, length of xs) of xs
else
""
end if
else
if n > 0 then
items 1 thru min(n, length of xs) of xs
else
{}
end if
end if
end take
-- takeCycle :: Int -> [a] -> [a]
on takeCycle(n, xs)
set lng to length of xs
if lng ≥ n then
set cycle to xs
else
set cycle to concat(replicate((n div lng) + 1, xs))
end if
if class of xs is string then
items 1 thru n of cycle as string
else
items 1 thru n of cycle
end if
end takeCycle
-- unlines :: [String] -> String
on unlines(xs)
|λ|(xs) of intercalate(linefeed)
end unlines
|
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 converts hex to ASCII,
; then prints the high nibble then the low.
lda $00 ;low byte of the starting address of the source
jsr PrintHex
jsr NewLine ;unimplemented new line routine
loop:
lda ($00),y
cmp #$60
beq Terminated
jsr PrintHex
jmp loop
Terminated:
jsr PrintHex ;print the last instruction of the routine.
rts
|
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 course"},reg match, // execute
println
reg free(T1) // free pointer to regular expression compiled.
exit(0)
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#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
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 iratA")
RETURN
|
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 air,
On a very fine gander.
Jack's mother came in,
And caught the goose soon,
And mounting its back,
Flew up to the moon.`
func main() {
reservePrinter := startMonitor(newPrinter(5), nil)
mainPrinter := startMonitor(newPrinter(5), reservePrinter)
var busy sync.WaitGroup
busy.Add(2)
go writer(mainPrinter, "hd", hdText, &busy)
go writer(mainPrinter, "mg", mgText, &busy)
busy.Wait()
}
// printer is a type representing an abstraction of a physical printer.
// It is a type defintion for a function that takes a string to print
// and returns an error value, (hopefully usually nil, meaning no error.)
type printer func(string) error
// newPrinter is a constructor. The parameter is a quantity of ink. It
// returns a printer object encapsulating the ink quantity.
// Note that this is not creating the monitor, only the object serving as
// a physical printer by writing to standard output.
func newPrinter(ink int) printer {
return func(line string) error {
if ink == 0 {
return eOutOfInk
}
for _, c := range line {
fmt.Printf("%c", c)
}
fmt.Println()
ink--
return nil
}
}
var eOutOfInk = errors.New("out of ink")
// For the language task, rSync is a type used to approximate the Ada
// rendezvous mechanism that includes the caller waiting for completion
// of the callee. For this use case, we signal completion with an error
// value as a response. Exceptions are not idiomatic in Go and there is
// no attempt here to model the Ada exception mechanism. Instead, it is
// idomatic in Go to return error values. Sending an error value on a
// channel works well here to signal completion. Go unbuffered channels
// provide synchronous rendezvous, but call and response takes two channels,
// which are bundled together here in a struct. The channel types are chosen
// to mirror the parameter and return types of "type printer" defined above.
// The channel types here, string and error are both "reference types"
// in Go terminology. That is, they are small things containing pointers
// to the actual data. Sending one on a channel does not involve copying,
// or much less marshalling string data.
type rSync struct {
call chan string
response chan error
}
// "rendezvous Print" requested by use case task.
// For the language task though, it is implemented here as a method on
// rSync that sends its argument on rSync.call and returns the result
// received from rSync.response. Each channel operation is synchronous.
// The two operations back to back approximate the Ada rendezvous.
func (r *rSync) print(data string) error {
r.call <- data // blocks until data is accepted on channel
return <-r.response // blocks until response is received
}
// monitor is run as a goroutine. It encapsulates the printer passed to it.
// Print requests are received through the rSync object "entry," named entry
// here to correspond to the Ada concept of an entry point.
func monitor(hardPrint printer, entry, reserve *rSync) {
for {
// The monitor goroutine will block here waiting for a "call"
// to its "entry point."
data := <-entry.call
// Assuming the call came from a goroutine calling rSync.print,
// that goroutine is now blocked, waiting for this one to send
// a response.
// attempt output
switch err := hardPrint(data); {
// consider return value from attempt
case err == nil:
entry.response <- nil // no problems
case err == eOutOfInk && reserve != nil:
// Requeue to "entry point" of reserve printer monitor.
// Caller stays blocked, and now this goroutine blocks until
// it gets a response from the reserve printer monitor.
// It then transparently relays the response to the caller.
entry.response <- reserve.print(data)
default:
entry.response <- err // return failure
}
// The response is away. Loop, and so immediately block again.
}
}
// startMonitor can be seen as an rSync constructor. It also
// of course, starts the monitor for which the rSync serves as entry point.
// Further to the langauge task, note that the channels created here are
// unbuffered. There is no buffer or message box to hold channel data.
// A sender will block waiting for a receiver to accept data synchronously.
func startMonitor(p printer, reservePrinter *rSync) *rSync {
entry := &rSync{make(chan string), make(chan error)}
go monitor(p, entry, reservePrinter)
return entry
}
// Two writer tasks are started as goroutines by main. They run concurrently
// and compete for printers as resources. Note the call to "rendezvous Print"
// as requested in the use case task and compare the syntax,
// Here: printMonitor.print(line);
// Ada solution: Main.Print ("string literal");
func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {
for _, line := range strings.Split(text, "\n") {
if err := printMonitor.print(line); err != nil {
fmt.Printf("**** writer task %q terminated: %v ****\n", id, err)
break
}
}
busy.Done()
}
|
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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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, node)++;
G(node, node + 1) = -1;
end
end
end
current = sparse(NN, 1);
Ar = 2; Ac = 2; A = Ac + N*( Ar - 1 );
Br = 7; Bc = 8; B = Bc + N*( Br - 1 );
current( A ) = -1;
current( B ) = +1;
voltage = G \ current;
VA = voltage( A );
VB = voltage( B );
full( abs( VA - VB ) )
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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 example {
method unknown {name args} {
puts "tried to handle unknown method \"$name\""
if {[llength $args]} {
puts "it had arguments: $args"
}
}
}
# Show off what we can now do...
example foo; # prints “this is foo”
example bar; # prints “this is bar”
example grill; # prints “tried to handle unknown method "grill"”
example ding dong; # prints “tried to handle unknown method "ding"”
# prints “it had arguments: dong”
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#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))
(cons (subseq s2 0 word-end) lst))
(cons s2 lst)))
lst))))
(iter str NIL)))
(defparameter *poem*
"---------- 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 -----------------------")
(with-input-from-string (s *poem*)
(loop for line = (read-line s NIL)
while line
do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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_map(Lower, Upper) = M =>
M = new_map(),
Len = Lower.length,
LDiv := Lower.length div 2,
foreach(I in 1..Len)
II = (LDiv+I) mod Len,
if II == 0 then II := Len end,
M.put(Upper[I],Upper[II]),
M.put(Lower[I],Lower[II])
end.
lower("abcdefghijklmnopqrstuvwxyz").
upper("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#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-=5000;
print1("I))")
);
while(n>999,
n-=1000;
print1("(I)")
);
if(n>499,
n-=500;
print1("I)")
);
while(n>99,
n-=100;
print1("C")
);
if(n>49,
n-=50;
print1("L");
);
while(n>9,
n-=10;
print1("X")
);
if(n>4,
n-=5;
print1("V");
);
while(n,
n--;
print1("I")
);
print()
};
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#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 )
[ 100 roman ] is C ( t p --> t p )
[ 500 roman ] is D ( t p --> t p )
[ 1000 roman ] is M ( t p --> t p )
[ 0 1000 rot
$ "" swap
witheach
[ space join
join ]
quackery
drop ] is ->arabic ( $ --> n )
$ " MCMXC" dup echo$ say " = " ->arabic echo cr
$ " MMVIII" dup echo$ say " = " ->arabic echo cr
$ "MDCLXVI" dup echo$ say " = " ->arabic echo cr
cr
$ "I MIX VIVID MILD MIMIC"
dup echo$ say " = " ->arabic echo cr
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#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;
repeat C:= S(I); I:= I+1;
N:= N+1;
until C#C0;
if N>1 then IntOut(0, N-1);
C0:= C;
until C=0;
]; \Compress
proc Expand(S); \Expand compressed string, and display it
char S;
int I, C0, C, N;
[I:= 0;
C0:= S(I); I:= I+1;
repeat ChOut(0, C0);
C:= S(I); I:= I+1;
if C>=^1 & C<=^9 then
[N:= 0;
while C>=^0 & C<=^9 do
[N:= N*10 + C-^0;
C:= S(I); I:= I+1;
];
while N do [ChOut(0, C0); N:= N-1];
];
C0:= C;
until C=0;
]; \Expand
[Compress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW");
CrLf(0);
Expand("W11BW11B2W23BW13"); CrLf(0);
]
|
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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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;
if max < cur then max := cur; end if;
arr := @next arr;
end loop;
# Values are also returned automatically.
end sub;
# Example of usage:
var nums: uint8[] := {23, 65, 33, 12, 95, 5, 32, 91, 135, 25, 8};
var least: uint8;
var most: uint8;
# Accept two output parameters from a function
(least, most) := MinMax(&nums[0], @sizeof nums);
print("Min: "); print_i8(least); print_nl();
print("Max: "); print_i8(most); print_nl();
|
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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#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,2
L R9,T-4(R1) e=t(k)
LR R7,R8 k
BCTR R7,0 j=k-1
LOOPJ C R7,=F'1' do j=k-1 to 1 by -1
BL ELOOPJ
LR R1,R7 j
SLA R1,2
L R2,T-4(R1) t(j)
CR R9,R2 if e=t(j) then goto iter
BE ITER
BCTR R7,0 j=j-1
B LOOPJ
ELOOPJ LA R6,1(R6) i=i+1
LR R1,R6 i
SLA R1,2
ST R9,T-4(R1) t(i)=e
ITER LA R8,1(R8) k=k+1
B LOOPK
ELOOPK LA R10,PG pgi=@pg
LA R8,1 k=1
LOOP CR R8,R6 do k=1 to i
BH ELOOP
LR R1,R8 k
SLA R1,2
L R2,T-4(R1) t(k)
XDECO R2,PG+80 edit t(k)
MVC 0(3,R10),PG+89 output t(k) on 3 char
LA R10,3(R10) pgi=pgi+3
LA R8,1(R8) k=k+1
B LOOP
ELOOP XPRNT PG,80 print buffer
XR R15,R15 set return code
BR R14 return to caller
T DC F'6',F'6',F'1',F'5',F'6',F'2',F'1',F'7',F'5',F'22'
DC F'4',F'19',F'1',F'1',F'6',F'8',F'9',F'10',F'11',F'12'
N DC A((N-T)/4) number of T items
PG DC CL92' '
YREGS
END REMDUP
|
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, ':');
foreach (m; __traits(allMembers, T)) {
static if (__traits(compiles, (typeof(__traits(getMember, T, m))))) {
alias typeof(__traits(getMember, T, m)) ti;
static if (!isFunction!ti) {
writeln(" ", m);
}
}
}
}
void main() {
printProperties!S;
printProperties!C;
}
|
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,"=",cast MessageName(p).getPropertyValue(o))
}
}
|
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
Task
Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice).
There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
Show your output on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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
0100101101
0100100
101
11
00
1
}
loop split.lines strings 'str [
rep: repeated? str
if? false = rep ->
print [str "-> *not* a rep-string"]
else ->
print [str "->" rep "( length:" size rep ")"]
]
|
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 :", name)
fmt.Println("Name of file :", path.Base(file))
fmt.Println("Line number :", line)
}
|
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 allocations :)
uninit regex
check mem leak; use dbg (:optional:)
|
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
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 = name
this.reserve = this
this
end
end
function lineprintertask(printer)
while true
line = take!(printer.inputpath)
linesprinted = 0
if(printer.inkremaining < 1)
if(printer.reserve == printer)
put!(printer.errorpath, "Error: printer $(printer.name) out of ink")
else
put!(printer.reserve.inputpath, line)
end
else
println(line)
printer.inkremaining -= 1
end
end
end
function schedulework(poems)
printerclose(printer) = (close(printer.inputpath); close(printer.errorpath))
reserveprinter = Printer(Channel{String}(1), Channel{String}(10), 5, "Reserve")
mainprinter = Printer(Channel{String}(1), Channel{String}(10), 5, "Main")
mainprinter.reserve = reserveprinter
@async(lineprintertask(mainprinter))
@async(lineprintertask(reserveprinter))
printers = [mainprinter, reserveprinter]
activeprinter = 1
@sync(
for poem in poems
activeprinter = (activeprinter % length(printers)) + 1
@async(
for line in poem
put!(printers[activeprinter].inputpath, line)
end)
end)
for p in printers
while isready(p.errorpath)
println(take!(p.errorpath))
end
printerclose(p)
end
end
const humptydumpty = ["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."]
const oldmothergoose = ["Old Mother Goose,",
"When she wanted to wander,",
"Would ride through the air,",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon."]
schedulework([humptydumpty, oldmothergoose])
|
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:
await p.backup.get().print(line)
else:
p.inkLevel-=1
stdout.writeLine("$1:$2".format(p.id, line))
await sleepAsync(100)
proc newPrinter(inkLevel, id: int, backup: Option[Printer]): Printer =
new(result)
result.inkLevel = inkLevel
result.id = id
result.backup = backup
proc print(p: Printer, msg: seq[string]){.async.} =
for line in msg:
try:
await p.print(line)
except OutOfInkException as e:
echo("out of ink")
break
const
humptyLines = @[
"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.",
]
gooseLines = @[
"Old Mother Goose,",
"When she wanted to wander,",
"Would ride through the air,",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon.",
]
proc main(){.async.} =
var
reservePrinter = newPrinter(5, 2, none(Printer))
mainPrinter = newPrinter(5, 1, some(reservePrinter))
await mainPrinter.print(gooseLines) and mainPrinter.print(humptyLines)
waitFor main()
|
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
{self.backup Msg}
end
else
{System.printInfo self.id#": "}
for C in Line do
{System.printInfo [C]}
end
{System.printInfo "\n"}
ink := @ink - 1
end
end
end
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#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);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
|
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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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 systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#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") { @ used as syntactic sugar as in C# for inhibiting escape. }
|
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][$_]}, [$i, $_ + 1] for 0 .. $w - 1;
}
for my $j (0 .. $w) {
push @{$n[$_][$j]}, [$_ - 1, $j] for 1 .. $h;
push @{$n[$_][$j]}, [$_ + 1, $j] for 0 .. $h - 1;
}
sub set_boundary {
$f[1][1] = 1; $f[6][7] = -1;
$v[1][1] = 1; $v[6][7] = -1;
}
sub calc_diff {
my $total_diff;
for my $i (0 .. $h) {
for my $j (0 .. $w) {
my ($p, $v) = $n[$i][$j];
$v += $v[$_->[0]][$_->[1]] for @$p;
$d[$i][$j] = $v = $v[$i][$j] - $v / scalar(@$p);
$total_diff += $v * $v unless $f[$i][$j];
}
}
$total_diff;
}
sub iter {
my $diff = 1;
while ($diff > 1e-15) {
set_boundary();
$diff = calc_diff();
#print "error^2: $diff\n"; # un-comment to see slow convergence
for my $i (0 .. $h) {
for my $j (0 .. $w) {
$v[$i][$j] -= $d[$i][$j];
}
}
}
my @current = (0) x 3;
for my $i (0 .. $h) {
for my $j (0 .. $w) {
$current[ $f[$i][$j] ] +=
$d[$i][$j] * scalar(@{$n[$i][$j]});
}
}
return ($current[1] - $current[-1]) / 2;
}
printf "R = %.6f\n", 2 / iter();
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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()
if (reply != "y" && reply != "Y") {
Fiber.abort("Decided to abort due to missing method.")
}
}
}
var test = Test.new()
var f = Fiber.new {
test.foo()
test.bar()
test.baz()
}
f.try()
var err = f.error
if (err) {
if (err.startsWith("Test does not implement")) {
test.missingMethod(err)
} else {
Fiber.abort(err) // rethrow other errors
}
}
System.print("OK, continuing.")
|
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 defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#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); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#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 -----------------------";
writefln("%(%-(%s %)\n%)",
text.splitLines.map!(r => r.split.retro));
}
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#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 "MCMXC = "; romToDec("MCMXC") '1990
PRINT "MMVIII = "; romToDec("MMVIII") '2008
PRINT "MDCLXVI = "; romToDec("MDCLXVI") '1666
PRINT: PRINT
PRINT "Here are other solutions not from the TASK:"
PRINT "MCMXCIX = "; romToDec("MCMXCIX") '1999
PRINT "XXV = "; romToDec("XXV") '25
PRINT "CMLIV = "; romToDec("CMLIV") '954
PRINT "MMXI = "; romToDec("MMXI") '2011
PRINT "MMIIIX = "; romToDec("MMIIIX") '2011
PRINT: PRINT
PRINT "2011 can be written either as MMXI or MMIIIX"
PRINT "With the IX = 9, MMIIIX is also 2011."
PRINT "2011 IS CORRECT (MM=2000 + II = 2 + IX = 9)"
END
FUNCTION romToDec (roman AS STRING)
'------------------------------------------------------
' FUNCTION THAT CONVERTS ANY ROMAN NUMERAL TO A DECIMAL
'
prenum = 0: num = 0
LN = LEN(roman)
FOR i = LN TO 1 STEP -1
x$ = MID$(roman, i, 1)
n = 1000
SELECT CASE x$
CASE "M": n = n / 1
CASE "D": n = n / 2
CASE "C": n = n / 10
CASE "L": n = n / 20
CASE "X": n = n / 100
CASE "V": n = n / 200
CASE "I": n = n / n
CASE ELSE: n = 0
END SELECT
IF n < prenum THEN num = num - n ELSE num = num + n
prenum = n
NEXT i
romToDec = num
END FUNCTION
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#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.write(n); sink.write(c); }
else { do(n) { sink.write(c); } }
};
text.reduce('wrap(a,b){
if(a==b) cnt.inc();
else{ write(a,cnt.value); cnt.set(1); }
b
},text[0]) : write(_,cnt.value);
sink;
}
|
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 related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#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 " ~ n ~ " = " ~ s ~ "[" ~ i.to!string ~ "];\n";
}
return res;
}());
}
auto addSub(T)(T x, T y) {
return tuple(x + y, x - y);
}
void main() {
mixin ret!q{ a, b = addSub(33, 12) };
writefln("33 + 12 = %d\n33 - 12 = %d", a, b);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.