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/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.
#sed
sed
  /^$/ b :start /^[0-9]/ b s/^/1/ :loop h /^9+([^0-9])\1+/ { s/^(9+).*/0\1/ y/09/10/ G s/^(.+)\n[0-9]+.(.*)/\1\2/ b loop } /^[0-9]*[0-8]([^0-9])\1+/ { s/^[0-9]*([0-8]).*/\1/ y/012345678/123456789/ G s/^(.)\n([0-9]*)[0-8].(.*)/\2\1\3/ b loop } /^[0-9]+9+([^0-9])\1+/ { s/^[0-9]*([0-8]9+).*/\1/ y/0123456789/1234567890/ G s/^(.+)\n([0-9]*)[0-8]9+.(.*)/\2\1\3/ b loop } s/^([0-9]+.)(.*)/\2\1/ b start  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#6502_Assembly
6502 Assembly
UnpackNibbles: ; Takes accumulator as input. ; Separates a two-digit hex number into its component "nibbles." Left nibble in X, right nibble in Y.   pha  ;backup the input. and #$0F  ;chop off the left nibble. What remains is our Y. tay pla  ;restore input and #$F0  ;chop off the right nibble. What remains is our X, but it needs to be bit shifted into the right nibble. lsr lsr lsr lsr tax  ;store in X rts
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#68000_Assembly
68000 Assembly
foo: MOVE.L D2,D0 MOVE.L D3,D1 ADD.L D1,D0 SUB.L D2,D3 MOVE.L D3,D1 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.
#Julia
Julia
using Nettle   labels = ["\"\" (empty string)", "\"a\"", "\"abc\"", "\"message digest\"", "\"a...z\"", "\"abcdbcde...nopq\"", "\"A...Za...z0...9\"", "8 times \"1234567890\"", "1 million times \"a\""] texts = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "1234567890" ^ 8, "a" ^ 1_000_000] expects = ["9c1185a5c5e9fc54612808977ee8f548b2258d31", "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", "5d0689ef49d2fae572b881b123a85ffa21595f36", "f71c27109c692c1b56bbdceb5b9d2865b3708dbc", "12a053384a9c0c88e405a06c27dcf49ada62eb2b", "b0e20b6e3116640286ed3a87a5713079b21f5189", "9b752e45573d4b39f4dbd3323cab82bf63326bfb", "52783243c1697bdbe16d37f97f68f08325dc1528"]   for (lab, text, expect) in zip(labels, texts, expects) digest = hexdigest("ripemd160", text) println("# $lab\n -> digest: $digest\n -> expect: $expect") end
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
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"ARRAYLIB" *FLOAT 64 @% = &F0F   PRINT "Resistance = "; FNresistormesh(10, 10, 1, 1, 7, 6) " ohms" END   DEF FNresistormesh(ni%, nj%, ai%, aj%, bi%, bj%) LOCAL c%, i%, j%, k%, n%, A(), B() n% = ni% * nj% DIM A(n%-1, n%-1), B(n%-1, 0) FOR i% = 0 TO ni%-1 FOR j% = 0 TO nj%-1 k% = i% * nj% + j% IF i% = ai% AND j% = aj% THEN A(k%, k%) = 1 ELSE c% = 0 IF (i% + 1) < ni% c% += 1 : A(k%, k% + nj%) = -1 IF i% > 0 c% += 1 : A(k%, k% - nj%) = -1 IF (j% + 1) < nj% c% += 1 : A(k%, k% + 1) = -1 IF j% > 0 c% += 1 : A(k%, k% - 1) = -1 A(k%, k%) = c% ENDIF NEXT NEXT k% = bi% * nj% + bj% B(k%, 0) = 1 PROC_invert(A()) B() = A().B() = B(k%, 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.
#Go
Go
package main   import ( "fmt" "reflect" )   type example struct{}   func (example) Foo() int { return 42 }   // a method to call another method by name func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { // it's known. call it. return int(m.Call(nil)[0].Int()) } // otherwise it's unknown. handle as needed. fmt.Println("Unknown method:", n) return 0 }   func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
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.
#Groovy
Groovy
class MyObject { def foo() { println 'Invoked foo' } def methodMissing(String name, args) { println "Invoked missing method $name$args" } }
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#AppleScript
AppleScript
on run   unlines(map(reverseWords, |lines|("---------- 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 -----------------------")))   end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- reverseWords :: String -> String on reverseWords(str) unwords(|reverse|(|words|(str))) end reverseWords   -- |reverse| :: [a] -> [a] on |reverse|(xs) if class of xs is text then (reverse of characters of xs) as text else reverse of xs end if end |reverse|   -- |lines| :: Text -> [Text] on |lines|(str) splitOn(linefeed, str) end |lines|   -- |words| :: Text -> [Text] on |words|(str) splitOn(space, str) end |words|   -- ulines :: [Text] -> Text on unlines(lstLines) intercalate(linefeed, lstLines) end unlines   -- unwords :: [Text] -> Text on unwords(lstWords) intercalate(space, lstWords) end unwords   -- splitOn :: Text -> Text -> [Text] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} set lstParts to text items of strMain set my text item delimiters to dlm lstParts end splitOn   -- interCalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm strJoined end intercalate   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to lambda(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property lambda : f end script end if end mReturn  
http://rosettacode.org/wiki/Repunit_primes
Repunit primes
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits. Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime. In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.) In base three: 111, 1111111, 1111111111111, etc. Repunit primes, by definition, are also circular primes. Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime. Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc. Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences. Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already. Task For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000. Stretch Increase the limit to 2700 (or as high as you have patience for.) See also Wikipedia: Repunit primes OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2) OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3) OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5) OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6) OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7) OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10) OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11) OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12) OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13) OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14) OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15) Related task: Circular primes
#Sidef
Sidef
var limit = 1000   say "Repunit prime digits (up to #{limit}) in:"   for n in (2..20) { printf("Base %2d: %s\n", n, {|k| is_prime((n**k - 1) / (n-1)) }.grep(1..limit)) }
http://rosettacode.org/wiki/Repunit_primes
Repunit primes
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits. Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime. In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.) In base three: 111, 1111111, 1111111111111, etc. Repunit primes, by definition, are also circular primes. Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime. Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc. Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences. Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already. Task For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000. Stretch Increase the limit to 2700 (or as high as you have patience for.) See also Wikipedia: Repunit primes OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2) OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3) OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5) OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6) OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7) OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10) OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11) OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12) OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13) OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14) OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15) Related task: Circular primes
#Wren
Wren
/* repunit_primes.wren */   import "./gmp" for Mpz import "./math" for Int import "./fmt" for Fmt import "./str" for Str   var limit = 2700 var primes = Int.primeSieve(limit)   for (b in 2..36) { var rPrimes = [] for (p in primes) { var s = Mpz.fromStr(Str.repeat("1", p), b) if (s.probPrime(15) > 0) rPrimes.add(p) } Fmt.print("Base $2d: $n", b, rPrimes) }
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
#MUMPS
MUMPS
Rot13(in) New low,rot,up Set up="ABCDEFGHIJKLMNOPQRSTUVWXYZ" Set low="abcdefghijklmnopqrstuvwxyz" Set rot=$Extract(up,14,26)_$Extract(up,1,13) Set rot=rot_$Extract(low,14,26)_$Extract(low,1,13) Quit $Translate(in,up_low,rot)   Write $$Rot13("Hello World!") ; Uryyb Jbeyq! Write $$Rot13("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ; NOPQRSTUVWXYZABCDEFGHIJKLM
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman 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
#LOLCODE
LOLCODE
HAI 1.2 I HAS A Romunz ITZ A BUKKIT Romunz HAS A SRS 0 ITZ "M" Romunz HAS A SRS 1 ITZ "CM" Romunz HAS A SRS 2 ITZ "D" Romunz HAS A SRS 3 ITZ "CD" Romunz HAS A SRS 4 ITZ "C" Romunz HAS A SRS 5 ITZ "XC" Romunz HAS A SRS 6 ITZ "L" Romunz HAS A SRS 7 ITZ "XL" Romunz HAS A SRS 8 ITZ "X" Romunz HAS A SRS 9 ITZ "IX" Romunz HAS A SRS 10 ITZ "V" Romunz HAS A SRS 11 ITZ "IV" Romunz HAS A SRS 12 ITZ "I"   I HAS A Valuez ITZ A BUKKIT Valuez HAS A SRS 0 ITZ 1000 Valuez HAS A SRS 1 ITZ 900 Valuez HAS A SRS 2 ITZ 500 Valuez HAS A SRS 3 ITZ 400 Valuez HAS A SRS 4 ITZ 100 Valuez HAS A SRS 5 ITZ 90 Valuez HAS A SRS 6 ITZ 50 Valuez HAS A SRS 7 ITZ 40 Valuez HAS A SRS 8 ITZ 10 Valuez HAS A SRS 9 ITZ 9 Valuez HAS A SRS 10 ITZ 5 Valuez HAS A SRS 11 ITZ 4 Valuez HAS A SRS 12 ITZ 1   HOW IZ I Romunize YR Num I HAS A Result ITZ "" IM IN YR Outer UPPIN YR Dummy TIL BOTH SAEM Num AN 0 IM IN YR Inner UPPIN YR Index TIL BOTH SAEM Index AN 13 BOTH SAEM Num AN BIGGR OF Num AN Valuez'Z SRS Index, O RLY? YA RLY Num R DIFF OF Num AN Valuez'Z SRS Index Result R SMOOSH Result Romunz'Z SRS Index MKAY GTFO OIC IM OUTTA YR Inner IM OUTTA YR Outer FOUND YR Result IF U SAY SO   VISIBLE SMOOSH 2009 " = " I IZ Romunize YR 2009 MKAY MKAY VISIBLE SMOOSH 1666 " = " I IZ Romunize YR 1666 MKAY MKAY VISIBLE SMOOSH 3888 " = " I IZ Romunize YR 3888 MKAY MKAY KTHXBYE
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.
#OCaml
OCaml
let decimal_of_roman roman = let arabic = ref 0 in let lastval = ref 0 in for i = (String.length roman) - 1 downto 0 do let n = match roman.[i] with | 'M' | 'm' -> 1000 | 'D' | 'd' -> 500 | 'C' | 'c' -> 100 | 'L' | 'l' -> 50 | 'X' | 'x' -> 10 | 'V' | 'v' -> 5 | 'I' | 'i' -> 1 | _ -> 0 in if n < !lastval then arabic := !arabic - n else arabic := !arabic + n; lastval := n done; !arabic   let () = Printf.printf " %d\n" (decimal_of_roman "MCMXC"); Printf.printf " %d\n" (decimal_of_roman "MMVIII"); Printf.printf " %d\n" (decimal_of_roman "MDCLXVI"); ;;
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "scanstri.s7i";   const func string: letterRleEncode (in string: data) is func result var string: result is ""; local var char: code is ' '; var integer: index is 1; begin if length(data) <> 0 then code := data[1]; repeat incr(index); until index > length(data) or code <> data[index]; result := str(pred(index)) & str(code) & letterRleEncode(data[index ..]); end if; end func;   const func string: letterRleDecode (in var string: data) is func result var string: result is ""; local var integer: count is 0; begin if length(data) <> 0 then count := integer parse getDigits(data); result := data[1 len 1] mult count & letterRleDecode(data[2 ..]); end if; end func;   const proc: main is func begin writeln(letterRleEncode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); writeln(letterRleDecode("12W1B12W3B24W1B14W")); end func;
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
#11l
11l
print(‘ha’ * 5)
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#8086_Assembly
8086 Assembly
mov ax,cx mov bx,dx add ax,bx sub cx,dx mov bx,cx ret
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.
#Kotlin
Kotlin
import org.bouncycastle.crypto.digests.RIPEMD160Digest import org.bouncycastle.util.encoders.Hex import kotlin.text.Charsets.US_ASCII   fun RIPEMD160Digest.inOneGo(input : ByteArray) : ByteArray { val output = ByteArray(digestSize)   update(input, 0, input.size) doFinal(output, 0)   return output }   fun main(args: Array<String>) { val input = "Rosetta Code".toByteArray(US_ASCII) val output = RIPEMD160Digest().inOneGo(input)   Hex.encode(output, System.out) System.out.flush() }
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
#C
C
#include <stdio.h> #include <stdlib.h>   #define S 10 typedef struct { double v; int fixed; } node;   #define each(i, x) for(i = 0; i < x; i++) node **alloc2(int w, int h) { int i; node **a = calloc(1, sizeof(node*)*h + sizeof(node)*w*h); each(i, h) a[i] = i ? a[i-1] + w : (node*)(a + h); return a; }   void set_boundary(node **m) { m[1][1].fixed = 1; m[1][1].v = 1; m[6][7].fixed = -1; m[6][7].v = -1; }   double calc_diff(node **m, node **d, int w, int h) { int i, j, n; double v, total = 0; each(i, h) each(j, w) { v = 0; n = 0; if (i) v += m[i-1][j].v, n++; if (j) 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++;   d[i][j].v = v = m[i][j].v - v / n; if (!m[i][j].fixed) total += v * v; } return total; }   double iter(node **m, int w, int h) { node **d = alloc2(w, h); int i, j; double diff = 1e10; double cur[] = {0, 0, 0};   while (diff > 1e-24) { set_boundary(m); diff = calc_diff(m, d, w, h); each(i,h) each(j, w) m[i][j].v -= d[i][j].v; }   each(i, h) each(j, w) cur[ m[i][j].fixed + 1 ] += d[i][j].v * (!!i + !!j + (i < h-1) + (j < w -1));   free(d); return (cur[2] - cur[0])/2; }   int main() { node **mesh = alloc2(S, S); printf("R = %g\n", 2 / iter(mesh, S, S)); return 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.
#Icon_and_Unicon
Icon and Unicon
procedure DynMethod(obj,meth,arglist[]) local m   if not (type(obj) ? ( tab(find("__")), ="__state", pos(0))) then runerr(205,obj) # invalid value - not an object   if meth == ("initially"|"UndefinedMethod") then fail # avoid protected   m := obj.__m # get methods list if fieldnames(m) == meth then # method exists? return m[meth]!push(copy(arglist),obj) # ... call it else if fieldnames(m) == "UndefinedMethod" then # handler exists? return obj.UndefinedMethod!arglist # ... call it else runerr(207,obj) # error invalid method (i.e. field) end
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.
#Io
Io
Example := Object clone do( foo := method(writeln("this is foo")) bar := method(writeln("this is bar")) forward := method( writeln("tried to handle unknown method ",call message name) if( call hasArgs, writeln("it had arguments: ",call evalArgs) ) ) )   example := Example clone   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: list("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
#Applesoft_BASIC
Applesoft BASIC
100 DATA"---------- ICE AND FIRE ------------" 110 DATA" " 120 DATA"FIRE, IN END WILL WORLD THE SAY SOME" 130 DATA"ICE. IN SAY SOME " 140 DATA"DESIRE OF TASTED I'VE WHAT FROM " 150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I " 160 DATA" " 170 DATA"... ELIDED PARAGRAPH LAST ... " 180 DATA" " 190 DATA"FROST ROBERT -----------------------"   200 FOR L = 1 TO 10 210 READ T$ 220 I = LEN(T$) 240 IF I THEN GOSUB 300 : PRINT W$; : IF I THEN PRINT " "; : GOTO 240 250 PRINT 260 NEXT L 270 END   300 W$ = "" 310 FOR I = I TO 1 STEP -1 320 IF MID$(T$, I, 1) = " " THEN NEXT I : RETURN 330 FOR I = I TO 1 STEP -1 340 C$ = MID$(T$, I, 1) 350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I 360 RETURN  
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
#Nanoquery
Nanoquery
def rot13(plaintext) uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase = "abcdefghijklmnopqrstuvwxyz"   cypher = "" for char in plaintext if uppercase .contains. char cypher += uppercase[uppercase[char] - 13] else if lowercase .contains. char cypher += lowercase[lowercase[char] - 13] else cypher += char end end   return cypher 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
#LotusScript
LotusScript
  Function toRoman(value) As String Dim arabic(12) As Integer Dim roman(12) As String   arabic(0) = 1000 arabic(1) = 900 arabic(2) = 500 arabic(3) = 400 arabic(4) = 100 arabic(5) = 90 arabic(6) = 50 arabic(7) = 40 arabic(8) = 10 arabic(9) = 9 arabic(10) = 5 arabic(11) = 4 arabic(12) = 1   roman(0) = "M" roman(1) = "CM" roman(2) = "D" roman(3) = "CD" roman(4) = "C" roman(5) = "XC" roman(6) = "L" roman(7) = "XL" roman(8) = "X" roman(9) = "IX" roman(10) = "V" roman(11) = "IV" roman(12) = "I"   Dim i As Integer, result As String   For i = 0 To 12 Do While value >= arabic(i) result = result + roman(i) value = value - arabic(i) Loop Next i   toRoman = result End Function    
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.
#PARI.2FGP
PARI/GP
fromRoman(s)={ my(v=Vecsmall(s),key=vector(88),cur,t=0,tmp); key[73]=1;key[86]=5;key[88]=10;key[76]=50;key[67]=100;key[68]=500;key[77]=1000; cur=key[v[1]]; for(i=2,#v, tmp=key[v[i]]; if(!cur, cur=tmp; next); if(tmp>cur, t+=tmp-cur; cur=0 , t+=cur; cur=tmp ) ); t+cur };
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.
#Sidef
Sidef
func encode(str) { str.gsub(/((.)(\2*))/, {|a,b| "#{a.len}#{b}" }); }   func decode(str) { str.gsub(/(\d+)(.)/, {|a,b| b * a.to_i }); }
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks 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
* Repeat a string - 19/04/2020 REPEATS CSECT USING REPEATS,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability XPRNT C24,24 print c24 LA R1,PARMLST pg=repeat(cx,ii) - repeat('abc ',6) BAL R14,REPEAT call repeat XPRNT PG,L'PG print pg L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling save REPEAT CNOP 0,4 procedure repeat(b,a,i) STM R2,R8,REPEATSA save registers L R2,0(R1) @b=%r1 L R3,4(R1) @a=%(r1+4) L R4,8(R1) @i=%(r1+8) LR R5,R3 length(a) before a SH R5,=H'2' @lengh(a) LH R6,0(R5) l=length(a) LR R7,R6 l BCTR R7,0 l-1 L R8,0(R4) i=%r4 LTR R8,R8 if i<=0 BNP RET then return LOOP EX R7,MVCX move a to b len R6 AR R2,R6 @b+=l BCT R8,LOOP loop i times RET LM R2,R8,REPEATSA restore registers BR R14 return PARMLST DC A(PG,CX,II) parmlist REPEATSA DS 7F local savearea MVCX MVC 0(0,R2),0(R3) move @ R3 to @ R2 C24 DC 6C'xyz ' constant repeat - repeat('xyz ',6) LCX DC AL2(L'CX) lengh(cc) CX DC CL4'abc ' cx II DC F'6' ii PG DC CL80' ' pg REGEQU END REPEATS
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ACL2
ACL2
;; To return multiple values: (defun multiple-values (a b) (mv a b))   ;; To extract the values: (mv-let (x y) (multiple-values 1 2) (+ x y))
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.
#Lasso
Lasso
  cipher_digest("Rosetta Code", -digest='RIPEMD160', -hex)  
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
#C.23
C#
using System; using System.Collections.Generic;   namespace ResistorMesh { class Node { public Node(double v, int fixed_) { V = v; Fixed = fixed_; }   public double V { get; set; } public int Fixed { get; set; } }   class Program { static void SetBoundary(List<List<Node>> m) { m[1][1].V = 1.0; m[1][1].Fixed = 1;   m[6][7].V = -1.0; m[6][7].Fixed = -1; }   static double CalcuateDifference(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[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; }   static double Iter(List<List<Node>> m, int w, int h) { List<List<Node>> d = new List<List<Node>>(h); for (int i = 0; i < h; i++) { List<Node> t = new List<Node>(w); for (int j = 0; j < w; j++) { t.Add(new Node(0.0, 0)); } d.Add(t); }   double[] curr = new double[3]; double diff = 1e10;   while (diff > 1e-24) { SetBoundary(m); diff = CalcuateDifference(m, d, w, h); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { m[i][j].V -= d[i][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++; curr[m[i][j].Fixed + 1] += d[i][j].V * k; } }   return (curr[2] - curr[0]) / 2.0; }   const int S = 10; static void Main(string[] args) { List<List<Node>> mesh = new List<List<Node>>(S); for (int i = 0; i < S; i++) { List<Node> t = new List<Node>(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); Console.WriteLine("R = {0:F15}", 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.
#J
J
example=:3 :0 doSomething_z_=: assert&0 bind 'doSomething was not implemented' doSomething__y '' )   doSomething_adhoc1_=: smoutput bind 'hello world' dSomethingElse_adhoc2_=: smoutput bind 'hello world'
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.
#JavaScript
JavaScript
  obj = new Proxy({}, { get : function(target, prop) { if(target[prop] === undefined) return function() { console.log('an otherwise undefined function!!'); }; else return target[prop]; } }); obj.f() ///'an otherwise undefined function!!' obj.l = function() {console.log(45);}; obj.l(); ///45  
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
#Arturo
Arturo
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 -----------------------}   reversed: map split.lines text => [join.with:" " reverse split.words &]   print join.with:"\n" reversed
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
#Neko
Neko
/* ROT-13 in Neko */   /* Assume ASCII encoding */ var rotate13 = function(c) { if (c >= 65 && c <= 77) || (c >= 97 && c <= 109) c += 13 else if (c >= 78 && c <= 90) || (c >= 110 && c <= 122) c -= 13 return c }   var rot13 = function(s) { var r = $scopy(s) var len = $ssize(r) var pos = 0 while pos < len { $sset(r, pos, rotate13($sget(r, pos))) pos += 1 } return r }   var msg = $loader.args[0] if msg == null { var testing = "[abcdefghijklmnopqrstuvwxyz 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ]" $print(testing, "\n", replaced = rot13(testing), "\n") $print(rot13(replaced), "\n") $print("\n") msg = "The secret message said \"Open Sesame!\"" } $print(msg, "\n", replaced = rot13(msg), "\n") $print(rot13(replaced), "\n")
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Lua
Lua
romans = { {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"} }   k = io.read() + 0 for _, v in ipairs(romans) do --note that this is -not- ipairs. val, let = unpack(v) while k >= val do k = k - val io.write(let) end end print()
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#Perl
Perl
use 5.10.0;   { my @trans = ( [M => 1000], [CM => 900], [D => 500], [CD => 400], [C => 100], [XC => 90], [L => 50], [XL => 40], [X => 10], [IX => 9], [V => 5], [IV => 4], [I => 1], );   sub from_roman { my $r = shift; my $n = 0; foreach my $pair (@trans) { my ($k, $v) = @$pair; $n += $v while $r =~ s/^$k//i; } return $n } }   say "$_: ", from_roman($_) for qw(MCMXC MDCLXVI MMVIII);
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.
#Smalltalk
Smalltalk
|compress decompress| compress := [:string | String streamContents:[:out | |count prev|   count := 0. (string,'*') "trick to avoid final run handling in loop" inject:nil into:[:prevChar :ch | ch ~= prevChar ifTrue:[ count = 0 ifFalse:[ count printOn:out. out nextPut:prevChar. count := 0. ]. ]. count := count + 1. ch ] ] ].   decompress := [:string | String streamContents:[:out | string readingStreamDo:[:in | [in atEnd] whileFalse:[ |n ch| n := Integer readFrom:in. ch := in next. out next:n put:ch. ] ] ]. ].
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
#4DOS_Batch
4DOS Batch
gosub repeat ha 5 echo %@repeat[*,5] quit   :Repeat [String Times] do %Times% echos %String% enddo echo. return
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Action.21
Action!
SET EndProg=*
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; procedure MultiReturn is procedure SumAndDiff (x, y : Integer; sum, diff : out Integer) is begin sum := x + y; diff := x - y; end SumAndDiff; inta : Integer := 5; intb : Integer := 3; thesum, thediff : Integer; begin SumAndDiff (inta, intb, thesum, thediff); Put_Line ("Sum:" & Integer'Image (thesum)); Put_Line ("Diff:" & Integer'Image (thediff)); end MultiReturn;  
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.
#Lua
Lua
#!/usr/bin/lua   require "crypto"   print(crypto.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
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector>   class Node { private: double v; int fixed;   public: Node() : v(0.0), fixed(0) { // empty }   Node(double v, int fixed) : v(v), fixed(fixed) { // empty }   double getV() const { return v; }   void setV(double nv) { v = nv; }   int getFixed() const { return fixed; }   void setFixed(int nf) { fixed = nf; } };   void setBoundary(std::vector<std::vector<Node>>& m) { m[1][1].setV(1.0); m[1][1].setFixed(1);   m[6][7].setV(-1.0); m[6][7].setFixed(-1); }   double calculateDifference(const std::vector<std::vector<Node>>& m, std::vector<std::vector<Node>>& d, const int w, const 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[i - 1][j].getV(); n++; } if (j > 0) { v += m[i][j - 1].getV(); n++; } if (i + 1 < h) { v += m[i + 1][j].getV(); n++; } if (j + 1 < w) { v += m[i][j + 1].getV(); n++; } v = m[i][j].getV() - v / n; d[i][j].setV(v); if (m[i][j].getFixed() == 0) { total += v * v; } } } return total; }   double iter(std::vector<std::vector<Node>>& m, const int w, const int h) { using namespace std; vector<vector<Node>> d; for (int i = 0; i < h; ++i) { vector<Node> t(w); d.push_back(t); }   double curr[] = { 0.0, 0.0, 0.0 }; double diff = 1e10;   while (diff > 1e-24) { setBoundary(m); diff = calculateDifference(m, d, w, h); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { m[i][j].setV(m[i][j].getV() - d[i][j].getV()); } } }   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; curr[m[i][j].getFixed() + 1] += d[i][j].getV()*k; } }   return (curr[2] - curr[0]) / 2.0; }   const int S = 10; int main() { using namespace std; vector<vector<Node>> mesh;   for (int i = 0; i < S; ++i) { vector<Node> t(S); mesh.push_back(t); }   double r = 2.0 / iter(mesh, S, S); cout << "R = " << setprecision(15) << r << '\n';   return 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.
#Julia
Julia
  function add(a, b) try a + b catch println("caught exception") a * b end end     println(add(2, 6)) println(add(1//2, 1//2)) println(add("Hello ", "world"))  
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.
#Kotlin
Kotlin
// Kotlin JS version 1.2.0 (Firefox 43)   class C { // this method prevents a TypeError being thrown if an unknown method is called fun __noSuchMethod__(id: String, args: Array<Any>) { println("Class C does not have a method called $id") if (args.size > 0) println("which takes arguments: ${args.asList()}") } }   fun main(args: Array<String>) { val c: dynamic = C() // 'dynamic' turns off compile time checks c.foo() // the compiler now allows this call even though foo() is undefined }
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
#AutoHotkey
AutoHotkey
Data := " (Join`r`n ---------- 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 ----------------------- )"   Loop, Parse, Data, `n, `r { Loop, Parse, A_LoopField, % A_Space Line := A_LoopField " " Line Output .= Line "`n", Line := "" } MsgBox, % RTrim(Output, "`n")
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   parse arg fileNames   rdr = BufferedReader   do if fileNames.length > 0 then do loop n_ = 1 for fileNames.words fileName = fileNames.word(n_) rdr = BufferedReader(FileReader(File(fileName))) encipher(rdr) end n_ end else do rdr = BufferedReader(InputStreamReader(System.in)) encipher(rdr) end catch ex = IOException ex.printStackTrace end   return   method encipher(rdr = BufferedReader) public static signals IOException   loop label l_ forever line = rdr.readLine if line = null then leave l_ say rot13(line) end l_ return   method rot13(input) public static signals IllegalArgumentException   return caesar(input, 13, isFalse)   method caesar(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException   if idx < 1 | idx > 25 then signal IllegalArgumentException()   -- 12345678901234567890123456 itab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' shift = itab.length - idx parse itab tl +(shift) tr otab = tr || tl   if caps then input = input.upper   cipher = input.translate(itab || itab.lower, otab || otab.lower)   return cipher   method caesar_encipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException   return caesar(input, idx, caps)   method caesar_decipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException   return caesar(input, int(26) - idx, isFalse)   method caesar_encipher(input = Rexx, idx = int) public static signals IllegalArgumentException   return caesar(input, idx, isFalse)   method caesar_decipher(input = Rexx, idx = int) public static signals IllegalArgumentException   return caesar(input, int(26) - idx, isFalse)   method caesar_encipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException   return caesar(input, idx, opt)   method caesar_decipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException   return caesar(input, int(26) - idx, opt)   method caesar(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException   if opt.upper.abbrev('U') >= 1 then caps = isTrue else caps = isFalse   return caesar(input, idx, caps)   method caesar(input = Rexx, idx = int) public static signals IllegalArgumentException   return caesar(input, idx, isFalse)   method isTrue public static returns boolean return (1 == 1)   method isFalse public static returns boolean return \isTrue  
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
#M4
M4
define(`roman',`ifelse(eval($1>=1000),1,`M`'roman(eval($1-1000))', `ifelse(eval($1>=900),1,`CM`'roman(eval($1-900))', `ifelse(eval($1>=500),1,`D`'roman(eval($1-500))', `ifelse(eval($1>=100),1,`C`'roman(eval($1-100))', `ifelse(eval($1>=90),1,`XC`'roman(eval($1-90))', `ifelse(eval($1>=50),1,`L`'roman(eval($1-50))', `ifelse(eval($1>=40),1,`XL`'roman(eval($1-40))', `ifelse(eval($1>=10),1,`X`'roman(eval($1-10))', `ifelse(eval($1>=9),1,`IX`'roman(eval($1-9))', `ifelse(eval($1>=5),1,`V`'roman(eval($1-5))', `ifelse(eval($1>=4),1,`IV`'roman(eval($1-4))', `ifelse(eval($1>=1),1,`I`'roman(eval($1-1))' )')')')')')')')')')')')')dnl dnl roman(3675)
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.
#Phix
Phix
function romanDec(string s) constant romans = "MDCLXVI", decmls = {1000,500,100,50,10,5,1} integer n, prev = 0, res = 0 for i=length(s) to 1 by -1 do n = decmls[find(s[i],romans)] if n<prev then n = 0-n end if res += n prev = n end for -- return res return {s,res} -- (for output) end function ?apply({"MCMXC","MMVIII","MDCLXVI"},romanDec)
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.
#SNOBOL4
SNOBOL4
* # Encode RLE define('rle(str)c,n') :(rle_end) rle str len(1) . c :f(return) str span(c) @n = rle = rle n c :(rle) rle_end   * # Decode RLE define('elr(str)c,n') :(elr_end) elr str span('0123456789') . n len(1) . c = :f(return) elr = elr dupl(c,n) :(elr) elr_end   * # Test and display str = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' output = str; str = rle(str); output = str str = elr(str); output = str 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
#6502_Assembly
6502 Assembly
CHROUT equ $FFD2  ;KERNAL call, prints the accumulator to the screen as an ascii value.   org $0801     db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00         lda #>TestStr sta $11   lda #<TestStr sta $10     ldx #5 ;number of times to repeat   loop: jsr PrintString dex bne loop     RTS ;RETURN TO BASIC     PrintString: ldy #0 loop_PrintString: lda ($10),y ;this doesn't actually increment the pointer itself, so we don't need to back it up. beq donePrinting jsr CHROUT iny jmp loop_PrintString donePrinting: rts       TestStr: db "HA",0
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Agena
Agena
# define a function returning three values mv := proc() is return 1, 2, "three" end ; # mv   scope # test the mv() proc local a, b, c := mv(); print( c, b, a ) epocs
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ALGOL_68
ALGOL 68
# example mode for returning multiple values from a procedure # MODE PAIR = STRUCT( STRING name, INT value );   # procedure returning multiple values via a structure # PROC get pair = ( INT a )PAIR: CASE a IN #1# ( "H", 0 ) , #2# ( "He", 1 ) , #3# ( "Li", 3 ) OUT ( "?", a ) ESAC ;   main: ( # use the result as a whole # print( ( get pair( 3 ), newline ) ); # access the components separately # print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) ) )
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.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function Prepare_RiPeMd_160 { Dim Base 0, K(5), K1(5) K(0)=0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E K1(0)=0x50A28BE6,0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000 Dim Base 0,r(80), r1(80), s(80), s1(80) r(0)=0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 r(16)=7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 r(32)= 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 r(48)=1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 r(64)=4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 k=r() : k*=4 ' k is a pointer to array. We have to multiply to make them offsets   r1(0)=5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 r1(16)=6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 r1(32)=15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 r1(48)=8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 r1(64)=12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11   k=r1() : k*=4   s(0)=11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 s(16)=7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 s(32)=11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 s(48)=11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 s(64)=9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6   s1(0)=8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 s1(16)=9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 s1(32)=9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 s1(48)=15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 s1(64)=8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11   Dim Base 0, T(5), TT(5) T(0)=lambda ->binary.xor(binary.xor(number,number),number) T(1)=lambda (B,C,D)->binary.or(binary.and(B,C), binary.and(binary.not(B), D)) T(2)=lambda ->binary.xor(binary.or(number, binary.not(number)), number) T(3)=lambda (B,C,D)->binary.or(binary.and(B,D), binary.and(C,binary.not(D))) T(4)=lambda ->binary.xor(number, binary.or(number, binary.not(number)))   \\ no need for variables we read form stack with number TT(0)=lambda ->binary.xor(number, binary.or(number, binary.not(number))) TT(1)=lambda (BB,CC,DD)->binary.or(binary.and(BB,DD), binary.and(CC,binary.not(DD))) TT(2)=lambda ->binary.xor(binary.or(number, binary.not(number)), number) TT(3)=lambda (BB,CC,DD)->binary.or(binary.and(BB,CC), binary.and(binary.not(BB),DD)) TT(4)=lambda ->binary.xor(binary.xor(number,number),number)   \\ return of this function is a lambda function \\ all arrays are closures to this lambda =lambda K(),K1(),TT(), T(),r(),r1(), s(), s1() (&message$, ansi as boolean=true, ansiid=1033)-> { set fast! def h0 = 0x67452301, h1 = 0xEFCDAB89, h2 = 0x98BADCFE def h3 = 0x10325476, h4 = 0xC3D2E1F0 def i, j, l, padding, l1, blocks, acc, f64 as boolean=true, oldid if ansi then oldid=locale : locale ansiid \\ we use a buffer of 64 bytes buffer clear message as byte*64 l=len(message$)*if(ansi->1,2 ) if binary.and(l,63)>55 then padding=64 padding+= 64 - (l Mod 64) l1=padding+l+1   f64=binary.and(l,63)<>0   blocks=l1 div 64 rem Print "blocks:";blocks \\ now prepare the buffer PrepareBuffer() def decimal A, B, C, D, E, AA, BB, CC, DD, EE, T, TT do A = h0 : B = h1 : C = h2 : D = h3 : E = h4 AA = h0 : BB = h1 : CC = h2 : DD = h3 : EE = h4 for J=0 to 79 { JJ=J DIV 16 PUSH binary.add(Binary.Rotate(binary.add(A,T(JJ)(B,C,D),eval(message ,r(j) as long),k(jj)), s(j)), e) A = E : E = D : D = Binary.Rotate(C, 10) : C = B : READ B PUSH binary.add(Binary.Rotate(binary.add(AA,TT(JJ)(BB,CC,DD),eval(message, r1(j) as long),k1(jj)),s1(j)),EE) AA = EE : EE = DD : DD = Binary.Rotate(CC, 10) : CC = BB : READ BB } push binary.add(h1, C, DD) h1 = binary.add(h2, D, EE) h2 = binary.add(h3, E, AA) h3 = binary.add(h4, A, BB) h4 = binary.add(h0, B, CC) Read h0 blocks-- rem print over $(0,8), blocks : Refresh if blocks=0 then exit PrepareBuffer() always rem print buffer ans as byte*20 \\ we put ulong (long is ulong in buffers) Return ans, 0:=h0 as long, 4:=h1 as long,8:=h2 as long, 12:=h3 as long, 16:=h4 as long =ans if ansi then locale oldid set fast Sub PrepareBuffer()   if l-acc>=64 then LoadPart(64) else.if blocks=1 then return message, 0:=string$(chr$(0),32) if l-acc=0 and f64 then Return message, 56:=l*8 as long, 60 :=binary.shift(l,-29) as long else Return message, l-acc:=0x80, 56:=l*8 as long, 60 :=binary.shift(l,-29) as long if l>acc then LoadPart(l-acc) end if else Return message, l-acc:=0x80 LoadPart(l-acc) end if End Sub sub LoadPart(many) \\ str$() convert to ansi, one byte per character \\ using 1033 as Ansi language if ansi then Return message, 0:=str$(mid$(message$,1+acc, many)) else Return message, 0:=mid$(message$, 1+acc, many) end if acc+=many end sub } } Module TestHash (RIPEMD){ Flush \\ push data to stack of values, as fifo (each entry append to end of stack) Data "b3be159860842cebaa7174c8fff0aa9e50a5199f","Rosetta Code" Data "9c1185a5c5e9fc54612808977ee8f548b2258d31","" Data "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe","a" Data "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc","abc" Data "5d0689ef49d2fae572b881b123a85ffa21595f36", "message digest" Data "f71c27109c692c1b56bbdceb5b9d2865b3708dbc","abcdefghijklmnopqrstuvwxyz" Data "b0e20b6e3116640286ed3a87a5713079b21f5189" Data "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" Data "9b752e45573d4b39f4dbd3323cab82bf63326bfb", String$("1234567890",8) rem Data "52783243c1697bdbe16d37f97f68f08325dc1528", String$("a",1000000)   While not empty Read check$, text$ Print "RIPEMD160 for ";quote$(Left$(if$(len(text$)>30->left$(text$,27)+"...", text$),30)) \\ pass text$ by reference Display(RIPEMD(&text$)) End While   sub Display(ans) local answer$ for i=0 to len(ans)-1 answer$+=hex$(eval(ans,i),1) next i Print lcase$(answer$) Print lcase$(answer$)=check$ end sub } TestHash Prepare_RiPeMd_160() } Checkit  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["Rosetta code","RIPEMD160","HexString"]
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
#D
D
import std.stdio, std.traits;   enum Node.FP differenceThreshold = 1e-40;   struct Node { alias FP = real; enum Kind : size_t { free, A, B }   FP voltage = 0.0;   /*const*/ private Kind kind = Kind.free; // Remove kindGet once kind is const. @property Kind kindGet() const pure nothrow @nogc {return kind; } }   Node.FP iter(size_t w, size_t h)(ref Node[w][h] m) pure nothrow @nogc { static void enforceBoundaryConditions(ref Node[w][h] m) pure nothrow @nogc { m[1][1].voltage = 1.0; m[6][7].voltage = -1.0; }   static Node.FP calcDifference(in ref Node[w][h] m, ref Node[w][h] d) pure nothrow @nogc { Node.FP total = 0.0;   foreach (immutable i; 0 .. h) { foreach (immutable j; 0 .. w) { Node.FP v = 0.0; { size_t n = 0; if (i != 0) { v += m[i - 1][j].voltage; n++; } if (j != 0) { v += m[i][j - 1].voltage; n++; } if (i < h - 1) { v += m[i + 1][j].voltage; n++; } if (j < w - 1) { v += m[i][j + 1].voltage; n++; } v = m[i][j].voltage - v / n; }   d[i][j].voltage = v; if (m[i][j].kindGet == Node.Kind.free) total += v ^^ 2; } }   return total; }   Node[w][h] difference;   while (true) { enforceBoundaryConditions(m); if (calcDifference(m, difference) < differenceThreshold) break; foreach (immutable i, const di; difference) foreach (immutable j, const ref dij; di) m[i][j].voltage -= dij.voltage; }   Node.FP[EnumMembers!(Node.Kind).length] cur = 0.0; foreach (immutable i, const di; difference) foreach (immutable j, const ref dij; di) cur[m[i][j].kindGet] += dij.voltage * (!!i + !!j + (i < h-1) + (j < w-1));   return (cur[Node.Kind.A] - cur[Node.Kind.B]) / 2.0; }   void main() { enum size_t w = 10, h = w; Node[w][h] mesh;   // Set A and B Nodes. mesh[1][1] = Node( 1.0, Node.Kind.A); mesh[6][7] = Node(-1.0, Node.Kind.B);   writefln("R = %.19f", 2 / mesh.iter); }
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
Respond to an unknown method call
Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined. This task is intended only for object systems that use a dynamic dispatch mechanism without static checking. Related task   Send an unknown method call.
#Lasso
Lasso
define exampletype => type { public foo() => { return 'this is foo\r' } public bar() => { return 'this is bar\r' } public _unknownTag(...) => { local(n = method_name->asString) return 'tried to handle unknown method called "'+#n+'"'+ (#rest->size ? ' with args: "'+#rest->join(',')+'"')+'\r' } }   local(e = exampletype)   #e->foo() // outputs 'this is foo'   #e->bar() // outputs 'this is bar'   #e->stuff() // outputs 'tried to handle unknown method called "stuff"'   #e->dothis('here',12,'there','nowhere') // outputs 'tried to handle unknown method called "dothis" with args: "here,12,there,nowhere"'
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.
#Logtalk
Logtalk
  :- object(foo).   :- public(try/0). try :- catch(bar::message, Error, handler(Error)).   handler(error(existence_error(predicate_declaration,message/0),_)) :- % handle the unknown message ...   :- end_object.  
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.
#Lua
Lua
  local object={print=print} setmetatable(object,{__index=function(t,k)return function() print("You called the method",k)end end}) object.print("Hi") -->Hi object.hello() -->You called the method hello  
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
#AWK
AWK
  # syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK BEGIN { text[++i] = "---------- Ice and Fire ------------" text[++i] = "" text[++i] = "fire, in end will world the say Some" text[++i] = "ice. in say Some" text[++i] = "desire of tasted I've what From" text[++i] = "fire. favor who those with hold I" text[++i] = "" text[++i] = "... elided paragraph last ..." text[++i] = "" text[++i] = "Frost Robert -----------------------" leng = i for (i=1; i<=leng; i++) { n = split(text[i],arr," ") for (j=n; j>0; j--) { printf("%s ",arr[j]) } printf("\n") } exit(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
#NewLISP
NewLISP
(define (rot13 str) (join (map (fn(c) (cond ((<= "A" (upper-case c) "M") (char (+ (char c) 13))) ((<= "N" (upper-case c) "Z") (char (- (char c) 13))) (true c))) (explode 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
#Maple
Maple
> for n in [ 1666, 1990, 2008 ] do printf( "%d\t%s\n", n, convert( n, 'roman' ) ) end: 1666 MDCLXVI 1990 MCMXC 2008 MMVIII
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.
#Phixmonti
Phixmonti
def romanDec /# s -- n #/ 0 >ps 0 >ps ( ( "M" 1000 ) ( "D" 500 ) ( "C" 100 ) ( "L" 50 ) ( "X" 10 ) ( "V" 5 ) ( "I" 1 ) )   swap upper reverse len while pop rot rot tochar getd if dup ps> < if 0 swap - endif dup ps> + >ps >ps swap else "Error: " print ? "" endif len endwhile drop drop ps> drop ps> enddef   /# usage example: "MMXX" romanDec ? (show 2020) #/
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.
#SQL
SQL
  -- variable table DROP TABLE IF EXISTS var; CREATE temp TABLE var ( VALUE VARCHAR(1000) ); INSERT INTO var(VALUE) SELECT 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';   -- select WITH recursive ints(num) AS ( SELECT 1 UNION ALL SELECT num+1 FROM ints WHERE num+1 <= LENGTH((SELECT VALUE FROM var)) ) , chars(num,chr,nextChr,isGroupEnd) AS ( SELECT tmp.*, CASE WHEN tmp.nextChr <> tmp.chr THEN 1 ELSE 0 END groupEnds FROM ( SELECT num, SUBSTRING((SELECT VALUE FROM var), num, 1) chr, (SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr FROM ints ) tmp ) SELECT (SELECT VALUE FROM var) plain_text, ( SELECT string_agg(concat(CAST(maxNoWithinGroup AS VARCHAR(10)) , chr), '' ORDER BY num) FROM ( SELECT *, MAX(noWithinGroup) OVER (partition BY chr, groupNo) maxNoWithinGroup FROM ( SELECT num, chr, groupNo, ROW_NUMBER() OVER( partition BY chr, groupNo ORDER BY num) noWithinGroup FROM ( SELECT *, (SELECT COUNT(*) FROM chars chars2 WHERE chars2.isGroupEnd = 1 AND chars2.chr = chars.chr AND chars2.num < chars.num) groupNo FROM chars ) tmp ) sub ) final WHERE noWithinGroup = 1 ) Rle_Compressed  
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
#68000_Assembly
68000 Assembly
MOVE.W #5-1,D1 RepString: LEA A3, MyString MOVE.L A3,-(SP) ;PUSH A3 JSR PrintString ;unimplemented hardware-dependent printing routine, assumed to not clobber D1 MOVE.L (SP)+,A3 ;POP A3 DBRA D1,RepString RTS ;return to basic or whatever   MyString: DC.B "ha",0 even
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ALGOL_W
ALGOL W
begin  % example using a record type to return multiple values from a procedure % record Element ( string(2) symbol; integer atomicNumber ); reference(Element) procedure getElement( integer value n ) ; begin Element( if n < 1 then "?<" else if n > 3 then "?>" else case n of ( %1% "H" , %2% "He" , %3% "Li" ) , n ) end getElement ;  % test the procedure % begin reference(Element) elementData; for n := 0 until 4 do begin elementData := getElement(n); write( s_w := 0, i_w := 1 , atomicNumber(elementData) , " " , symbol(elementData) ); end end   end.
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 DECLARE EXTERNAL SUB sumdiff 110 ! 120 CALL sumdiff(5, 3, sum, diff) 130 PRINT "Sum is "; sum 140 PRINT "Difference is "; diff 150 END 160 ! 170 EXTERNAL SUB sumdiff(a, b, c, d) 180 LET c = a + b 190 LET d = a - b 200 END SUB
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.
#Nim
Nim
import nimcrypto / [ripemd, hash]   echo ripemd160.digest("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.
#Objeck
Objeck
  class Hash { function : Main(args : String[]) ~ Nil { in := "Rosetta Code"->ToByteArray(); hash := Encryption.Hash->RIPEMD160(in); hash->ToHexString()->PrintLine(); } }  
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
#ERRE
ERRE
  PROGRAM RESISTENCE_MESH    !$BASE=1    !$DYNAMIC DIM A[0,0]   BEGIN   N=10 NN=N*N  !$DIM A[NN,NN+1]   PRINT(CHR$(12);) !CLS  ! generate matrix data NODE=0 FOR ROW=1 TO N DO FOR COL=1 TO N DO NODE=NODE+1 IF ROW>1 THEN A[NODE,NODE]=A[NODE,NODE]+1 A[NODE,NODE-N]=-1 END IF IF ROW<N THEN A[NODE,NODE]=A[NODE,NODE]+1 A[NODE,NODE+N]=-1 END IF IF COL>1 THEN A[NODE,NODE]=A[NODE,NODE]+1 A[NODE,NODE-1]=-1 END IF IF COL<N THEN A[NODE,NODE]=A[NODE,NODE]+1 A[NODE,NODE+1]=-1 END IF END FOR END FOR   AR=2 AC=2 A=AC+N*(AR-1) BR=7 BC=8 B=BC+N*(BR-1) A[A,NN+1]=-1 A[B,NN+1]=1   PRINT("Nodes ";A,B)    ! solve linear system  ! using Gauss-Seidel method  ! with pivoting R=NN   FOR J=1 TO R DO FOR I=J TO R DO EXIT IF A[I,J]<>0 END FOR IF I=R+1 THEN PRINT("No solution!")  !$STOP END IF FOR K=1 TO R+1 DO SWAP(A[J,K],A[I,K]) END FOR Y=1/A[J,J] FOR K=1 TO R+1 DO A[J,K]=Y*A[J,K] END FOR FOR I=1 TO R DO IF I<>J THEN Y=-A[I,J] FOR K=1 TO R+1 DO A[I,K]=A[I,K]+Y*A[J,K] END FOR END IF END FOR END FOR PRINT("Resistence=";ABS(A[A,NN+1]-A[B,NN+1])) END PROGRAM  
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.
#M2000_Interpreter
M2000 Interpreter
  module checkit {   Class Alfa { k=1000 module a (x, y) { Print x, y } module NoParam { Print "ok" } Function Sqr(x) { =Sqrt(x) } Function NoParam { =.k } Function Sqr$(x) { =Str$(Sqrt(x),1033) ' using locale 1033, no leading space for positive } } \\ modules, functions numeric and string, and variables can use same name \\ here we have module invoke, function invoke, and function invoke$ Module invoke (&a, method$) { param=(,) Read ? param Function Check(&a, method$) { group b type "module "+method$+" {}" =valid(@a as b) } if check(&a, method$) then { for a { \\ we call this.methodname call "."+method$, !param } } else Flush : Error "unknown method "+method$ ' flush empty the stack } Function invoke (&a, method$) { \\ functions have own stack of values Function Check(&a, method$) { group b type "Function "+filter$(method$, "()")+" {}" =valid(@a as b) } if check(&a, method$) then { for a { =Function("."+method$, ![]) } } else Error "unknown Function "+method$ } \\ invoke string functions Function invoke$ (&a, method$) { \\ functions have own stack of values Function Check(&a, method$) { group b type "Function "+filter$(method$, "()")+" {}" =valid(@a as b) } if check(&a, method$) then { for a { \\ [] is a function which return current stack as a stack object, and pass to current stack a new stack object. =Function$("."+method$, ![]) } } else Error "unknown Function "+method$ }   Module obj.alfa { Flush 'empty stack Print "this is a fake module, is not part of obj" } Function obj.alfa { Print "this is a fake function, is not part of obj" } Obj=Alfa() \\ normal invoke, interpreter not know that this is an object method \\ this method has a weak reference to obj, so anytime we use This. or just dot, this weak reference make the real name to execute Obj.a 10,20 \\ call the fake method (can't access object methods and properties), has empty weak reference to object obj.alfa 10, 20   \\ check before call using custom invoke \\ to check if a method (module) exist, we have to compare this object with other temporary object \\ we make one with the method name and empty definition, and then check if obj has anything this temp object has \\ arguments passed in a tuple (optional), so we didn't leave stack with unused items, if we have an unknown method. invoke &obj, "a", (10, 20) invoke &obj, "NoParam" \\ now with an unknown method, using alfa Try ok { invoke &obj, "Alfa", (10, 20) } If Error Then Print Error$ \\ we can use invoke for functions Print Invoke(&obj, "Sqr()", 4), Invoke(&obj, "NoParam()") Print Invoke$(&obj, "Sqr$()",2) \ without custom invoke Print obj.Sqr(4), obj.Noparam(), obj.Sqr$(2) \\ so now we try to call Alfa() and Alfa$() (unknown functions) Try ok { Print Invoke(&obj, "Alfa()") } If Error Then Print Error$ Try ok { Print Invoke$(&obj, "Alfa$()") } If Error Then Print Error$     \\ so now lets copy obj to obj2 \\ fake method didn't passed to new object obj2=obj Try ok { invoke &obj2, "alfa", (10, 20) } If Error Then Print Error$   p->obj2 \\ if p is a pointer to named group we can pass it as is invoke &p, "a", (10, 20) \\ normal called p=>a 10,20   For p { invoke &this, "a", (10, 20) Try ok { invoke &this, "alfa", (10, 20) } If Error Then Print Error$ }   p->(obj2) ' p point to a copy of obj2 (an unnamed group) For p { invoke &this, "a", (10, 20) \\ normal called p=>a 10, 20 Try ok { invoke &this, "alfa", (10, 20) } If Error Then Print Error$   }   } checkit  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
obj[foo] = "This is foo."; obj[bar] = "This is bar."; obj[f_Symbol] := "What is " <> SymbolName[f] <> "?"; Print[obj@foo]; Print[obj@bar]; Print[obj@baz];
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
#BaCon
BaCon
  PRINT REV$("---------- Ice and Fire ------------") PRINT PRINT REV$("fire, in end will world the say Some") PRINT REV$("ice. in say Some ") PRINT REV$("desire of tasted I've what From ") PRINT REV$("fire. favor who those with hold I ") PRINT PRINT REV$("... elided paragraph last ... ") PRINT PRINT REV$("Frost Robert -----------------------")  
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
#Nim
Nim
import strutils   proc rot13(c: char): char = case toLowerAscii(c) of 'a'..'m': chr(ord(c) + 13) of 'n'..'z': chr(ord(c) - 13) else: c   for line in stdin.lines: for c in line: stdout.write rot13(c) stdout.write "\n"
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RomanNumeral[4] RomanNumeral[99] RomanNumeral[1337] RomanNumeral[1666] RomanNumeral[6889]
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.
#PHP
PHP
<?php /** * @author Elad Yosifon */ $roman_to_decimal = array( 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000, );   /** * @param $number * @return int */ function roman2decimal($number) { global $roman_to_decimal;   // breaks the string into an array of chars $digits = str_split($number); $lastIndex = count($digits)-1; $sum = 0;   foreach($digits as $index => $digit) { if(!isset($digits[$index])) { continue; }   if(isset($roman_to_decimal[$digit])) { if($index < $lastIndex) { $left = $roman_to_decimal[$digits[$index]]; $right = $roman_to_decimal[$digits[$index+1]]; if($left < $right) { $sum += ($right - $left); unset($digits[$index+1],$left, $right); continue; } unset($left, $right); } } $sum += $roman_to_decimal[$digit]; }   return $sum; }   /*============= OUTPUT =============*/ header('Content-Type: text/plain');   $tests = array( "I" => array(roman2decimal('I'), 1), "II" => array(roman2decimal('II'), 2), "III" => array(roman2decimal('III'), 3), "IV" => array(roman2decimal('IV'), 4), "V" => array(roman2decimal('V'), 5), "VI" => array(roman2decimal('VI'), 6), "VII" => array(roman2decimal('VII'), 7), "IX" => array(roman2decimal('IX'), 9), "X" => array(roman2decimal('X'), 10), "XI" => array(roman2decimal('XI'), 11), "XIV" => array(roman2decimal('XIV'), 14), "XV" => array(roman2decimal('XV'), 15), "XVI" => array(roman2decimal('XVI'), 16), "XVIV" => array(roman2decimal('XVIV'), 19), "XIX" => array(roman2decimal('XIX'), 19), "MDCLXVI" => array(roman2decimal('MDCLXVI'), 1666), "MCMXC" => array(roman2decimal('MCMXC'), 1990), "MMVIII" => array(roman2decimal('MMVIII'), 2008), "MMMCLIX" => array(roman2decimal('MMMCLIX'), 3159), "MCMLXXVII" => array(roman2decimal('MCMLXXVII'), 1977), );     foreach($tests as $key => $value) { echo "($key == {$value[0]}) => " . ($value[0] === $value[1] ? "true" : "false, should be {$value[1]}.") . "\n"; }
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.
#Standard_ML
Standard ML
fun encode str = let fun aux (sub, acc) = case Substring.getc sub of NONE => rev acc | SOME (x, sub') => let val (y, z) = Substring.splitl (fn c => c = x) sub' in aux (z, (x, Substring.size y + 1) :: acc) end in aux (Substring.full str, []) end   fun decode lst = concat (map (fn (c,n) => implode (List.tabulate (n, fn _ => c))) lst)
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
#8th
8th
"ha" 5 s:* . cr
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ARM_Assembly
ARM Assembly
foo: MOV R2,R0 MOV R3,R1 ADD R0,R2,R3 SUB R1,R2,R3 BX LR
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Arturo
Arturo
addsub: function [x y]-> @[x+y x-y]   a: 33 b: 12   result: addsub a b   print [a "+" b "=" result\0] print [a "-" b "=" result\1]
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.
#PARI.2FGP
PARI/GP
#include <pari/pari.h> #include <openssl/ripemd.h>   #define HEX(x) (((x) < 10)? (x)+'0': (x)-10+'a')   GEN plug_ripemd160(char *text) { char md[RIPEMD160_DIGEST_LENGTH]; char hash[sizeof(md) * 2 + 1]; int i;   RIPEMD160((unsigned char*)text, strlen(text), (unsigned char*)md);   for (i = 0; i < sizeof(md); i++) { hash[i+i] = HEX((md[i] >> 4) & 0x0f); hash[i+i+1] = HEX(md[i] & 0x0f); }   hash[sizeof(md) * 2] = 0;   return strtoGENstr(hash); }
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
#Euler_Math_Toolbox
Euler Math Toolbox
  >load incidence; >{u,r}=solvePotentialX(makeRectangleX(10,10),12,68); r, 1.60899124173  
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.
#Nim
Nim
{.experimental:"dotOperators".} from strutils import join   type Foo = object   proc qux(f:Foo) = echo "called qux"   #for nicer output func quoteStrings[T](x:T):string = (when T is string: "\"" & x & "\"" else: $x)   #dot operator catches all unmatched calls on Foo template `.()`(f:Foo,field:untyped,args:varargs[string,quoteStrings]):untyped = echo "tried to call method '" & astToStr(`field`) & (if `args`.len > 0: "' with args: " & args.join(", ") else: "'")   let f = Foo() f.bar() #f.bar #error: undeclared field f.baz("hi",5) f.qux() f.qux("nope")
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.
#Object_Pascal
Object Pascal
  type Tanimal = class public procedure bark(); virtual; abstract; end;   implementation   var animal: Tanimal;   initialization   animal := Tanimal.Create; animal.bark(); // abstract method call exception at runtime here animal.Free;   end.  
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
#Batch_File
Batch File
@echo off ::The Main Thing... cls echo. call :reverse "---------- Ice and Fire ------------" call :reverse call :reverse "fire, in end will world the say Some" call :reverse "ice. in say Some" call :reverse "desire of tasted I've what From" call :reverse "fire. favor who those with hold I" call :reverse call :reverse "... elided paragraph last ..." call :reverse call :reverse "Frost Robert -----------------------" echo. pause>nul exit ::/The Main Thing... ::The Function... :reverse set reversed=&set word=&set str=%1 :process for /f "tokens=1,*" %%A in (%str%) do ( set str=%%B set word=%%A ) set reversed=%word% %reversed% set str="%str%" if not %str%=="" goto process   echo.%reversed% goto :EOF ::/The Function...
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
#Objeck
Objeck
  bundle Default { class Rot13 { function : Main(args : String[]) ~ Nil { Rot13("nowhere ABJURER")->PrintLine(); }   function : native : Rot13(text : String) ~ String { rot := ""; each(i : text) { c := text->Get(i); if(c >= 'a' & c <= 'm' | c >= 'A' & c <= 'M') { rot->Append(c + 13); } else if(c >= 'n' & c <= 'z' | c >= 'N' & c <= 'Z') { rot->Append(c - 13); } else { rot->Append(c); }; };   return rot; } } }  
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
#Mercury
Mercury
  :- module roman.   :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module char, int, list, string.   main(!IO) :- command_line_arguments(Args, !IO), filter(is_all_digits, Args, CleanArgs), foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :- ( Roman = to_roman(Arg) -> format("%s => %s", [s(Arg), s(Roman)], !IO), nl(!IO)  ; format("%s cannot be converted.", [s(Arg)], !IO), nl(!IO) ) ), CleanArgs, !IO).   :- func to_roman(string::in) = (string::out) is semidet. to_roman(Number) = from_char_list(build_roman(reverse(to_char_list(Number)))).   :- func build_roman(list(char)) = list(char). :- mode build_roman(in) = out is semidet. build_roman([]) = []. build_roman([D|R]) = Roman :- map(promote, build_roman(R), Interim), Roman = Interim ++ digit_to_roman(D).   :- func digit_to_roman(char) = list(char). :- mode digit_to_roman(in) = out is semidet. digit_to_roman('0') = []. digit_to_roman('1') = ['I']. digit_to_roman('2') = ['I','I']. digit_to_roman('3') = ['I','I','I']. digit_to_roman('4') = ['I','V']. digit_to_roman('5') = ['V']. digit_to_roman('6') = ['V','I']. digit_to_roman('7') = ['V','I','I']. digit_to_roman('8') = ['V','I','I','I']. digit_to_roman('9') = ['I','X'].   :- pred promote(char::in, char::out) is semidet. promote('I', 'X'). promote('V', 'L'). promote('X', 'C'). promote('L', 'D'). promote('C', 'M').   :- end_module roman.  
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.
#Picat
Picat
go => List = ["IV", "XLII", "M", "MCXI", "CMXI", "MCM", "MCMXC", "MMVIII", "MMIX", "MCDXLIV", "MDCLXVI", "MMXII"], foreach(R in List) printf("%-8s: %w\n", R, roman_decode(R)) end, nl.     roman_decode(Str) = Res => if Str == "" then Res := "" else D = new_map(findall((R=D), roman(R,D))), Res = 0, Old = 0, foreach(S in Str) N = D.get(S),  % Fix for the Roman convention that XC = 90, not 110. if Old > 0, N > Old then Res := Res - 2*Old end, Res := Res + N, Old := N end end.   roman('I', 1). roman('V', 5). roman('X', 10). roman('L', 50). roman('C', 100). roman('D', 500). roman('M', 1000).
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.
#Swift
Swift
import Foundation   // "WWWBWW" -> [(3, W), (1, B), (2, W)] func encode(input: String) -> [(Int, Character)] { return input.characters.reduce([(Int, Character)]()) { if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r } return $0 + [(1, $1)] } }   // [(3, W), (1, B), (2, W)] -> "WWWBWW" func decode(encoded: [(Int, Character)]) -> String { return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) } }  
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
#ABAP
ABAP
  report z_repeat_string.   write repeat( val = `ha` occ = 5 ).  
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
#Action.21
Action!
Proc Main() byte REPEAT   REPEAT=5 Do Print("ha") REPEAT==-1 Until REPEAT=0 Do   Return
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ATS
ATS
// #include "share/atspre_staload.hats" // (* ****** ****** *)   fun addsub ( x: int, y: int ) : (int, int) = (x+y, x-y)   (* ****** ****** *)   implement main0 () = let val (sum, diff) = addsub (33, 12) in println! ("33 + 12 = ", sum); println! ("33 - 12 = ", diff); end (* end of [main0] *)
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#AutoHotkey
AutoHotkey
addsub(x, y) { return [x + y, x - y] }
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.
#Perl
Perl
use Crypt::RIPEMD160; say unpack "H*", Crypt::RIPEMD160->hash("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.
#Phix
Phix
include builtins\ripemd160.e constant test = "Rosetta Code" printf(1,"\n%s => %s\n",{test,ripemd160(test)})
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
#FreeBASIC
FreeBASIC
' version 01-07-2018 ' compile with: fbc -s console   #Define n 10   Dim As UInteger nn = n * n Dim As Double g(-nn To nn +1, -nn To nn +1) Dim As UInteger node, row, col   For row = 1 To n For col = 1 To n node += 1 If row > 1 Then g(node, node) += 1 g(node, node - n) = -1 End If If row < n Then g(node, node) += 1 g(node, node + n) = -1 End If If col > 1 Then g(node, node) += 1 g(node, node -1) = -1 End If If col < n Then g(node, node) += 1 g(node, node +1) = -1 End If Next Next   Dim As UInteger ar = 2, ac = 2 Dim As UInteger br = 7, bc = 8 Dim As UInteger a = ac + n * (ar -1) Dim As UInteger b = bc + n * (br -1)   g(a, nn +1) = -1 g(b, nn +1) = 1   Print : Print "Nodes a: "; a, " b: "; b   ' solve linear system using Gauss-Seidel method with pivoting Dim As UInteger i, j, k Dim As Double y   Do For j = 1 To nn For i = j To nn If g(i, j) <> 0 Then Exit For Next If i = nn +1 Then Print : Print "No solution" Exit Do End If For k = 1 To nn +1 Swap g(j, k), g(i, k) Next y = g(j, j) For k = 1 To nn +1 g(j, k) = g(j, k) / y Next For i = 1 To nn If i <> j Then y = -g(i, j) For k = 1 To nn +1 g(i, k) = g(i, k) + y * g(j, k) Next End If Next Next   Print Print "Resistance ="; Abs(g(a, nn +1) - g(b, nn +1)); " Ohm" Exit Do Loop   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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.
#Objective-C
Objective-C
#include <Foundation/Foundation.h>   // The methods need to be declared somewhere @interface Dummy : NSObject - (void)grill; - (void)ding:(NSString *)s; @end   @interface Example : NSObject - (void)foo; - (void)bar; @end   @implementation Example - (void)foo { NSLog(@"this is foo"); }   - (void)bar { NSLog(@"this is bar"); }   - (void)forwardInvocation:(NSInvocation *)inv { NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); NSUInteger n = [[inv methodSignature] numberOfArguments]; for (NSUInteger i = 0; i < n-2; i++) { // First two arguments are the object and selector. id __unsafe_unretained arg; // We assume that all arguments are objects. // getArguments: is type-agnostic and does not perform memory management, // therefore we must pass it a pointer to an unretained type [inv getArgument:&arg atIndex:i+2]; NSLog(@"argument #%lu: %@", i, arg); } }   // forwardInvocation: does not work without methodSignatureForSelector: // The runtime uses the signature returned here to construct the invocation. - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; // we assume that all arguments are objects // The type encoding is "v@:@@@...", where "v" is the return type, void // "@" is the receiver, object type; ":" is the selector of the current method; // and each "@" after corresponds to an object argument return [NSMethodSignature signatureWithObjCTypes: [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; } @end   int main() { @autoreleasepool {   id example = [[Example alloc] init];   [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 "argument #0: dong"   } return 0; }
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
#BASIC256
BASIC256
source = freefile open (source, "m:\text.txt") textEnt$ = "" dim textSal$(size(source)*8) linea = 0   while not eof(source) textEnt$ = readline(source) linea += 1 textSal$[linea] = textEnt$ end while   for n = size(source) to 1 step -1 print textSal$[n]; next n close source
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
#OCaml
OCaml
let rot13 c = match c with | 'A'..'M' | 'a'..'m' -> char_of_int (int_of_char c + 13) | 'N'..'Z' | 'n'..'z' -> char_of_int (int_of_char c - 13) | _ -> c
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Microsoft_Small_Basic
Microsoft Small Basic
  arabicNumeral = 1990 ConvertToRoman() TextWindow.WriteLine(romanNumeral) 'MCMXC arabicNumeral = 2018 ConvertToRoman() TextWindow.WriteLine(romanNumeral) 'MMXVIII arabicNumeral = 3888 ConvertToRoman() TextWindow.WriteLine(romanNumeral) 'MMMDCCCLXXXVIII   Sub ConvertToRoman weights[0] = 1000 weights[1] = 900 weights[2] = 500 weights[3] = 400 weights[4] = 100 weights[5] = 90 weights[6] = 50 weights[7] = 40 weights[8] = 10 weights[9] = 9 weights[10] = 5 weights[11] = 4 weights[12] = 1 symbols[0] = "M" symbols[1] = "CM" symbols[2] = "D" symbols[3] = "CD" symbols[4] = "C" symbols[5] = "XC" symbols[6] = "L" symbols[7] = "XL" symbols[8] = "X" symbols[9] = "IX" symbols[10] = "V" symbols[11] = "IV" symbols[12] = "I" romanNumeral = "" i = 0 While (i <= 12) And (arabicNumeral > 0) While arabicNumeral >= weights[i] romanNumeral = Text.Append(romanNumeral, symbols[i]) arabicNumeral = arabicNumeral - weights[i] EndWhile i = i + 1 EndWhile EndSub  
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.
#PicoLisp
PicoLisp
(de roman2decimal (Rom) (let L (replace (chop Rom) 'M 1000 'D 500 'C 100 'L 50 'X 10 'V 5 'I 1) (sum '((A B) (if (>= A B) A (- A))) L (cdr L)) ) )
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.
#Tcl
Tcl
proc encode {string} { set encoding {} # use a regular expression to match runs of one character foreach {run -} [regexp -all -inline {(.)\1+|.} $string] { lappend encoding [string length $run] [string index $run 0] } return $encoding }   proc decode {encoding} { foreach {count char} $encoding { append decoded [string repeat $char $count] } return $decoded }