task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Repeat_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
|
#ActionScript
|
ActionScript
|
function repeatString(string:String, numTimes:uint):String
{
var output:String = "";
for(var i:uint = 0; i < numTimes; i++)
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.
|
#AutoIt
|
AutoIt
|
Func _AddSub($iX, $iY)
Local $aReturn[2]
$aReturn[0] = $iX + $iY
$aReturn[1] = $iX - $iY
Return $aReturn
EndFunc
|
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.
|
#11l
|
11l
|
F repeat(f, n)
L 1..n
f()
F procedure()
print(‘Example’)
repeat(procedure, 3)
|
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.
|
#PicoLisp
|
PicoLisp
|
(de *R160-R1 . (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
8 5 14 2 11 7 16 4 13 1 10 6 3 15 12 9
4 11 15 5 10 16 9 2 3 8 1 7 14 12 6 13
2 10 12 11 1 9 13 5 14 4 8 16 15 6 7 3
5 1 6 10 8 13 3 11 15 2 4 9 12 7 16 14 .))
(de *R160-R2 . (6 15 8 1 10 3 12 5 14 7 16 9 2 11 4 13
7 12 4 8 1 14 6 11 15 16 9 13 5 10 2 3
16 6 2 4 8 15 7 10 12 9 13 3 11 1 5 14
9 7 5 2 4 12 16 1 6 13 3 14 10 8 11 15
13 16 11 5 2 6 9 8 7 3 14 15 1 4 10 12 .))
(de *R160-S1 . (11 14 15 12 5 8 7 9 11 13 14 15 6 7 9 8
7 6 8 13 11 9 7 15 7 12 15 9 11 7 13 12
11 13 6 7 14 9 13 15 14 8 13 6 5 12 7 5
11 12 14 15 14 15 9 8 9 14 5 6 8 6 5 12
9 15 5 11 6 8 13 12 5 12 13 14 11 8 5 6 .))
(de *R160-S2 . (8 9 9 11 13 15 15 5 7 7 8 11 14 14 12 6
9 13 15 7 12 8 9 11 7 7 12 7 6 15 13 11
9 7 15 11 8 6 6 14 12 13 5 14 13 13 7 5
15 5 8 11 14 14 6 14 6 9 12 9 12 5 15 8
8 5 12 9 12 5 14 6 8 13 6 5 15 13 11 11 .))
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
(x| N `(hex "FFFFFFFF")) )
(de add32 @
(mod32 (pass +)) )
(de leftRotate (X C)
(| (mod32 (>> (- C) X)) (>> (- 32 C) X)) )
(de ripemd160 (Str)
(let Len (length Str)
(setq Str
(conc
(need
(- 8 (* 64 (/ (+ Len 1 8 63) 64)))
(conc
(mapcar char (chop Str))
(cons `(hex "80")) )
0 )
(make
(setq Len (* 8 Len))
(do 8
(link (& Len 255))
(setq Len (>> 8 Len )) ) ) ) ) )
(let
(H0 `(hex "67452301")
H1 `(hex "EFCDAB89")
H2 `(hex "98BADCFE")
H3 `(hex "10325476")
H4 `(hex "C3D2E1F0") )
(while Str
(let
(A1 H0 B1 H1 C1 H2 D1 H3 E1 H4
A2 H0 B2 H1 C2 H2 D2 H3 E2 H4
W (make
(do 16
(link
(apply |
(mapcar >> (0 -8 -16 -24) (cut 4 'Str)) ) ) ) ) )
(use (Func1 Func2 Hex1 Hex2)
(for I 80
(cond
((>= 16 I)
(setq
Func1 '(x| B1 C1 D1)
Func2 '(x| B2 (| C2 (not32 D2)))
Hex1 0
Hex2 `(hex "50A28BE6") ) )
((>= 32 I)
(setq
Func1 '(| (& B1 C1) (& (not32 B1) D1))
Func2 '(| (& B2 D2) (& C2 (not32 D2)))
Hex1 `(hex "5A827999")
Hex2 `(hex "5C4DD124") ) )
((>= 48 I)
(setq
Func1 '(x| (| B1 (not32 C1)) D1)
Func2 '(x| (| B2 (not32 C2)) D2)
Hex1 `(hex "6ED9EBA1")
Hex2 `(hex "6D703EF3") ) )
((>= 64 I)
(setq
Func1 '(| (& B1 D1) (& C1 (not32 D1)))
Func2 '(| (& B2 C2) (& (not32 B2) D2))
Hex1 `(hex "8F1BBCDC")
Hex2 `(hex "7A6D76E9") ) )
(T
(setq
Func1 '(x| B1 (| C1 (not32 D1)))
Func2 '(x| B2 C2 D2)
Hex1 `(hex "A953FD4E")
Hex2 0 ) ) )
(setq
Tmp1
(add32
(leftRotate
(add32
A1
(eval Func1)
(get W (pop '*R160-R1))
Hex1 )
(pop '*R160-S1) )
E1 )
Tmp2
(add32
(leftRotate
(add32
A2
(eval Func2)
(get W (pop '*R160-R2))
Hex2 )
(pop '*R160-S2) )
E2 )
A1 E1
E1 D1
D1 (leftRotate C1 10)
C1 B1
B1 Tmp1
A2 E2
E2 D2
D2 (leftRotate C2 10)
C2 B2
B2 Tmp2 ) ) )
(setq
Tmp (add32 H1 C1 D2)
H1 (add32 H2 D1 E2)
H2 (add32 H3 E1 A2)
H3 (add32 H4 A1 B2)
H4 (add32 H0 B1 C2)
H0 Tmp ) ) )
(make
(for N (list H0 H1 H2 H3 H4)
(do 4
(link (& N 255))
(setq N (>> 8 N)) ) ) ) ) )
(let Str "Rosetta Code"
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(ripemd160 Str) ) ) )
(println
(pack
(mapcar
'((B) (pad 2 (hex B)))
(native
"libcrypto.so"
"RIPEMD160"
'(B . 20)
Str
(length Str)
'(NIL (20)) ) ) ) ) )
(bye)
|
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.
|
#PowerShell
|
PowerShell
|
function Get-Hash
{
[CmdletBinding(DefaultParameterSetName="String")]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName="String",
Position=0)]
[string]
$String,
[Parameter(Mandatory=$true,
ParameterSetName="FileName",
Position=0)]
[string]
$FileName,
[Parameter(Mandatory=$false,
Position=1)]
[ValidateSet("MD5", "RIPEMD160", "SHA1", "SHA256", "SHA384", "SHA512")]
[string]
$HashType = "MD5"
)
$hashAlgorithm = [System.Security.Cryptography.HashAlgorithm]
$stringBuilder = New-Object -TypeName System.Text.StringBuilder
switch ($PSCmdlet.ParameterSetName)
{
"String"
{
$hashAlgorithm::Create($HashType).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) | ForEach-Object {
$stringBuilder.Append($_.ToString("x2")) | Out-Null
}
}
"FileName"
{
$fileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $FileName, ([System.IO.FileMode]::Open)
$hashAlgorithm::Create($HashType).ComputeHash($fileStream) | ForEach-Object {
$stringBuilder.Append($_.ToString("x2")) | Out-Null
}
$fileStream.Close()
$fileStream.Dispose()
}
}
$stringBuilder.ToString()
}
|
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
|
#Go
|
Go
|
package main
import "fmt"
const (
S = 10
)
type node struct {
v float64
fixed int
}
func alloc2(w, h int) [][]node {
a := make([][]node, h)
for i := range a {
a[i] = make([]node, w)
}
return a
}
func set_boundary(m [][]node) {
m[1][1].fixed = 1
m[1][1].v = 1
m[6][7].fixed = -1
m[6][7].v = -1
}
func calc_diff(m [][]node, d [][]node, w, h int) float64 {
total := 0.0
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
v := 0.0
n := 0
if i != 0 {
v += m[i-1][j].v
n++
}
if j != 0 {
v += m[i][j-1].v
n++
}
if i+1 < h {
v += m[i+1][j].v
n++
}
if j+1 < w {
v += m[i][j+1].v
n++
}
v = m[i][j].v - v/float64(n)
d[i][j].v = v
if m[i][j].fixed == 0 {
total += v * v
}
}
}
return total
}
func iter(m [][]node, w, h int) float64 {
d := alloc2(w, h)
diff := 1.0e10
cur := []float64{0, 0, 0}
for diff > 1e-24 {
set_boundary(m)
diff = calc_diff(m, d, w, h)
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
m[i][j].v -= d[i][j].v
}
}
}
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
t := 0
if i != 0 {
t += 1
}
if j != 0 {
t += 1
}
if i < h-1 {
t += 1
}
if j < w-1 {
t += 1
}
cur[m[i][j].fixed+1] += d[i][j].v * float64(t)
}
}
return (cur[2] - cur[0]) / 2
}
func main() {
mesh := alloc2(S, S)
fmt.Printf("R = %g\n", 2/iter(mesh, S, S))
}
|
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.
|
#Oforth
|
Oforth
|
1 first
[1:interpreter] ExRuntime : 1 does not understand method <#first>
|
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.
|
#ooRexx
|
ooRexx
|
u = .unknown~new
u~foo(1, 2, 3)
::class unknown
::method unknown
use arg name, args
say "Unknown method" name "invoked with arguments:" args~tostring('l',', ')
|
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.
|
#Oz
|
Oz
|
declare
class Example
meth init skip end
meth foo {System.showInfo foo} end
meth bar {System.showInfo bar} end
meth otherwise(Msg)
{System.showInfo "Unknown method "#{Label Msg}}
if {Width Msg} > 0 then
{System.printInfo "Arguments: "}
{System.show {Record.toListInd Msg}}
end
end
end
Object = {New Example init}
in
{Object foo}
{Object bar}
{Object grill}
{Object ding(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
|
#BBC_BASIC
|
BBC BASIC
|
PRINT FNreverse("---------- Ice and Fire ------------")\
\ 'FNreverse("")\
\ 'FNreverse("fire, in end will world the say Some")\
\ 'FNreverse("ice. in say Some")\
\ 'FNreverse("desire of tasted I've what From")\
\ 'FNreverse("fire. favor who those with hold I")\
\ 'FNreverse("")\
\ 'FNreverse("... elided paragraph last ...")\
\ 'FNreverse("")\
\ 'FNreverse("Frost Robert -----------------------")
END
DEF FNreverse(s$)
LOCAL sp%
sp%=INSTR(s$," ")
IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$
|
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
|
#Oforth
|
Oforth
|
: encryptRot13(c)
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c 13 + over - 26 mod + ;
: rot13 map(#encryptRot13) charsAsString ;
|
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
|
#Modula-2
|
Modula-2
|
MODULE RomanNumeralsEncode;
FROM Strings IMPORT
Append;
FROM STextIO IMPORT
WriteString, WriteLn;
CONST
MaxChars = 15;
(* 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
with these symbols. *)
TYPE
TRomanNumeral = ARRAY [0 .. MaxChars - 1] OF CHAR;
PROCEDURE ToRoman(AValue: CARDINAL; VAR OUT Destination: ARRAY OF CHAR);
TYPE
TRomanSymbols = ARRAY [0 .. 1] OF CHAR;
TWeights = ARRAY [0 .. 12] OF CARDINAL;
TSymbols = ARRAY [0 .. 12] OF TRomanSymbols;
CONST
Weights = TWeights {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
Symbols = TSymbols {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
"V", "IV", "I"};
VAR
I: CARDINAL;
BEGIN
Destination := "";
I := 0;
WHILE (I <= HIGH(Weights)) AND (AValue > 0) DO
WHILE AValue >= Weights[I] DO
Append(Symbols[I], Destination);
AValue := AValue - Weights[I]
END;
INC(I);
END;
END ToRoman;
VAR
Numeral: TRomanNumeral;
BEGIN
ToRoman(1990, Numeral); WriteString(Numeral); WriteLn; (* MCMXC *)
ToRoman(2018, Numeral); WriteString(Numeral); WriteLn; (* MMXVIII *)
ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *)
END RomanNumeralsEncode.
|
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.
|
#PL.2FI
|
PL/I
|
test_decode: procedure options (main); /* 28 January 2013 */
declare roman character (20) varying;
do roman = 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'iix',
'ix', 'x', 'xi', 'xiv', 'MCMLXIV', 'MCMXC', 'MDCLXVI',
'MIM', 'MM', 'MMXIII';
put skip list (roman, decode(roman));
end;
decode: procedure (roman) returns (fixed(15));
declare roman character (*) varying;
declare (current, previous) character (1);
declare n fixed (15);
declare i fixed binary;
previous = ''; n = 0;
do i = length(roman) to 1 by -1;
current = substr(roman, i, 1);
if digit_value(current) < digit_value(previous) then
n = n - digit_value(current);
else if digit_value(current) > digit_value(previous) then
do;
n = n + digit_value(current);
previous = current;
end;
else
n = n + digit_value(current);
end;
return (n);
end decode;
digit_value: procedure (roman_char) returns (fixed);
declare roman_char character(1);
select (roman_char);
when ('M', 'm') return (1000);
when ('D', 'd') return (500);
when ('C', 'c') return (100);
when ('L', 'l') return (50);
when ('X', 'x') return (10);
when ('V', 'v') return (5);
when ('I', 'i') return (1);
otherwise return (0);
end;
end digit_value;
end test_decode;
|
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.
|
#TMG
|
TMG
|
loop: ordcop [lch?]\loop;
ordcop: ord/copy;
ord: char(ch)/last [ch!=lch?]\new [cnt++] fail;
new: ( [lch?] parse(out) | () ) [lch=ch] [cnt=1] fail;
out: decimal(cnt) scopy = { 2 1 };
last: parse(out) [lch=0];
copy: smark any(!<<>>);
ch: 0;
lch: 0;
cnt: 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
|
#Ada
|
Ada
|
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure String_Multiplication is
begin
Put_Line (5 * "ha");
end String_Multiplication;
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#BASIC
|
BASIC
|
' Return multiple values
RECORD multi
LOCAL num
LOCAL s$[2]
END RECORD
FUNCTION f(n) TYPE multi_type
LOCAL r = { 0 } TYPE multi_type
r.num = n
r.s$[0] = "Hitchhiker's Guide"
r.s$[1] = "Douglas Adams"
RETURN r
END FUNCTION
DECLARE rec TYPE multi_type
rec = f(42)
PRINT rec.num
PRINT rec.s$[0]
PRINT rec.s$[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.
|
#6502_Assembly
|
6502 Assembly
|
macro RepeatProc,addr,count ;VASM macro syntax
; input:
; addr = the label of the routine you wish to call repeatedly
; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times.
lda #<\addr
sta z_L ;a label for a zero-page memory address
lda #>\addr
sta z_H ;a label for the zero-page memory address immediately after z_L
lda \count
jsr doRepeatProc
endm
doRepeatProc:
sta z_C ;another zero-page memory location
loop_RepeatProc:
jsr Trampoline_RepeatProc
dec z_C
lda z_C
bne loop_RepeatProc
rts
Trampoline_RepeatProc:
db $6c,z_L,$00
;when executed, becomes an indirect JMP to the address stored at z_L and z_H. Some assemblers will let you type
;JMP (z_L) and it will automatically replace it with the above during the assembly process.
;This causes an indirect JMP to the routine. Its RTS will return execution to just after the "JSR Trampoline_RepeatProc"
;and flow into the loop overhead.
|
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.
|
#68000_Assembly
|
68000 Assembly
|
lea foo,a5 ;function to execute
move.w #4-1,d7 ;times to repeat
jsr Repeater
jmp * ;halt the CPU, we're done
repeater:
jsr repeaterhelper ;this also need to be a call, so that the RTS of the desired procedure
;returns us to the loop rather than the line after "jsr Repeater".
DBRA D7,repeater
rts
repeaterhelper:
jmp (a5) ;keep in mind, this is NOT a dereference, it simply sets the program counter equal to A5.
;A bit misleading if you ask me.
foo:
MOVE.B #'!',D0
JSR PrintChar
rts
|
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.
|
#Python
|
Python
|
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import hashlib
>>> h = hashlib.new('ripemd160')
>>> h.update(b"Rosetta Code")
>>> h.hexdigest()
'b3be159860842cebaa7174c8fff0aa9e50a5199f'
>>>
|
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.
|
#Racket
|
Racket
|
#lang racket
(require (planet soegaard/digest:1:2/digest))
(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
|
#Haskell
|
Haskell
|
{-# LANGUAGE ParallelListComp #-}
import Numeric.LinearAlgebra (linearSolve, toDense, (!), flatten)
import Data.Monoid ((<>), Sum(..))
rMesh n (ar, ac) (br, bc)
| n < 2 = Nothing
| any (\x -> x < 1 || x > n) [ar, ac, br, bc] = Nothing
| otherwise = between a b <$> voltage
where
a = (ac - 1) + n*(ar - 1)
b = (bc - 1) + n*(br - 1)
between x y v = abs (v ! a - v ! b)
voltage = flatten <$> linearSolve matrixG current
matrixG = toDense $ concat [ element row col node
| row <- [1..n], col <- [1..n]
| node <- [0..] ]
element row col node =
let (Sum c, elements) =
(Sum 1, [((node, node-n), -1)]) `when` (row > 1) <>
(Sum 1, [((node, node+n), -1)]) `when` (row < n) <>
(Sum 1, [((node, node-1), -1)]) `when` (col > 1) <>
(Sum 1, [((node, node+1), -1)]) `when` (col < n)
in [((node, node), c)] <> elements
x `when` p = if p then x else mempty
current = toDense [ ((a, 0), -1) , ((b, 0), 1) , ((n^2-1, 0), 0) ]
|
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.
|
#Perl
|
Perl
|
package Example;
sub new {
bless {}
}
sub foo {
print "this is foo\n";
}
sub bar {
print "this is bar\n";
}
sub AUTOLOAD {
my $name = $Example::AUTOLOAD;
my ($self, @args) = @_;
print "tried to handle unknown method $name\n";
if (@args) {
print "it had arguments: @args\n";
}
}
sub DESTROY {} # dummy method to prevent AUTOLOAD from
# being triggered when an Example is
# destroyed
package main;
my $example = Example->new;
$example->foo; # prints "this is foo"
$example->bar; # prints "this is bar"
$example->grill; # prints "tried to handle unknown method Example::grill"
$example->ding("dong"); # prints "tried to handle unknown method Example::ding"
# and "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
|
#Bracmat
|
Bracmat
|
("---------- 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 -----------------------"
: ?text
& ( reverse
= token tokens reversed
. :?tokens
& whl
' ( @( !arg
: ?token (" "|\t|\r) ?arg
)
& !tokens !token:?tokens
)
& !tokens !arg:?tokens
& :?reversed
& whl
' ( !tokens:%?token %?tokens
& " " !token !reversed:?reversed
)
& !tokens !reversed:?reversed
& str$!reversed
)
& :?output
& whl
' ( @(!text:?line \n ?text)
& !output reverse$!line \n:?output
)
& !output reverse$!text:?output
& out$str$!output
);
|
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
|
#Ol
|
Ol
|
(import (scheme char))
(define (rot13 str)
(runes->string (map (lambda (ch)
(+ ch (cond
((char-ci<=? #\a ch #\m)
13)
((char-ci<=? #\n ch #\z)
-13)
(else 0))))
(string->runes str))))
(define str "`What a curious feeling!' said Alice; `I must be shutting up like a telescope.'")
(print (rot13 str))
(print (rot13 (rot13 str)))
|
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
|
#MUMPS
|
MUMPS
|
TOROMAN(INPUT)
;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
;OUTPUT is the string to return
;I is a loop variable
;CURRVAL is the current value in the loop
QUIT:($FIND(INPUT,".")>1)!(INPUT<=0)!(INPUT>3999) "Invalid input"
NEW OUTPUT,I,CURRVAL
SET OUTPUT="",CURRVAL=INPUT
SET:$DATA(ROMANNUM)=0 ROMANNUM="I^IV^V^IX^X^XL^L^XC^C^CD^D^CM^M"
SET:$DATA(ROMANVAL)=0 ROMANVAL="1^4^5^9^10^40^50^90^100^400^500^900^1000"
FOR I=$LENGTH(ROMANVAL,"^"):-1:1 DO
.FOR Q:CURRVAL<$PIECE(ROMANVAL,"^",I) SET OUTPUT=OUTPUT_$PIECE(ROMANNUM,"^",I),CURRVAL=CURRVAL-$PIECE(ROMANVAL,"^",I)
KILL I,CURRVAL
QUIT OUTPUT
|
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.
|
#PL.2FM
|
PL/M
|
100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* CP/M COMMAND LINE ARGUMENT */
DECLARE ARG$LPTR ADDRESS INITIAL (80H), ARG$LEN BASED ARG$LPTR BYTE;
DECLARE ARG$PTR ADDRESS INITIAL (81H), ARG BASED ARG$PTR BYTE;
/* CONVERT ROMAN NUMERAL TO BINARY */
READ$ROMAN: PROCEDURE (RP) ADDRESS;
DECLARE DIGITS (7) BYTE INITIAL ('MDCLXVI');
DECLARE VALUES (7) ADDRESS INITIAL (1000,500,100,50,10,5,1);
DECLARE (RP, V, DVAL) ADDRESS, R BASED RP BYTE;
V = 0;
GET$DIGIT: PROCEDURE (D) ADDRESS;
DECLARE (D, I) BYTE;
DO I = 0 TO LAST(DIGITS);
IF DIGITS(I) = D THEN RETURN VALUES(I);
END;
RETURN 0; /* NOT FOUND */
END GET$DIGIT;
DO WHILE R <> '$';
DVAL = GET$DIGIT(R);
IF DVAL = 0 THEN RETURN 0; /* ERROR */
RP = RP + 1;
IF GET$DIGIT(R) > DVAL THEN
V = V - DVAL; /* SUBTRACTIVE PRINCIPLE */
ELSE
V = V + DVAL;
END;
RETURN V;
END READ$ROMAN;
/* PRINT BINARY NUMBER AS DECIMAL */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
IF ARG$LEN = 0 THEN DO;
CALL PRINT(.'NO INPUT$');
CALL EXIT;
END;
ARG(ARG$LEN) = '$'; /* TERMINATE ARGUMENT STRING */
CALL PRINT(.ARG(1)); /* PRINT ROMAN NUMERAL */
CALL PRINT(.': $');
CALL PRINT$NUMBER(READ$ROMAN(.ARG(1))); /* CONVERT AND PRINT VALUE */
CALL EXIT;
EOF
|
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.
|
#TSE_SAL
|
TSE SAL
|
STRING PROC FNStringGetDecodeStringCharacterEqualCountS( STRING inS )
STRING s1[255] = ""
STRING s2[255] = ""
STRING s3[255] = ""
STRING s4[255] = ""
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
INTEGER L = 0
K = Length( inS )
I = 1 - 1
REPEAT
J = 1 - 1
s3 = ""
REPEAT
I = I + 1
J = J + 1
s1 = SubStr( inS, I, 1 )
s3 = s3 + s1
s4 = SubStr( inS, I + 1, 1 )
UNTIL ( NOT ( s4 IN '0'..'9' ) )
FOR L = 1 TO Val( s3 )
s2 = s2 + s4
ENDFOR
I = I + 1
UNTIL ( I >= ( K - 1 ) )
RETURN( s2 )
END
//
STRING PROC FNStringGetEncodeStringCharacterEqualCountS( STRING inS )
STRING s1[255] = ""
STRING s2[255] = ""
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
K = Length( inS )
I = 1 - 1
REPEAT
J = 1 - 1
REPEAT
I = I + 1
J = J + 1
s1 = SubStr( inS, I, 1 )
UNTIL ( NOT ( SubStr( inS, I + 1, 1 ) == s1 ) )
s2 = s2 + Str( J ) + s1
UNTIL ( I >= ( K - 1 ) )
RETURN( s2 )
END
//
STRING PROC FNStringGetEncodeDecodeStringCharacterEqualCountS( STRING inS )
STRING s1[255] = FNStringGetEncodeStringCharacterEqualCountS( inS )
STRING s2[255] = FNStringGetDecodeStringCharacterEqualCountS( s1 )
RETURN( s2 )
END
//
PROC Main()
STRING s1[255] = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
STRING s2[255] = ""
IF ( NOT ( Ask( "string: get: encode: decode: string: character: equal: count: inS = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
s2 = FNStringGetEncodeDecodeStringCharacterEqualCountS( s1 )
Warn( "equal strings if result is 1", ",", " ", "and the result is", ":", " ", s1 == s2 )
END
|
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
|
#Aime
|
Aime
|
call_n(5, o_text, "ha");
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Bracmat
|
Bracmat
|
(addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y));
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#C
|
C
|
#include<stdio.h>
typedef struct{
int integer;
float decimal;
char letter;
char string[100];
double bigDecimal;
}Composite;
Composite example()
{
Composite C = {1, 2.3, 'a', "Hello World", 45.678};
return C;
}
int main()
{
Composite C = example();
printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);
return 0;
}
|
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
|
#0815
|
0815
|
}:r: Start reader loop.
!~>& Push a character to the "stack".
<:a:=- Stop reading on newline.
^:r:
@> Rotate the newline to the end and enqueue a sentinel 0.
{~ Dequeue and rotate the first character into place.
}:p:
${~ Print the current character until it's 0.
^:p:
#:r: Read again.
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#Detailed_Description_of_Programming_Task
|
Detailed Description of Programming Task
|
select
Server.Wake_Up (Parameters);
or delay 5.0;
-- No response, try something else
...
end select;
|
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.
|
#Action.21
|
Action!
|
DEFINE PTR="CARD"
PROC OutputText(CHAR ARRAY s)
PrintE(s)
RETURN
PROC Procedure=*(CHAR ARRAY s)
DEFINE JSR="$20"
DEFINE RTS="$60"
[JSR $00 $00 ;JSR to address set by SetProcedure
RTS]
PROC SetProcedure(PTR p)
PTR addr
addr=Procedure+1 ;location of address of JSR
PokeC(addr,p)
RETURN
PROC Repeat(PTR procFun CHAR ARRAY s BYTE n)
BYTE i
SetProcedure(procFun)
FOR i=1 TO n
DO
Procedure(s)
OD
RETURN
PROC Main()
Repeat(OutputText,"Action!",5)
RETURN
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO;
procedure Repeat_Example is
procedure Repeat(P: access Procedure; Reps: Natural) is
begin
for I in 1 .. Reps loop
P.all; -- P points to a procedure, and P.all actually calls that procedure
end loop;
end Repeat;
procedure Hello is
begin
Ada.Text_IO.Put("Hello! ");
end Hello;
begin
Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello
end Repeat_Example;
|
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.
|
#Raku
|
Raku
|
=for CREDITS
Crypto-JS v2.0.0
http:#code.google.com/p/crypto-js/
Copyright (c) 2009, Jeff Mott. All rights reserved.
sub rotl($n, $b) { $n +< $b +| $n +> (32 - $b) }
sub prefix:<m^> { +^$^x % 2**32 }
sub infix:<m+> { ($^x + $^y) % 2**32 }
constant r1 = <
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
7 4 13 1 10 6 15 3 12 0 9 5 2 14 11 8
3 10 14 4 9 15 8 1 2 7 0 6 13 11 5 12
1 9 11 10 0 8 12 4 13 3 7 15 14 5 6 2
4 0 5 9 7 12 2 10 14 1 3 8 11 6 15 13
>;
constant r2 = <
5 14 7 0 9 2 11 4 13 6 15 8 1 10 3 12
6 11 3 7 0 13 5 10 14 15 8 12 4 9 1 2
15 5 1 3 7 14 6 9 11 8 12 2 10 0 4 13
8 6 4 1 3 11 15 0 5 12 2 13 9 7 10 14
12 15 10 4 1 5 8 7 6 2 13 14 0 3 9 11
>;
constant s1 = <
11 14 15 12 5 8 7 9 11 13 14 15 6 7 9 8
7 6 8 13 11 9 7 15 7 12 15 9 11 7 13 12
11 13 6 7 14 9 13 15 14 8 13 6 5 12 7 5
11 12 14 15 14 15 9 8 9 14 5 6 8 6 5 12
9 15 5 11 6 8 13 12 5 12 13 14 11 8 5 6
>;
constant s2 = <
8 9 9 11 13 15 15 5 7 7 8 11 14 14 12 6
9 13 15 7 12 8 9 11 7 7 12 7 6 15 13 11
9 7 15 11 8 6 6 14 12 13 5 14 13 13 7 5
15 5 8 11 14 14 6 14 6 9 12 9 12 5 15 8
8 5 12 9 12 5 14 6 8 13 6 5 15 13 11 11
>;
constant F =
* +^ * +^ *,
{ ($^x +& $^y) +| (m^$^x +& $^z) },
(* +| m^*) +^ *,
{ ($^x +& $^z) +| ($^y +& m^$^z) },
* +^ (* +| m^*),
;
constant K1 = flat | <0x00000000 0x5a827999 0x6ed9eba1 0x8f1bbcdc 0xa953fd4e> »xx» 16;
constant K2 = flat | <0x50a28be6 0x5c4dd124 0x6d703ef3 0x7a6d76e9 0x00000000> »xx» 16;
our proto rmd160($) returns Blob {*}
multi rmd160(Str $s) { rmd160 $s.encode: 'ascii' }
multi rmd160(Blob $data) {
my @b = | $data, 0x80;
push @b, 0 until (8*@b-448) %% 512;
my $len = 8 * $data.elems;
push @b, | gather for ^8 { take $len % 256; $len div= 256 }
my @word = gather for @b -> $a, $b, $c, $d {
take reduce * *256 + *, $d, $c, $b, $a;
}
my @h = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0;
loop (my $i = 0; $i < @word; $i += 16) {
my @X = my @Y = @h;
for ^80 -> $j {
my $T = rotl(
@X[0] m+ F[$j div 16](|@X[1..3]) m+ (@word[$i+r1[$j]] // 0) m+ K1[$j], s1[$j]
) m+ @X[4];
@X = @X[4], $T, @X[1], rotl(@X[2], 10) % 2**32, @X[3];
$T = rotl(
@Y[0] m+ F[(79-$j) div 16](|@Y[1..3]) m+ (@word[$i+r2[$j]] // 0) m+ K2[$j], s2[$j]
) m+ @Y[4];
@Y = @Y[4], $T, @Y[1], rotl(@Y[2], 10) % 2**32, @Y[3];
}
@h = (flat @h[1..4,^1]) Z[m+] (flat @X[2..4,^2]) Z[m+] flat @Y[3..4,^3];
}
return Blob.new: gather for @h -> $word is rw {
for ^4 { take $word % 256; $word div= 256 }
}
}
say rmd160 "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
|
#J
|
J
|
nodes=: 10 10 #: i. 100
nodeA=: 1 1
nodeB=: 6 7
NB. verb to pair up coordinates along a specific offset
conn =: [: (#~ e.~/@|:~&0 2) ([ ,: +)"1
ref =: ~. nodeA,nodes-.nodeB NB. all nodes, with A first and B omitted
wiring=: /:~ ref i. ,/ nodes conn"2 1 (,-)=i.2 NB. connected pairs (indices into ref)
Yii=: (* =@i.@#) #/.~ {."1 wiring NB. diagonal of Y represents connections to B
Yij=: -1:`(<"1@[)`]}&(+/~ 0*i.1+#ref) wiring NB. off diagonal of Y represents wiring
Y=: _1 _1 }. Yii+Yij
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
enum METHODS
function invoke(object o, string name, sequence args={})
--(this works on any class, for any function, with any number or type of parameters)
integer mdict = o[METHODS]
integer node = getd_index(name,mdict)
if node!=0 then
return call_func(getd_by_index(node,mdict),args)
end if
return "no such method" -- or throw(), fatal(), etc
end function
--class X: Xmethods emulates a vtable
constant Xmethods = new_dict()
function exists()
return "exists"
end function
setd("exists",routine_id("exists"),Xmethods)
--class X: create new instances
function newX()
return {Xmethods}
end function
object x = newX()
?invoke(x,"exists")
?invoke(x,"non_existent_method")
|
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.
|
#PHP
|
PHP
|
<?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$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
|
#Burlesque
|
Burlesque
|
blsq ) "It is not raining"wd<-wd
"raining not is It"
blsq ) "ice. in say some"wd<-wd
"some say in ice."
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#C
|
C
|
#include <stdio.h>
#include <ctype.h>
void rev_print(char *s, int n)
{
for (; *s && isspace(*s); s++);
if (*s) {
char *e;
for (e = s; *e && !isspace(*e); e++);
rev_print(e, 0);
printf("%.*s%s", (int)(e - s), s, " " + n);
}
if (n) putchar('\n');
}
int main(void)
{
char *s[] = {
"---------- 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 -----------------------",
0
};
int i;
for (i = 0; s[i]; i++) rev_print(s[i], 1);
return 0;
}
|
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
|
#Oz
|
Oz
|
declare
fun {RotChar C}
if C >= &A andthen C =< &Z then &A + (C - &A + 13) mod 26
elseif C >= &a andthen C =< &z then &a + (C - &a + 13) mod 26
else C
end
end
fun {Rot13 S}
{Map S RotChar}
end
in
{System.showInfo {Rot13 "NOWHERE Abjurer 42"}}
{System.showInfo {Rot13 {Rot13 "NOWHERE Abjurer 42"}}}
|
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
|
#Nim
|
Nim
|
import strutils
const nums = [(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")]
proc toRoman(n: Positive): string =
var n = n.int
for (a, r) in nums:
result.add(repeat(r, n div a))
n = n mod a
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
25, 30, 40, 50, 60, 69, 70, 80, 90, 99,
100, 200, 300, 400, 500, 600, 666, 700, 800, 900,
1000, 1009, 1444, 1666, 1945, 1997, 1999,
2000, 2008, 2010, 2011, 2500, 3000, 3999]:
echo ($i).align(4), ": ", i.toRoman
|
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.
|
#PL.2FSQL
|
PL/SQL
|
/*****************************************************************
* $Author: Atanas Kebedjiev $
*****************************************************************
* PL/SQL code can be run as anonymous block.
* To test, execute the whole script or create the functions and then e.g. 'select rdecode('2012') from dual;
* Please note that task definition does not describe fully some current rules, such as
* * subtraction - IX XC CM are the valid subtraction combinations
* * A subtraction character cannot be repeated: 8 is expressed as VIII and not as IIX
* * V L and D cannot be used for subtraction
* * Any numeral cannot be repeated more than 3 times: 1910 should be MCMX and not MDCCCCX
* Code below does not validate the Roman numeral itself and will return a result even for a non-compliant number
* E.g. both MCMXCIX and IMM will return 1999 but the first one is the correct notation
*/
DECLARE
FUNCTION rvalue(c IN CHAR) RETURN NUMBER IS
i INTEGER;
BEGIN
i := 0;
CASE (c)
when 'M' THEN i := 1000;
when 'D' THEN i := 500;
when 'C' THEN i := 100;
when 'L' THEN i := 50;
when 'X' THEN i := 10;
when 'V' THEN i := 5;
when 'I' THEN i := 1;
END CASE;
RETURN i;
END;
FUNCTION decode(rn IN VARCHAR2) RETURN NUMBER IS
i INTEGER;
l INTEGER;
cr CHAR; -- current Roman numeral as substring from r
cv INTEGER; -- value of current Roman numeral
gr CHAR; -- next Roman numeral
gv NUMBER; -- value of the next numeral;
dv NUMBER; -- decimal value to return
BEGIN
l := length(rn);
i := 1;
dv := 0;
while (i <= l)
LOOP
cr := substr(rn,i,1);
cv := rvalue(cr);
/* Look for a larger numeral in next position, like IV or CM
The number to subtract should be at least 1/10th of the bigger number
CM and XC are valid, but IC and XM are not */
IF (i < l) THEN
gr := substr(rn,i+1,1);
gv := rvalue(gr);
IF (cv < gv ) THEN
dv := dv - cv;
ELSE
dv := dv + cv;
END IF;
ELSE
dv := dv + cv;
END IF; -- need to add the last value unconditionally
i := i + 1;
END LOOP;
RETURN dv;
END;
BEGIN
DBMS_OUTPUT.PUT_LINE ('MMXII = ' || rdecode('MMXII')); -- 2012
DBMS_OUTPUT.PUT_LINE ('MCMLI = ' || rdecode('MCMLI')); -- 1951
DBMS_OUTPUT.PUT_LINE ('MCMLXXXVII = ' || rdecode('MCMLXXXVII')); -- 1987
DBMS_OUTPUT.PUT_LINE ('MDCLXVI = ' || rdecode('MDCLXVI')); -- 1666
DBMS_OUTPUT.PUT_LINE ('MCMXCIX = ' || rdecode('MCMXCIX')); -- 1999
END;
|
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.
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT,{}
input="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",output=""
string=strings(input," ? ")
letter=ACCUMULATE(string,freq)
freq=SPLIT(freq),letter=SPLIT(letter)
output=JOIN(freq,"",letter)
output=JOIN(output,"")
PRINT input
PRINT output
|
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
|
#ALGOL_68
|
ALGOL 68
|
print (5 * "ha")
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
class ReturnMultipleValues
{
static void Main()
{
var values = new[] { 4, 51, 1, -3, 3, 6, 8, 26, 2, 4 };
int max, min;
MinMaxNum(values, out max, out min);
Console.WriteLine("Min: {0}\nMax: {1}", min, max);
}
static void MinMaxNum(IEnumerable<int> nums, out int max, out int min)
{
var sortedNums = nums.OrderBy(num => num).ToArray();
max = sortedNums.Last();
min = sortedNums.First();
}
}
|
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
|
#11l
|
11l
|
reversed(string)
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#Ada
|
Ada
|
select
Server.Wake_Up (Parameters);
or delay 5.0;
-- No response, try something else
...
end select;
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#AutoHotkey
|
AutoHotkey
|
OnMessage(0x4a, "PrintMonitor")
SetTimer, print2, 400
print1:
print("Old Mother Goose")
print("When she wanted to wander,")
print("Would ride through the air")
print("On a very fine gander.")
print("Jack's mother came in,")
print("And caught the goose soon,")
print("And mounting its back,")
print("Flew up to the moon.")
Return
print2:
SetTimer, print2, Off
print("Humpty Dumpty sat on a wall.")
print("Humpty Dumpty had a great fall.")
print("All the king's horses and all the king's men")
print("Couldn't put Humpty together again.")
Return
print(message)
{
Static StringToSend
StringToSend := message
Gui +LastFound
VarSetCapacity(CopyDataStruct, 12, 0)
NumPut(StrLen(StringToSend) + 1, CopyDataStruct, 4)
NumPut(&StringToSend, CopyDataStruct, 8)
SendMessage, 0x4a, 0, &CopyDataStruct
If ErrorLevel
MsgBox out of ink
Sleep, 200
Return
}
PrintMonitor(wParam, lParam, msg)
{
Static ink = 5
Global printed
Critical
If ink
{
StringAddress := NumGet(lParam + 8)
StringLength := DllCall("lstrlen", UInt, StringAddress)
VarSetCapacity(CopyOfData, StringLength)
DllCall("lstrcpy", "str", CopyOfData, "uint", StringAddress)
printed .= "primaryprinter: " . CopyOfData . "`n"
ToolTip, primary printer`n: %printed%
ink--
}
Else
{
OnMessage(0x4a, "Reserve")
print(CopyOfData)
}
}
Reserve(wParam, lParam, msg)
{
Static ink = 5
Global printed
Critical
If ink
{
StringAddress := NumGet(lParam + 8)
StringLength := DllCall("lstrlen", UInt, StringAddress)
VarSetCapacity(CopyOfData, StringLength)
DllCall("lstrcpy", "str", CopyOfData, "uint", StringAddress)
printed .= "reserveprinter: " . CopyOfData . "`n"
ToolTip, Reserve printer`n: %printed%
ink--
}
Else
Return -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.
|
#ALGOL_68
|
ALGOL 68
|
# operator that executes a procedure the specified number of times #
OP REPEAT = ( INT count, PROC VOID routine )VOID:
TO count DO routine OD;
# make REPEAT a low priority operater #
PRIO REPEAT = 1;
# can also create variant that passes the iteration count as a parameter #
OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID:
FOR iteration TO count DO routine( iteration ) OD;
main: (
# PROC to test the REPEAT operator with #
PROC say something = VOID: print( ( "something", newline ) );
3 REPEAT say something;
# PROC to test the variant #
PROC show squares = ( INT n )VOID: print( ( n, n * n, newline ) );
3 REPEAT show squares
)
|
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.)
|
#11l
|
11l
|
fs:rename(‘input.txt’, ‘output.txt’)
fs:rename(‘docs’, ‘mydocs’)
fs:rename(fs:path:sep‘input.txt’, fs:path:sep‘output.txt’)
fs:rename(fs:path:sep‘docs’, fs:path:sep‘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.
|
#Ruby
|
Ruby
|
require 'digest'
puts Digest::RMD160.hexdigest('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.
|
#Rust
|
Rust
|
use ripemd160::{Digest, Ripemd160};
/// Create a lowercase hexadecimal string using the
/// RIPEMD160 hashing algorithm
fn ripemd160(text: &str) -> String {
// create a lowercase hexadecimal string
// using the shortand for the format macro
// https://doc.rust-lang.org/std/fmt/trait.LowerHex.html
format!("{:x}", Ripemd160::digest(text.as_bytes()))
}
fn main() {
println!("{}", 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
|
#Java
|
Java
|
import java.util.ArrayList;
import java.util.List;
public class ResistorMesh {
private static final int S = 10;
private static class Node {
double v;
int fixed;
Node(double v, int fixed) {
this.v = v;
this.fixed = fixed;
}
}
private static void setBoundary(List<List<Node>> m) {
m.get(1).get(1).v = 1.0;
m.get(1).get(1).fixed = 1;
m.get(6).get(7).v = -1.0;
m.get(6).get(7).fixed = -1;
}
private static double calcDiff(List<List<Node>> m, List<List<Node>> d, int w, int h) {
double total = 0.0;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
double v = 0.0;
int n = 0;
if (i > 0) {
v += m.get(i - 1).get(j).v;
n++;
}
if (j > 0) {
v += m.get(i).get(j - 1).v;
n++;
}
if (i + 1 < h) {
v += m.get(i + 1).get(j).v;
n++;
}
if (j + 1 < w) {
v += m.get(i).get(j + 1).v;
n++;
}
v = m.get(i).get(j).v - v / n;
d.get(i).get(j).v = v;
if (m.get(i).get(j).fixed == 0) {
total += v * v;
}
}
}
return total;
}
private static double iter(List<List<Node>> m, int w, int h) {
List<List<Node>> d = new ArrayList<>(h);
for (int i = 0; i < h; ++i) {
List<Node> t = new ArrayList<>(w);
for (int j = 0; j < w; ++j) {
t.add(new Node(0.0, 0));
}
d.add(t);
}
double[] cur = new double[3];
double diff = 1e10;
while (diff > 1e-24) {
setBoundary(m);
diff = calcDiff(m, d, w, h);
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
m.get(i).get(j).v -= d.get(i).get(j).v;
}
}
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
int k = 0;
if (i != 0) k++;
if (j != 0) k++;
if (i < h - 1) k++;
if (j < w - 1) k++;
cur[m.get(i).get(j).fixed + 1] += d.get(i).get(j).v * k;
}
}
return (cur[2] - cur[0]) / 2.0;
}
public static void main(String[] args) {
List<List<Node>> mesh = new ArrayList<>(S);
for (int i = 0; i < S; ++i) {
List<Node> t = new ArrayList<>(S);
for (int j = 0; j < S; ++j) {
t.add(new Node(0.0, 0));
}
mesh.add(t);
}
double r = 2.0 / iter(mesh, S, S);
System.out.printf("R = %.15f", 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.
|
#PicoLisp
|
PicoLisp
|
(redef send (Msg Obj . @)
(or
(pass try Msg Obj)
(pass 'no-applicable-method> Obj Msg) ) )
(de no-applicable-method> (This Msg)
(pack "No method for " Msg " on " This) )
(class +A)
(dm do-something> ()
(pack "Do something to " This) )
|
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.
|
#Pike
|
Pike
|
class CatchAll
{
mixed `->(string name)
{
return lambda(int arg){ write("you are calling %s(%d);\n", name, arg); };
}
}
> CatchAll()->hello(5);
you are calling hello(5);
> CatchAll()->something(99);
you are calling something(99);
|
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
|
#C.23
|
C#
|
using System;
public class ReverseWordsInString
{
public static void Main(string[] args)
{
string 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 -----------------------
";
foreach (string line in text.Split(Environment.NewLine)) {
//Splits on any whitespace, not just spaces
string[] words = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
WriteLine(string.Join(" ", words));
}
}
}
|
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
|
#PARI.2FGP
|
PARI/GP
|
rot13(s)={
s=Vecsmall(s);
for(i=1,#s,
if(s[i]>109&s[i]<123,s[i]-=13,if(s[i]<110&s[i]>96,s[i]+=13,if(s[i]>77&s[i]<91,s[i]-=13,if(s[i]<78&s[i]>64,s[i]+=13))))
);
Strchr(s)
};
|
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
|
#Objeck
|
Objeck
|
bundle Default {
class Roman {
nums: static : Int[];
rum : static : String[];
function : Init() ~ Nil {
nums := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
rum := ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
}
function : native : ToRoman(number : Int) ~ String {
result := "";
for(i :=0; i < nums->Size(); i += 1;) {
while(number >= nums[i]) {
result->Append(rum[i]);
number -= nums[i];
};
};
return result;
}
function : Main(args : String[]) ~ Nil {
Init();
ToRoman(1999)->PrintLine();
ToRoman(25)->PrintLine();
ToRoman(944)->PrintLine();
}
}
}
|
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.
|
#PowerShell
|
PowerShell
|
Filter FromRoman {
$output = 0
if ($_ -notmatch '^(M{1,3}|)(CM|CD|D?C{0,3}|)(XC|XL|L?X{0,3}|)(IX|IV|V?I{0,3}|)$') {
throw 'Incorrect format'
}
$current = 1000
$subtractor = 'M'
$whole = $False
$roman = $_
'C','D','X','L','I','V',' ' `
| %{
if ($whole = !$whole) {
$current /= 10
$subtractor = $_ + $subtractor[0]
$_ = $subtractor[1]
}
else {
$subtractor = $subtractor[0] + $_
}
if ($roman -match $subtractor) {
$output += $current * (4,9)[$whole]
$roman = $roman -replace $subtractor,''
}
if ($roman -match ($_ + '{1,3}')) {
$output += $current * (5,10)[$whole] * $Matches[0].Length
}
}
$output
}
|
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.
|
#UNIX_Shell
|
UNIX Shell
|
encode() {
local phrase=$1
[[ -z $phrase ]] && return
local result="" count=0 char=${phrase:0:1}
for ((i = 0; i < ${#phrase}; i++)); do
if [[ ${phrase:i:1} == "$char" ]]; then
((count++))
else
result+="$(encode_sequence "$count" "$char")"
char=${phrase:i:1}
count=1
fi
done
result+="$(encode_sequence "$count" "$char")"
echo "$result"
}
encode_sequence() {
local count=$1 char=$2
((count == 1)) && count=""
echo "${count}${char}"
}
decode() {
local phrase=$1
local result=""
local count char
while [[ $phrase =~ ([[:digit:]]+)([^[:digit:]]) ]]; do
printf -v phrase "%s%s%s" \
"${phrase%%${BASH_REMATCH[0]}*}" \
"$(repeat "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}")" \
"${phrase#*${BASH_REMATCH[0]}}"
done
echo "$phrase"
}
repeat() {
local count=$1 char=$2
local result
# string of count spaces
printf -v result "%*s" "$count" ""
# replace spaces with the char
echo "${result// /$char}"
}
|
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
|
#Amazing_Hopper
|
Amazing Hopper
|
#!/usr/bin/hopper
#include <hopper.h>
main:
{"ha"}replyby(5), println
{"ha",5}replicate, println
{0}return
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>
std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
const auto maximum = std::max_element(numbers, numbers + num);
const auto minimum = std::min_element(numbers, numbers + num);
return std::make_tuple(*minimum, *maximum) ;
}
int main( ) {
const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
int min{};
int max{};
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}
|
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
|
#11l
|
11l
|
F reps(text)
R (1 .< 1 + text.len I/ 2).filter(x -> @text.starts_with(@text[x..])).map(x -> @text[0 .< x])
V matchstr =
|‘1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1’
L(line) matchstr.split("\n")
print(‘'#.' has reps #.’.format(line, reps(line)))
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#11l
|
11l
|
V string = ‘This is a string’
I re:‘string$’.search(string)
print(‘Ends with string.’)
string = string.replace(re:‘ a ’, ‘ another ’)
print(string)
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#360_Assembly
|
360 Assembly
|
* Reverse a string 21/05/2016
REVERSE CSECT
USING REVERSE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
MVC TMP(L'C),C tmp=c
LA R8,C @c[1]
LA R9,TMP+L'C-1 @tmp[n-1]
LA R6,1 i=1
LA R7,L'C n=length(c)
LOOPI CR R6,R7 do i=1 to n
BH ELOOPI leave i
MVC 0(1,R8),0(R9) substr(c,i,1)=substr(tmp,n-i+1,1)
LA R8,1(R8) @c=@c+1
BCTR R9,0 @tmp=@tmp-1
LA R6,1(R6) i=i+1
B LOOPI next i
ELOOPI XPRNT C,L'C print c
L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
C DC CL12'edoC attesoR'
TMP DS CL12
REGEQU
END REVERSE
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#C
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
/* The language task, implemented with pthreads for POSIX systems. */
/* Each rendezvous_t will be accepted by a single thread, and entered
* by one or more threads. accept_func() only returns an integer and
* is always run within the entering thread's context to simplify
* handling the arguments and return value. This somewhat unlike an
* Ada rendezvous and is a subset of the Ada rendezvous functionality.
* Ada's in and out parameters can be simulated via the void pointer
* passed to accept_func() to update variables owned by both the
* entering and accepting threads, if a suitable struct with pointers
* to those variables is used. */
typedef struct rendezvous {
pthread_mutex_t lock; /* A mutex/lock to use with the CVs. */
pthread_cond_t cv_entering; /* Signaled when a thread enters. */
pthread_cond_t cv_accepting; /* Signaled when accepting thread is ready. */
pthread_cond_t cv_done; /* Signaled when accept_func() finishes. */
int (*accept_func)(void*); /* The function to run when accepted. */
int entering; /* Number of threads trying to enter. */
int accepting; /* True if the accepting thread is ready. */
int done; /* True if accept_func() is done. */
} rendezvous_t;
/* Static initialization for rendezvous_t. */
#define RENDEZVOUS_INITILIZER(accept_function) { \
.lock = PTHREAD_MUTEX_INITIALIZER, \
.cv_entering = PTHREAD_COND_INITIALIZER, \
.cv_accepting = PTHREAD_COND_INITIALIZER, \
.cv_done = PTHREAD_COND_INITIALIZER, \
.accept_func = accept_function, \
.entering = 0, \
.accepting = 0, \
.done = 0, \
}
int enter_rendezvous(rendezvous_t *rv, void* data)
{
/* Arguments are passed in and out of the rendezvous via
* (void*)data, and the accept_func() return value is copied and
* returned to the caller (entering thread). A data struct with
* pointers to variables in both the entering and accepting
* threads can be used to simulate Ada's in and out parameters, if
* needed. */
pthread_mutex_lock(&rv->lock);
rv->entering++;
pthread_cond_signal(&rv->cv_entering);
while (!rv->accepting) {
/* Nothing is accepting yet, keep waiting. pthreads will
* queue all waiting entries. The loop is needed to handle
* both race conditions and spurious wakeups. */
pthread_cond_wait(&rv->cv_accepting, &rv->lock);
}
/* Call accept_func() and copy the return value before leaving
* the mutex. */
int ret = rv->accept_func(data);
/* This signal is needed so that the accepting thread will wait
* for the rendezvous to finish before trying to accept again. */
rv->done = 1;
pthread_cond_signal(&rv->cv_done);
rv->entering--;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
return ret;
}
void accept_rendezvous(rendezvous_t *rv)
{
/* This accept function does not take in or return parameters.
* That is handled on the entry side. This is only for
* synchronization. */
pthread_mutex_lock(&rv->lock);
rv->accepting = 1;
while (!rv->entering) {
/* Nothing to accept yet, keep waiting. */
pthread_cond_wait(&rv->cv_entering, &rv->lock);
}
pthread_cond_signal(&rv->cv_accepting);
while (!rv->done) {
/* Wait for accept_func() to finish. */
pthread_cond_wait(&rv->cv_done, &rv->lock);
}
rv->done = 0;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
}
/* The printer use case task implemented using the above rendezvous
* implementation. Since C doesn't have exceptions, return values are
* used to signal out of ink errors. */
typedef struct printer {
rendezvous_t rv;
struct printer *backup;
int id;
int remaining_lines;
} printer_t;
typedef struct print_args {
struct printer *printer;
const char* line;
} print_args_t;
int print_line(printer_t *printer, const char* line) {
print_args_t args;
args.printer = printer;
args.line = line;
return enter_rendezvous(&printer->rv, &args);
}
int accept_print(void* data) {
/* This is called within the rendezvous, so everything is locked
* and okay to modify. */
print_args_t *args = (print_args_t*)data;
printer_t *printer = args->printer;
const char* line = args->line;
if (printer->remaining_lines) {
/* Print the line, character by character. */
printf("%d: ", printer->id);
while (*line != '\0') {
putchar(*line++);
}
putchar('\n');
printer->remaining_lines--;
return 1;
}
else if (printer->backup) {
/* "Requeue" this rendezvous with the backup printer. */
return print_line(printer->backup, line);
}
else {
/* Out of ink, and no backup available. */
return -1;
}
}
printer_t backup_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = NULL,
.id = 2,
.remaining_lines = 5,
};
printer_t main_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = &backup_printer,
.id = 1,
.remaining_lines = 5,
};
void* printer_thread(void* thread_data) {
printer_t *printer = (printer_t*) thread_data;
while (1) {
accept_rendezvous(&printer->rv);
}
}
typedef struct poem {
char* name;
char* lines[];
} poem_t;
poem_t humpty_dumpty = {
.name = "Humpty Dumpty",
.lines = {
"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.",
""
},
};
poem_t mother_goose = {
.name = "Mother Goose",
.lines = {
"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.",
""
},
};
void* poem_thread(void* thread_data) {
poem_t *poem = (poem_t*)thread_data;
for (unsigned i = 0; poem->lines[i] != ""; i++) {
int ret = print_line(&main_printer, poem->lines[i]);
if (ret < 0) {
printf(" %s out of ink!\n", poem->name);
exit(1);
}
}
return NULL;
}
int main(void)
{
pthread_t threads[4];
pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty);
pthread_create(&threads[1], NULL, poem_thread, &mother_goose);
pthread_create(&threads[2], NULL, printer_thread, &main_printer);
pthread_create(&threads[3], NULL, printer_thread, &backup_printer);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_cancel(threads[2]);
pthread_cancel(threads[3]);
return 0;
}
|
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.
|
#ALGOL_W
|
ALGOL W
|
begin
% executes the procedure routine the specified number of times %
procedure repeat ( integer value count; procedure routine ) ;
for i := 1 until count do routine;
begin
integer x;
% print "hello" three times %
repeat( 3, write( "hello" ) );
% print the first 10 squares %
write();
x := 1;
repeat( 10
, begin
writeon( i_w := s_w := 1, x * x );
x := x + 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.
|
#AppleScript
|
AppleScript
|
-- applyN :: Int -> (a -> a) -> a -> a
on applyN(n, f, x)
script go
on |λ|(a, g)
|λ|(a) of mReturn(g)
end |λ|
end script
foldl(go, x, replicate(n, f))
end applyN
-------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION --------
on double(x)
2 * x
end double
on plusArrow(s)
s & " -> "
end plusArrow
on squareRoot(n)
n ^ 0.5
end squareRoot
-------------------------- TESTS --------------------------
on run
log applyN(10, double, 1)
--> 1024
log applyN(5, plusArrow, "")
--> " -> -> -> -> -> "
log applyN(3, squareRoot, 65536)
--> 4.0
end run
-------------------- GENERIC FUNCTIONS --------------------
-- 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
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
|
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.)
|
#Action.21
|
Action!
|
INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
PROC Dir(CHAR ARRAY filter)
BYTE dev=[1]
CHAR ARRAY line(255)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*",
cmd="D:INPUT.TXT OUTPUT.TXT"
Put(125) PutE() ;clear screen
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Rename ""%S""%E%E",cmd)
Rename(cmd)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN
|
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.)
|
#Ada
|
Ada
|
with Ada.Directories; use Ada.Directories;
...
Rename ("input.txt", "output.txt");
Rename ("docs", "mydocs");
Rename ("/input.txt", "/output.txt");
Rename ("/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.
|
#Scala
|
Scala
|
import org.bouncycastle.crypto.digests.RIPEMD160Digest
object RosettaRIPEMD160 extends App {
val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new RIPEMD160Digest())
messageDigest.update(raw, 0, raw.length)
val out = Array.fill[Byte](messageDigest.getDigestSize())(0)
messageDigest.doFinal(out, 0)
assert(out.map("%02x".format(_)).mkString == "b3be159860842cebaa7174c8fff0aa9e50a5199f")
}
|
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
|
#Julia
|
Julia
|
N = 10
D1 = speye(N-1,N) - spdiagm(ones(N-1),1,N-1,N)
D = [ kron(D1, speye(N)); kron(speye(N), D1) ]
i, j = N*1 + 2, N*7+7
b = zeros(N^2); b[i], b[j] = 1, -1
v = (D' * D) \ b
v[i] - v[j]
|
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
|
#Kotlin
|
Kotlin
|
// version 1.1.4-3
typealias List2D<T> = List<List<T>>
const val S = 10
class Node(var v: Double, var fixed: Int)
fun setBoundary(m: List2D<Node>) {
m[1][1].v = 1.0; m[1][1].fixed = 1
m[6][7].v = -1.0; m[6][7].fixed = -1
}
fun calcDiff(m: List2D<Node>, d: List2D<Node>, w: Int, h: Int): Double {
var total = 0.0
for (i in 0 until h) {
for (j in 0 until w) {
var v = 0.0
var n = 0
if (i > 0) { v += m[i - 1][j].v; n++ }
if (j > 0) { v += m[i][j - 1].v; n++ }
if (i + 1 < h) { v += m[i + 1][j].v; n++ }
if (j + 1 < w) { v += m[i][j + 1].v; n++ }
v = m[i][j].v - v / n
d[i][j].v = v
if (m[i][j].fixed == 0) total += v * v
}
}
return total
}
fun iter(m: List2D<Node>, w: Int, h: Int): Double {
val d = List(h) { List(w) { Node(0.0, 0) } }
val cur = DoubleArray(3)
var diff = 1e10
while (diff > 1e-24) {
setBoundary(m)
diff = calcDiff(m, d, w, h)
for (i in 0 until h) {
for (j in 0 until w) m[i][j].v -= d[i][j].v
}
}
for (i in 0 until h) {
for (j in 0 until w) {
var k = 0
if (i != 0) k++
if (j != 0) k++
if (i < h - 1) k++
if (j < w - 1) k++
cur[m[i][j].fixed + 1] += d[i][j].v * k
}
}
return (cur[2] - cur[0]) / 2.0
}
fun main(args: Array<String>) {
val mesh = List(S) { List(S) { Node(0.0, 0) } }
val r = 2.0 / iter(mesh, S, S)
println("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.
|
#Python
|
Python
|
class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
return method
example = Example()
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.
|
#Racket
|
Racket
|
#lang racket
(require racket/class)
(define-syntax-rule (send~ obj method x ...)
;; note: this is a naive macro, a real one should avoid evaluating `obj' and
;; the `xs' more than once
(with-handlers ([(λ(e) (and (exn:fail:object? e)
;; only do this if there *is* an `unknown-method'
(memq 'unknown-method (interface->method-names
(object-interface o)))))
(λ(e) (send obj unknown-method 'method x ...))])
(send obj method x ...)))
(define foo%
(class object%
(define/public (foo x)
(printf "foo: ~s\n" x))
(define/public (unknown-method name . xs)
(printf "Unknown method ~s: ~s\n" name xs))
(super-new)))
(define o (new foo%))
(send~ o foo 1) ; => foo: 1
(send~ o whatever 1) ; Unknown method whatever: (1)
|
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
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <functional>
#include <string>
#include <iostream>
#include <vector>
//code for a C++11 compliant compiler
template <class BidirectionalIterator, class T>
void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
std::reverse(first, last);
auto block_last = first;
do {
using std::placeholders::_1;
auto block_first = std::find_if_not(block_last, last,
std::bind(std::equal_to<T>(),_1, separator));
block_last = std::find(block_first, last, separator);
std::reverse(block_first, block_last);
} while(block_last != last);
}
//code for a C++03 compliant compiler
template <class BidirectionalIterator, class T>
void block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
std::reverse(first, last);
BidirectionalIterator block_last = first;
do {
BidirectionalIterator block_first = std::find_if(block_last, last,
std::bind2nd(std::not_equal_to<T>(), separator));
block_last = std::find(block_first, last, separator);
std::reverse(block_first, block_last);
} while(block_last != last);
}
int main() {
std::string str1[] =
{
"---------- 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 -----------------------"
};
std::for_each(begin(str1), end(str1), [](std::string& s){
block_reverse_cpp11(begin(s), end(s), ' ');
std::cout << s << std::endl;
});
std::for_each(begin(str1), end(str1), [](std::string& s){
block_reverse_cpp03(begin(s), end(s), ' ');
std::cout << s << std::endl;
});
return 0;
}
|
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
|
#Pascal
|
Pascal
|
program rot13;
var
line: string;
function rot13(someText: string): string;
var
i: integer;
ch: char;
result: string;
begin
result := '';
for i := 1 to Length(someText) do
begin
ch := someText[i];
case ch of
'A' .. 'M', 'a' .. 'm':
ch := chr(ord(ch)+13);
'N' .. 'Z', 'n' .. 'z':
ch := chr(ord(ch)-13);
end;
result := result + ch;
end;
rot13 := result;
end;
begin
while not eof(input) do
begin
readln(line);
writeln(rot13(line));
end;
end.
|
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
|
#OCaml
|
OCaml
|
let digit x y z = function
1 -> [x]
| 2 -> [x;x]
| 3 -> [x;x;x]
| 4 -> [x;y]
| 5 -> [y]
| 6 -> [y;x]
| 7 -> [y;x;x]
| 8 -> [y;x;x;x]
| 9 -> [x;z]
let rec to_roman x =
if x = 0 then []
else if x < 0 then
invalid_arg "Negative roman numeral"
else if x >= 1000 then
'M' :: to_roman (x - 1000)
else if x >= 100 then
digit 'C' 'D' 'M' (x / 100) @ to_roman (x mod 100)
else if x >= 10 then
digit 'X' 'L' 'C' (x / 10) @ to_roman (x mod 10)
else
digit 'I' 'V' 'X' x
|
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.
|
#Prolog
|
Prolog
|
decode_digit(i, 1).
decode_digit(v, 5).
decode_digit(x, 10).
decode_digit(l, 50).
decode_digit(c, 100).
decode_digit(d, 500).
decode_digit(m, 1000).
decode_string(Sum, _, [], Sum).
decode_string(LastSum, LastValue, [Digit|Rest], NextSum) :-
decode_digit(Digit, Value),
Value < LastValue,
Sum is LastSum - Value,
decode_string(Sum, Value, Rest, NextSum).
decode_string(LastSum, LastValue, [Digit|Rest], NextSum) :-
decode_digit(Digit, Value),
Value >= LastValue,
Sum is LastSum + Value,
decode_string(Sum, Value, Rest, NextSum).
decode_string(Atom, Value) :-
atom_chars(Atom, String),
reverse(String, [Last|Rest]),
decode_digit(Last, Start),
decode_string(Start, Start, Rest, Value).
test :-
decode_string(mcmxc, 1990),
decode_string(mmviii, 2008),
decode_string(mdclxvi, 1666).
|
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.
|
#Ursala
|
Ursala
|
#import std
#import nat
encode = (rlc ==); *= ^lhPrNCT\~&h %nP+ length
decode = (rlc ~&l-=digits); *=zyNCXS ^|DlS/~& iota+ %np
test_data = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
#show+
example =
<
encode test_data,
decode encode test_data>
|
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
|
#APL
|
APL
|
10⍴'ha'
hahahahaha
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Clipper
|
Clipper
|
Function Addsub( x, y )
Return { x+y, x-y }
|
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
|
#Action.21
|
Action!
|
BYTE FUNC IsCycle(CHAR ARRAY s,sub)
BYTE i,j,count
IF sub(0)=0 OR s(0)<sub(0) THEN
RETURN (0)
FI
j=1 count=0
FOR i=1 TO s(0)
DO
IF s(i)#sub(j) THEN
RETURN (0)
FI
j==+1
IF j>sub(0) THEN
j=1 count==+1
FI
OD
IF count>1 THEN
RETURN (1)
FI
RETURN (0)
PROC Test(CHAR ARRAY s)
CHAR ARRAY sub
BYTE len,count
PrintF("%S -> ",s)
count=0
FOR len=1 TO s(0)-1
DO
SCopyS(sub,s,1,len)
IF IsCycle(s,sub) THEN
IF count>0 THEN
Print(", ")
FI
Print(sub)
count==+1
FI
OD
IF count=0 THEN
Print("none")
FI
PutE()
RETURN
PROC Main()
Test("1001110011")
Test("1110111011")
Test("0010010010")
Test("1010101010")
Test("1111111111")
Test("0100101101")
Test("0100100")
Test("101")
Test("11")
Test("00")
Test("1")
RETURN
|
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
|
#8th
|
8th
|
"haystack" /a./ r:match . cr
"haystack" /a./ "blah" s:replace! . cr
|
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
|
#ABAP
|
ABAP
|
DATA: text TYPE string VALUE 'This is a Test'.
FIND FIRST OCCURRENCE OF REGEX 'is' IN text.
IF sy-subrc = 0.
cl_demo_output=>write( 'Regex matched' ).
ENDIF.
REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'.
cl_demo_output=>write( text ).
cl_demo_output=>display( ).
|
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
|
#8080_Assembly
|
8080 Assembly
|
org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reverse a string under HL in place
;; strrev0: reverse a zero-terminated string
;; strrev: reverse a string terminated by the value in A
;; arrayrev: reverse bytes starting at DE and ending at HL
;; Destroys a, b, d, e, h, l registers.
strrev0: xra a ; Zero A
strrev: mov d,h ; Copy string begin to DE
mov e,l
dcx h
strrev_end: inx h ; Find string end in HL
cmp m
jnz strrev_end
dcx h ; Point HL to last character
arrayrev: mov a,h ; If HL<DE, we're done
cmp d
rc
mov a,l
cmp e
rc
ldax d ; Get low character in string
mov b,m ; Get high character in string
mov m,a ; Swap them
mov a,b
stax d
inx d ; Move the low pointer up,
dcx h ; and the high pointer down
jmp arrayrev
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test code (CP/M): ask the user for a string, and reverse it
prompt: db " :gnirts a retne esaelP$"
bufdef: db 127, 0
buf: ds 128 ; one extra byte that will remain 0
newline: lxi d,newline_str
mvi c,9
jmp 5
newline_str: db 13, 10, "$"
test: ;; Reverse and output the prompt
mvi a,'$' ; CP/M string is $-terminated
lxi h,prompt ; Reverse the string
call strrev
lxi d,prompt ; Output the string
mvi c,9
call 5
;; Get input and reverse it
lxi d,bufdef
mvi c,10
call 5
call newline
lxi h,buf
call strrev0 ; 0-terminated due to buffer definition
;; Output reversed input
lxi h,buf
loop: mov e,m
xra a
ora e
rz ; Stop when done
mvi c,2
push h
call 5
pop h
inx h
jmp loop
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#D
|
D
|
import std.stdio, std.array, std.datetime, std.exception,
std.concurrency, core.thread, core.atomic;
final class OutOfInk: Exception {
this() pure nothrow {
super("Out of ink.");
}
}
struct Printer {
string id;
size_t ink;
void printIt(in string line) {
enforce(ink != 0, new OutOfInk);
writefln("%s: %s", id, line);
ink--;
}
}
/// Treats shared lvalue as if it is thread-local.
ref assumeThreadLocal(T)(ref shared T what) pure nothrow {
return *cast(T*)&what;
}
struct RendezvousPrinter {
Printer[] printers;
void print(const(string)[] lines) shared {
OutOfInk savedException;
// Lightweight mutual exclusion
// using shared atomic bool.
shared static bool mutex;
void lock() {
while (!cas(&mutex, false, true))
Thread.sleep(1.hnsecs);
}
void unlock() nothrow {
assert(mutex.atomicLoad!(MemoryOrder.acq));
mutex.atomicStore!(MemoryOrder.rel)(false);
}
while (!lines.empty) {
if (printers.empty) {
// No more printers to try.
assert(savedException !is null);
throw savedException;
}
try {
{
lock;
scope(exit) unlock;
printers.front.assumeThreadLocal
.printIt(lines.front);
}
lines.popFront;
// Increase the chance of interleaved output.
Thread.sleep(10.msecs);
} catch (OutOfInk exc) {
savedException = exc;
// Switch to the next printer.
lock;
scope(exit) unlock;
printers.assumeThreadLocal.popFront;
}
}
}
}
void humptyDumptyTask(shared ref RendezvousPrinter rendezvous) {
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."];
rendezvous.print(humptyDumpty);
}
void motherGooseTask(shared ref RendezvousPrinter rendezvous) {
const motherGoose = ["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."];
rendezvous.print(motherGoose);
}
void main() {
shared rendezvous = RendezvousPrinter
([Printer("main", 5), Printer("reserve", 5)]);
spawn(&humptyDumptyTask, rendezvous);
spawn(&motherGooseTask, rendezvous);
}
|
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.
|
#Applesoft_BASIC
|
Applesoft BASIC
|
print "---------------------------"
print "As a loop"
print "---------------------------"
loop 4 'x ->
print "Example 1"
repeatFunc: function [f,times][
loop times 'x ->
do f
]
print "---------------------------"
print "With a block param"
print "---------------------------"
repeatFunc [print "Example 2"] 4
repeatFunc: function [f,times][
loop times 'x ->
f
]
print "---------------------------"
print "With a function param"
print "---------------------------"
repeatFunc $[][print "Example 3"] 4
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Arturo
|
Arturo
|
print "---------------------------"
print "As a loop"
print "---------------------------"
loop 4 'x ->
print "Example 1"
repeatFunc: function [f,times][
loop times 'x ->
do f
]
print "---------------------------"
print "With a block param"
print "---------------------------"
repeatFunc [print "Example 2"] 4
repeatFunc: function [f,times][
loop times 'x ->
f
]
print "---------------------------"
print "With a function param"
print "---------------------------"
repeatFunc $[][print "Example 3"] 4
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#ALGOL_68
|
ALGOL 68
|
main:(
PROC rename = (STRING source name, dest name)INT:
BEGIN
FILE actual file;
INT errno = open(actual file, source name, stand back channel);
IF errno NE 0 THEN
errno
ELSE
IF reidf possible(actual file) THEN
reidf(actual file, dest name); # change the identification of the book #
errno
ELSE
close(actual file);
-1
FI
FI
END;
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.)
|
#Arturo
|
Arturo
|
fileFrom: "input.txt"
fileTo: "output.txt"
docsFrom: "docs"
docsTo: "mydocs"
rename fileFrom fileTo
rename.directory docsFrom docsTo
rename join.path ["/" fileFrom]
join.path ["/" fileTo]
rename.directory join.path ["/" docsFrom]
join.path ["/" docsTo]
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(ripemd160("Rosetta Code")));
end func;
|
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.
|
#Swift
|
Swift
|
// Circular left shift: http://en.wikipedia.org/wiki/Circular_shift
// Precendence should be the same as <<
infix operator ~<< { precedence 160 associativity none }
public func ~<< (lhs: UInt32, rhs: Int) -> UInt32 {
return (lhs << UInt32(rhs)) | (lhs >> UInt32(32 - rhs));
}
public struct Block {
public init() {}
var message: [UInt32] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
// Initial values
var h₀: UInt32 = 0x67452301
var h₁: UInt32 = 0xEFCDAB89
var h₂: UInt32 = 0x98BADCFE
var h₃: UInt32 = 0x10325476
var h₄: UInt32 = 0xC3D2E1F0
public var hash: [UInt32] {
return [h₀, h₁, h₂, h₃, h₄]
}
// FIXME: Make private as soon as tests support that
public mutating func compress (message: [UInt32]) -> () {
assert(count(message) == 16, "Wrong message size")
var Aᴸ = h₀
var Bᴸ = h₁
var Cᴸ = h₂
var Dᴸ = h₃
var Eᴸ = h₄
var Aᴿ = h₀
var Bᴿ = h₁
var Cᴿ = h₂
var Dᴿ = h₃
var Eᴿ = h₄
for j in 0...79 {
// Left side
let wordᴸ = message[r.Left[j]]
let functionᴸ = f(j)
let Tᴸ: UInt32 = ((Aᴸ &+ functionᴸ(Bᴸ,Cᴸ,Dᴸ) &+ wordᴸ &+ K.Left[j]) ~<< s.Left[j]) &+ Eᴸ
Aᴸ = Eᴸ
Eᴸ = Dᴸ
Dᴸ = Cᴸ ~<< 10
Cᴸ = Bᴸ
Bᴸ = Tᴸ
// Right side
let wordᴿ = message[r.Right[j]]
let functionᴿ = f(79 - j)
let Tᴿ: UInt32 = ((Aᴿ &+ functionᴿ(Bᴿ,Cᴿ,Dᴿ) &+ wordᴿ &+ K.Right[j]) ~<< s.Right[j]) &+ Eᴿ
Aᴿ = Eᴿ
Eᴿ = Dᴿ
Dᴿ = Cᴿ ~<< 10
Cᴿ = Bᴿ
Bᴿ = Tᴿ
}
let T = h₁ &+ Cᴸ &+ Dᴿ
h₁ = h₂ &+ Dᴸ &+ Eᴿ
h₂ = h₃ &+ Eᴸ &+ Aᴿ
h₃ = h₄ &+ Aᴸ &+ Bᴿ
h₄ = h₀ &+ Bᴸ &+ Cᴿ
h₀ = T
}
public func f (j: Int) -> ((UInt32, UInt32, UInt32) -> UInt32) {
switch j {
case let index where j < 0:
assert(false, "Invalid j")
return {(_, _, _) in 0 }
case let index where j <= 15:
return {(x, y, z) in x ^ y ^ z }
case let index where j <= 31:
return {(x, y, z) in (x & y) | (~x & z) }
case let index where j <= 47:
return {(x, y, z) in (x | ~y) ^ z }
case let index where j <= 63:
return {(x, y, z) in (x & z) | (y & ~z) }
case let index where j <= 79:
return {(x, y, z) in x ^ (y | ~z) }
default:
assert(false, "Invalid j")
return {(_, _, _) in 0 }
}
}
public enum K {
case Left, Right
public subscript(j: Int) -> UInt32 {
switch j {
case let index where j < 0:
assert(false, "Invalid j")
return 0
case let index where j <= 15:
return self == .Left ? 0x00000000 : 0x50A28BE6
case let index where j <= 31:
return self == .Left ? 0x5A827999 : 0x5C4DD124
case let index where j <= 47:
return self == .Left ? 0x6ED9EBA1 : 0x6D703EF3
case let index where j <= 63:
return self == .Left ? 0x8F1BBCDC : 0x7A6D76E9
case let index where j <= 79:
return self == .Left ? 0xA953FD4E : 0x00000000
default:
assert(false, "Invalid j")
return 0
}
}
}
public enum r {
case Left, Right
public subscript (j: Int) -> Int {
switch j {
case let index where j < 0:
assert(false, "Invalid j")
return 0
case let index where j <= 15:
if self == .Left {
return index
} else {
return [5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12][index]
}
case let index where j <= 31:
if self == .Left {
return [ 7, 4,13, 1,10, 6,15, 3,12, 0, 9, 5, 2,14,11, 8][index - 16]
} else {
return [ 6,11, 3, 7, 0,13, 5,10,14,15, 8,12, 4, 9, 1, 2][index - 16]
}
case let index where j <= 47:
if self == .Left {
return [3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12][index - 32]
} else {
return [15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13][index - 32]
}
case let index where j <= 63:
if self == .Left {
return [1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2][index - 48]
} else {
return [8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14][index - 48]
}
case let index where j <= 79:
if self == .Left {
return [ 4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13][index - 64]
} else {
return [12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11][index - 64]
}
default:
assert(false, "Invalid j")
return 0
}
}
}
public enum s {
case Left, Right
public subscript(j: Int) -> Int {
switch j {
case let index where j < 0:
assert(false, "Invalid j")
return 0
case let index where j <= 15:
return (self == .Left ? [11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8] : [8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6])[j]
case let index where j <= 31:
return (self == .Left ? [7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12] : [9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11])[j - 16]
case let index where j <= 47:
return (self == .Left ? [11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5] : [9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5])[j - 32]
case let index where j <= 63:
return (self == .Left ? [11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12] : [15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8])[j - 48]
case let index where j <= 79:
return (self == .Left ? [9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6] : [8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11])[j - 64]
default:
assert(false, "Invalid j")
return 0
}
}
}
}
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ResistanceMatrix[g_Graph] := With[{n = VertexCount[g], km = KirchhoffMatrix[g]},
Table[ ReplacePart[ Diagonal[ DrazinInverse[ ReplacePart[km, k -> UnitVector[n, k]]]], k -> 0],
{k, n}]
]
rm = ResistanceMatrix[GridGraph[{10, 10}]];
N[rm[[12, 68]], 40]
|
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
|
#Maxima
|
Maxima
|
/* Place a current souce between A and B, providing 1 A. Then we are really looking
for the potential at A and B, since I = R (V(B) - V(A)) where I is given and we want R.
Atually, we will compute potential at each node, except A where we assume it's 0.
Without this assumption, there would be infinitely many solutions since potential
is known up to a constant. For A we will simply write the equation V(A) = 0, to
keep the program simple.
Hence, for a general grid of p rows and q columns, there are n = p * q nodes,
so n unknowns, and n equations. Write Kirchhoff's current law at each node.
Be careful with the node A (equation A = 0) and the node B (there is a constant
current to add, from the source, that will go in the constant terms of the system).
Finally, we have a n x n linear system of equations to solve. Simply use Maxima's
builtin LU decomposition.
Since all computations are exact, the result will be also exact, written as a fraction.
Also, the program can work with any grid, and any two nodes on the grid.
For those who want more speed and less space, notice the system is sparse and necessarily
symmetric, so one can use conjugate gradient or any other sparse symmetric solver. */
/* Auxiliary function to get rid of the borders */
ongrid(i, j, p, q) := is(i >= 1 and i <= p and j >= 1 and j <= q)$
grid_resistor(p, q, ai, aj, bi, bj) := block(
[n: p * q, A, B, M, k, c, V],
A: zeromatrix(n, n),
for i thru p do
for j thru q do (
k: (i - 1) * q + j,
if i = ai and j = aj then
A[k, k]: 1
else (
c: 0,
if ongrid(i + 1, j, p, q) then (c: c + 1, A[k, k + q]: -1),
if ongrid(i - 1, j, p, q) then (c: c + 1, A[k, k - q]: -1),
if ongrid(i, j + 1, p, q) then (c: c + 1, A[k, k + 1]: -1),
if ongrid(i, j - 1, p, q) then (c: c + 1, A[k, k - 1]: -1),
A[k, k]: c
)
),
B: zeromatrix(n, 1),
B[k: (bi - 1) * q + bj, 1]: 1,
M: lu_factor(A),
V: lu_backsub(M, B),
V[k, 1]
)$
grid_resistor(10, 10, 2, 2, 8, 7);
455859137025721 / 283319837425200
bfloat(%), fpprec = 40;
1.608991241730729655954495520510088761201b0
/* Some larger example */
grid_resistor(20, 20, 1, 1, 20, 20);
129548954101732562831760781545158173626645023 / 33283688571680493510612137844679320717594861
bfloat(%), fpprec = 40;
3.89226554090400912102670691601064387507b0
|
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.
|
#Raku
|
Raku
|
class Farragut {
method FALLBACK ($name, *@rest) {
say "{self.WHAT.raku}: $name.tc() the @rest[], full speed ahead!";
}
}
class Sparrow is Farragut { }
Farragut.damn: 'torpedoes';
Sparrow.hoist: <Jolly Roger mateys>;
|
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.
|
#Ring
|
Ring
|
load "stdlibcore.ring"
new test {
anyMethodThatDoesNotExist() # Define and call the new method
anyMethodThatDoesNotExist() # Call the new method
}
class test
func braceerror
if substr(cCatchError,"Error (R3)")
? "You are calling a method that doesn't exist!"
aError = Split(cCatchError," ")
cMethodName = aError[len(aError)]
? "The Method Name: " + cMethodName
AddMethod(self,cMethodName,func {
? "Hello from the new method!"
})
? "We defined the new method!"
call cMethodName()
ok
|
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.
|
#Ruby
|
Ruby
|
class Example
def foo
puts "this is foo"
end
def bar
puts "this is bar"
end
def method_missing(name, *args, &block)
puts "tried to handle unknown method %s" % name # name is a symbol
unless args.empty?
puts "it had arguments: %p" % [args]
end
end
end
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
|
#Clojure
|
Clojure
|
(def 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 -----------------------")
(dorun
(map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.