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/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Nim
Nim
import random, strutils, tables   type Choice {.pure.} = enum Rock, Paper, Scissors History = tuple[total: int; counts: CountTable[Choice]]   const Successor: array[Choice, Choice] = [Paper, Scissors, Rock]   func `>`(a, b: Choice): bool = ## By construction, only the successor is greater than the choice. a == Successor[b]   proc choose(history: History): Choice = ## Make a weighted random choice using the player counts ## then select the choice likely to beat it. var value = rand(1..history.total) for choice, count in history.counts.pairs: if value <= count: return Successor[choice] dec value, count     randomize()   # Initialize history with one for each choice in order to avoid special case. var history: History = (3, [Rock, Paper, Scissors].toCountTable)   echo "To quit game, type 'q' when asked for your choice."   var myChoice, yourChoice: Choice var myWins, yourWins = 0   while true:   # Get player choice. try: stdout.write "Rock(1), paper(2), scissors(3). Your choice? " let answer = stdin.readLine().strip() if answer == "q": quit "Quitting game.", QuitSuccess if answer notin ["1", "2", "3"]: echo "Invalid choice." continue yourChoice = Choice(ord(answer[0]) - ord('1')) except EOFError: quit "Quitting game.", QuitFailure   # Make my choice. myChoice = history.choose() echo "I choosed ", myChoice, '.' history.counts.inc yourChoice inc history.total   # Display result of round. if myChoice == yourChoice: echo "It’s a tie." elif myChoice > yourChoice: echo "I win." inc myWins else: echo "You win." inc yourWins echo "Total wins. You: ", yourWins, " Me: ", myWins
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RunLengthEncode[input_String]:= (l |-> {First@l, Length@l}) /@ (Split@Characters@input)
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
#GW-BASIC
GW-BASIC
10 INPUT "Enter a string: ",A$ 20 GOSUB 50 30 PRINT B$ 40 END 50 FOR I=1 TO LEN(A$) 60 N=ASC(MID$(A$,I,1)) 70 E=255 80 IF N>64 AND N<91 THEN E=90 ' uppercase 90 IF N>96 AND N<123 THEN E=122 ' lowercase 100 IF E<255 THEN N=N+13 110 IF N>E THEN N=N-26 120 B$=B$+CHR$(N) 130 NEXT 140 RETURN
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Raku
Raku
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;   for <Washington Bush> -> $needle { say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }"; }
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
#Elena
Elena
import system'collections; import system'routines; import extensions; import extensions'text;   static RomanDictionary = Dictionary.new() .setAt(1000, "M") .setAt(900, "CM") .setAt(500, "D") .setAt(400, "CD") .setAt(100, "C") .setAt(90, "XC") .setAt(50, "L") .setAt(40, "XL") .setAt(10, "X") .setAt(9, "IX") .setAt(5, "V") .setAt(4, "IV") .setAt(1, "I");   extension op { toRoman() = RomanDictionary.accumulate(new StringWriter("I", self), (m,kv => m.replace(new StringWriter("I",kv.Key), kv.Value))); }   public program() { console.printLine("1990 : ", 1990.toRoman()); console.printLine("2008 : ", 2008.toRoman()); console.printLine("1666 : ", 1666.toRoman()) }
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#F.23
F#
let decimal_of_roman roman = let rec convert arabic lastval = function | head::tail -> let n = match head with | 'M' | 'm' -> 1000 | 'D' | 'd' -> 500 | 'C' | 'c' -> 100 | 'L' | 'l' -> 50 | 'X' | 'x' -> 10 | 'V' | 'v' -> 5 | 'I' | 'i' -> 1 | _ -> 0 let op = if n > lastval then (-) else (+) convert (op arabic lastval) n tail | _ -> arabic + lastval convert 0 0 (Seq.toList roman) ;;
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#PicoLisp
PicoLisp
(de findRoots (F Start Stop Step Eps) (filter '((N) (> Eps (abs (F N)))) (range Start Stop Step) ) )   (scl 12)   (mapcar round (findRoots '((X) (+ (*/ X X X `(* 1.0 1.0)) (*/ -3 X X 1.0) (* 2 X))) -1.0 3.0 0.0001 0.00000001 ) )
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#NS-HUBASIC
NS-HUBASIC
10 COMPUTER=RND(3)+1 20 COMPUTER$="ROCK" 30 IF COMPUTER=2 THEN COMPUTER$="PAPER" 40 IF COMPUTER=3 THEN COMPUTER$="SCISSORS" 50 INPUT "ROCK, PAPER OR SCISSORS? ",HUMAN$ 60 IF HUMAN$="ROCK" THEN GOTO 100 70 IF HUMAN$="PAPER" THEN GOTO 100 80 IF HUMAN$="SCISSORS" THEN GOTO 100 90 PRINT "INVALID GUESS. TRY AGAIN.": GOTO 50 100 PRINT "YOU CHOSE "HUMAN$" AND THE COMPUTER CHOSE "COMPUTER$"." 110 IF HUMAN$=COMPUTER$ THEN PRINT "THOSE ARE THE SAME CHOICES";", SO YOU TIED." 120 IF HUMAN$="ROCK" AND COMPUTER=2 THEN PRINT "PAPER COVERS ROCK, SO YOU LOSE." 130 IF HUMAN$="ROCK" AND COMPUTER=3 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU WIN." 140 IF HUMAN$="PAPER" AND COMPUTER=1 THEN PRINT "PAPER COVERS ROCK, SO YOU WIN." 150 IF HUMAN$="PAPER" AND COMPUTER=3 THEN PRINT "SCISSORS CUT PAPER";", SO YOU LOSE." 160 IF HUMAN$="SCISSORS" AND COMPUTER=1 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU LOSE." 170 IF HUMAN$="SCISSORS" AND COMPUTER=2 THEN PRINT "SCISSORS CUT PAPER, SO YOU WIN."10 COMPUTER=RND(3)+1
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. 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.
#Maxima
Maxima
rle(a) := block( [n: slength(a), b: "", c: charat(a, 1), k: 1], for i from 2 thru n do if cequal(c, charat(a, i)) then k: k + 1 else (b: sconcat(b, k, c), c: charat(a, i), k: 1), sconcat(b, k, c) )$   rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); "12W1B12W3B24W1B14W"
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
#Haskell
Haskell
import Data.Char (chr, isAlpha, ord, toLower) import Data.Bool (bool)   rot13 :: Char -> Char rot13 c | isAlpha c = chr $ bool (-) (+) ('m' >= toLower c) (ord c) 13 | otherwise = c   -- Simple test main :: IO () main = print $ rot13 <$> "Abjurer nowhere"
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#REBOL
REBOL
rebol [ Title: "List Indexing" URL: http://rosettacode.org/wiki/Index_in_a_list ]   locate: func [ "Find the index of a string (needle) in string collection (haystack)." haystack [series!] "List of values to search." needle [string!] "String to find in value list." /largest "Return the largest index if more than one needle." /local i ][ i: either largest [ find/reverse tail haystack needle][find haystack needle] either i [return index? i][ throw reform [needle "is not in haystack."] ] ]   ; Note that REBOL uses 1-base lists instead of 0-based like most ; computer languages. Therefore, the index provided will be one ; higher than other results on this page.   haystack: parse "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo" none   print "Search for first occurance:" foreach needle ["Washington" "Bush"] [ print catch [ reform [needle "=>" locate haystack needle] ] ]   print [crlf "Search for last occurance:"] foreach needle ["Washington" "Bush"] [ print catch [ reform [needle "=>" locate/largest haystack needle] ] ]
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
#Elixir
Elixir
defmodule Roman_numeral do def encode(0), do: '' def encode(x) when x >= 1000, do: [?M | encode(x - 1000)] def encode(x) when x >= 100, do: digit(div(x,100), ?C, ?D, ?M) ++ encode(rem(x,100)) def encode(x) when x >= 10, do: digit(div(x,10), ?X, ?L, ?C) ++ encode(rem(x,10)) def encode(x) when x >= 1, do: digit(x, ?I, ?V, ?X)   defp digit(1, x, _, _), do: [x] defp digit(2, x, _, _), do: [x, x] defp digit(3, x, _, _), do: [x, x, x] defp digit(4, x, y, _), do: [x, y] defp digit(5, _, y, _), do: [y] defp digit(6, x, y, _), do: [y, x] defp digit(7, x, y, _), do: [y, x, x] defp digit(8, x, y, _), do: [y, x, x, x] defp digit(9, x, _, z), do: [x, z] end
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.
#Factor
Factor
USE: roman ( scratchpad ) "MMMCCCXXXIII" roman> . 3333
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#PL.2FI
PL/I
  f: procedure (x) returns (float (18)); declare x float (18); return (x**3 - 3*x**2 + 2*x ); end f;   declare eps float, (x, y) float (18); declare dx fixed decimal (15,13);   eps = 1e-12;   do dx = -5.03 to 5 by 0.1; x = dx; if sign(f(x)) ^= sign(f(dx+0.1)) then call locate_root; end;   locate_root: procedure; declare (left, mid, right) float (18);   put skip list ('Looking for root in [' || x, x+0.1 || ']' ); left = x; right = dx+0.1; PUT SKIP LIST (F(LEFT), F(RIGHT) ); if abs(f(left) ) < eps then do; put skip list ('Found a root at x=', left); return; end; else if abs(f(right) ) < eps then do; put skip list ('Found a root at x=', right); return; end; do forever; mid = (left+right)/2; if sign(f(mid)) = 0 then do; put skip list ('Root found at x=', mid); return; end; else if sign(f(left)) ^= sign(f(mid)) then right = mid; else left = mid; /* put skip list (left || right); */ if abs(right-left) < eps then do; put skip list ('There is a root near ' || (left+right)/2); return; end; end; end locate_root;  
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#OCaml
OCaml
  let pf = Printf.printf ;;   let looses a b = match a, b with `R, `P -> true | `P, `S -> true | `S, `R -> true | _, _ -> false ;;   let rec get_move () = pf "[R]ock, [P]aper, [S]cisors [Q]uit? " ; match String.uppercase (read_line ()) with "P" -> `P | "S" -> `S | "R" -> `R | "Q" -> exit 0 | _ -> get_move () ;;   let str_of_move = function `P -> "paper" | `R -> "rock" | `S -> "scisors" ;;   let comp_move r p s = let tot = r +. p +. s in let n = Random.float 1.0 in if n < r /. tot then `R else if n < (r +. p) /. tot then `P else `S ;;   let rec make_moves r p s = let cm = comp_move r p s in (* Computer move is based on game history. *) let hm = get_move () in (* Human move is requested. *) pf "Me: %s. You: %s. " (str_of_move cm) (str_of_move hm); let outcome = if looses hm cm then "I win. You loose.\n" else if cm = hm then "We draw.\n" else "You win. I loose.\n" in pf "%s" outcome; match hm with (* Play on with adapted strategy. *) `S -> make_moves (r +. 1.) p s | `R -> make_moves r (p +. 1.) s | `P -> make_moves r p (s +. 1.) ;;   (* Main loop. *) make_moves 1. 1. 1. ;;    
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. 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.
#MMIX
MMIX
LOC Data_Segment GREG @ Buf OCTA 0,0,0,0 integer print buffer Char BYTE 0,0 single char print buffer task BYTE "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW" BYTE "WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",0 len GREG @-1-task // task should become this tEnc BYTE "12W1B12W3B24W1B14W",0   GREG @ // tuple array for encoding purposes // each tuple is a tetra (4 bytes long or 2 wydes long) // (c,l) in which c is a char and l = number of chars c // high wyde of the tetra contains the char // low wyde .. .. .. contains the length RLE TETRA 0   LOC #100 locate program GREG @ // print number to stdout // destroys input arg $3 ! Prt64 LDA $255,Buf+23 points to LSD // do 2H DIV $3,$3,10 (N,R) = divmod (N,10) GET $13,rR get remainder INCL $13,'0' convert to ascii STBU $13,$255 store ascii digit BZ $3,3F SUB $255,$255,1 move pointer down JMP 2B While N !=0 3H TRAP 0,Fputs,StdOut print number to standard out GO $127,$127,0 return   GREG @ // print char to stdout PChar LDA $255,Char STBU $4,$255 TRAP 0,Fputs,StdOut GO $127,$127,0   GREG @ // encode routine // $0 string pointer // $1 index var // $2 pointer to tuple array // $11 temp var tuple Encode SET $1,0 initialize index = 0 SET $11,0 postion in string = 0 LDBU $3,$0,$1 get first char ADDU $6,$3,0 remember it do 1H INCL $1,1 repeat incr index LDBU $3,$0,$1 get a char BZ $3,2F if EOS then finish CMP $7,$3,$6 PBZ $7,1B while new == old XOR $4,$4,$4 new tuple ADDU $4,$6,0 SLU $4,$4,16 old char to tuple -> (c,_) SUB $7,$1,$11 length = index - previous position ADDU $11,$1,0 incr position OR $4,$4,$7 length l to tuple -> (c,l) STT $4,$2 put tuple in array ADDU $6,$3,0 remember new char INCL $2,4 incr 'tetra' pointer JMP 1B loop 2H XOR $4,$4,$4 put last tuple in array ADDU $4,$6,0 SLU $4,$4,16 SUB $7,$1,$11 ADDU $11,$1,0 OR $4,$4,$7 STT $4,$2 GO $127,$127,0 return   GREG @ Main LDA $0,task pointer uncompressed string LDA $2,RLE pointer tuple array GO $127,Encode encode string LDA $2,RLE points to start tuples SET $5,#ffff mask for extracting length 1H LDTU $3,$2 while not End of Array BZ $3,2F SRU $4,$3,16 char = (c,_) AND $3,$3,$5 length = (_,l) GO $127,Prt64 print length GO $127,PChar print char INCL $2,4 incr tuple pointer JMP 1B wend 2H SET $4,#a print NL GO $127,PChar // decode using the RLE tuples LDA $2,RLE pointer tuple array SET $5,#ffff mask 1H LDTU $3,$2 while not End of Array BZ $3,2F SRU $4,$3,16 char = (c,_) AND $3,$3,$5 length = (_,l) // for (i=0;i<length;i++) { 3H GO $127,PChar print a char SUB $3,$3,1 PBNZ $3,3B INCL $2,4 JMP 1B } 2H SET $4,#a print NL GO $127,PChar TRAP 0,Halt,0 EXIT
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
#HicEst
HicEst
CHARACTER c, txt='abc? XYZ!', cod*100   DO i = 1, LEN_TRIM(txt) c = txt(i) n = ICHAR(txt(i)) IF( (c >= 'a') * (c <= 'm') + (c >= 'A') * (c <= 'M') ) THEN c = CHAR( ICHAR(c) + 13 ) ELSEIF( (c >= 'n') * (c <= 'z') + (c >= 'N') * (c <= 'Z') ) THEN c = CHAR( ICHAR(c) - 13 ) ENDIF   cod(i) = c ENDDO   WRITE(ClipBoard, Name) txt, cod ! txt=abc? XYZ!; cod=nop? KLM!; END
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#REXX
REXX
/*REXX program searches a collection of strings (an array of periodic table elements).*/ hay.= /*initialize the haystack collection. */ hay.1 = 'sodium' hay.2 = 'phosphorous' hay.3 = 'californium' hay.4 = 'copernicium' hay.5 = 'gold' hay.6 = 'thallium' hay.7 = 'carbon' hay.8 = 'silver' hay.9 = 'curium' hay.10 = 'copper' hay.11 = 'helium' hay.12 = 'sulfur'   needle = 'gold' /*we'll be looking for the gold. */ upper needle /*in case some people capitalize stuff.*/ found=0 /*assume the needle isn't found yet. */   do j=1 while hay.j\=='' /*keep looking in the haystack. */ _=hay.j; upper _ /*make it uppercase to be safe. */ if _=needle then do; found=1 /*we've found the needle in haystack. */ leave /* ··· and stop looking, of course. */ end end /*j*/   if found then return j /*return the haystack index number. */ else say needle "wasn't found in the haystack!" return 0 /*indicates the needle wasn't found. */
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
#Emacs_Lisp
Emacs Lisp
(defun ar2ro (AN) "Translate from arabic number AN to roman number. For example, (ar2ro 1666) returns (M D C L X V I)." (cond ((>= AN 1000) (cons 'M (ar2ro (- AN 1000)))) ((>= AN 900) (cons 'C (cons 'M (ar2ro (- AN 900))))) ((>= AN 500) (cons 'D (ar2ro (- AN 500)))) ((>= AN 400) (cons 'C (cons 'D (ar2ro (- AN 400))))) ((>= AN 100) (cons 'C (ar2ro (- AN 100)))) ((>= AN 90) (cons 'X (cons 'C (ar2ro (- AN 90))))) ((>= AN 50) (cons 'L (ar2ro (- AN 50)))) ((>= AN 40) (cons 'X (cons 'L (ar2ro (- AN 40))))) ((>= AN 10) (cons 'X (ar2ro (- AN 10)))) ((>= AN 5) (cons 'V (ar2ro (- AN 5)))) ((>= AN 4) (cons 'I (cons 'V (ar2ro (- AN 4))))) ((>= AN 1) (cons 'I (ar2ro (- AN 1)))) ((= AN 0) nil)))
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.
#FALSE
FALSE
[ 32| {get value of Roman digit on stack} $'m= $[\% 1000\]? ~[ $'d= $[\% 500\]? ~[ $'c= $[\% 100\]? ~[ $'l= $[\% 50\]? ~[ $'x= $[\% 10\]? ~[ $'v= $[\% 5\]? ~[ $'i= $[\% 1\]? ~[  % 0 ]?]?]?]?]?]?]? ]r:   0 {accumulator} ^r;! {read first Roman digit} [^r;!$][ {read another, and as long as it is valid...} \$@@\$@@ {copy previous and current} \>[\_\]? {if previous smaller than current, negate previous} @@+\ {add previous to accumulator} ]# %+. {add final digit to accumulator and output} 10, {and a newline}
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#PureBasic
PureBasic
Procedure.d f(x.d) ProcedureReturn x*x*x-3*x*x+2*x EndProcedure   Procedure main() OpenConsole() Define.d StepSize= 0.001 Define.d Start=-1, stop=3 Define.d value=f(start), x=start Define.i oldsign=Sign(value)   If value=0 PrintN("Root found at "+StrF(start)) EndIf   While x<=stop value=f(x) If Sign(value) <> oldsign PrintN("Root found near "+StrF(x)) ElseIf value = 0 PrintN("Root found at "+StrF(x)) EndIf oldsign=Sign(value) x+StepSize Wend EndProcedure   main()
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#PARI.2FGP
PARI/GP
contest(rounds)={ my(v=[1,1,1],wins,losses); \\ Laplace rule for(i=1,rounds, my(computer,player,t); t=random(v[1]+v[2]+v[3]); if(t<v[1], computer = "R", if(t<v[1]+v[2], computer = "P", computer = "S") ); print("Rock, paper, or scissors?"); t = Str(input()); if(#t, player=Vec(t)[1]; if(player <> "R" && player <> "P", player = "S") , player = "S" ); if (player == "R", v[2]++); if (player == "P", v[3]++); if (player == "S", v[1]++); print1(player" vs. "computer": "); if (computer <> player, if((computer == "R" && player = "P") || (computer == "P" && player = "S") || (computer == "S" && player == "R"), print("You win"); losses++ , print("I win"); wins++ ) , print("Tie"); ) ); [wins,losses] }; contest(10)
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.
#Nim
Nim
import parseutils, strutils   proc compress(input: string): string = var count = 1 prev = '\0'   for ch in input: if ch != prev: if prev != '\0': result.add $count & prev count = 1 prev = ch else: inc count result.add $count & prev   proc uncompress(text: string): string = var start = 0 var count: int while true: let n = text.parseInt(count, start) if n == 0 or start + n >= text.len: raise newException(ValueError, "corrupted data.") inc start, n result.add repeat(text[start], count) inc start if start == text.len: break     const Text = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"   echo "Text: ", Text let compressed = Text.compress() echo "Compressed: ", compressed echo "Uncompressed: ", compressed.uncompress()
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
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) file := open(arglist[1],"r") | &input every write(rot13(|read(file))) end   procedure rot13(s) #: returns rot13(string) static a,n initial { a := &lcase || &ucase (&lcase || &lcase) ? n := ( move(13), move(*&lcase) ) (&ucase || &ucase) ? n ||:= ( move(13), move(*&ucase) ) } return map(s,a,n) end
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Ring
Ring
  haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf", "hotel","india","juliet","kilo","lima","mike","needle", "november","oscar","papa","quebec","romeo","sierra","tango", "needle","uniform","victor","whisky","x-ray","yankee","zulu"]   needle = "needle" maxindex = len(haystack)   for index = 1 to maxindex if needle = haystack[index] exit ok next if index <= maxindex see "first found at index " + index + nl ok for last = maxindex to 0 step -1 if needle = haystack[last] exit ok next if !=index see " last found at index " + last + nl else see "not found" + nl ok  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Ruby
Ruby
haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)   %w(Bush Washington).each do |needle| if (i = haystack.index(needle)) puts "#{i} #{needle}" else raise "#{needle} is not in haystack\n" end end
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Erlang
Erlang
-module(roman). -export([to_roman/1]).   to_roman(0) -> []; to_roman(X) when X >= 1000 -> [$M | to_roman(X - 1000)]; to_roman(X) when X >= 100 -> digit(X div 100, $C, $D, $M) ++ to_roman(X rem 100); to_roman(X) when X >= 10 -> digit(X div 10, $X, $L, $C) ++ to_roman(X rem 10); to_roman(X) when X >= 1 -> digit(X, $I, $V, $X).   digit(1, X, _, _) -> [X]; digit(2, X, _, _) -> [X, X]; digit(3, X, _, _) -> [X, X, X]; digit(4, X, Y, _) -> [X, Y]; digit(5, _, Y, _) -> [Y]; digit(6, X, Y, _) -> [Y, X]; digit(7, X, Y, _) -> [Y, X, X]; digit(8, X, Y, _) -> [Y, X, X, X]; digit(9, X, _, Z) -> [X, Z].
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.
#Forth
Forth
create (arabic) 1000 128 * char M + , 500 128 * char D + , 100 128 * char C + , 50 128 * char L + , 10 128 * char X + , 5 128 * char V + , 1 128 * char I + , does> 7 cells bounds do i @ over over 127 and = if nip 7 rshift leave else drop then 1 cells +loop dup ;   : >arabic 0 dup >r >r begin over over while c@ dup (arabic) rot <> while r> over r> over over > if 2* negate + else drop then + swap >r >r 1 /string repeat then drop 2drop r> r> drop ;   s" MCMLXXXIV" >arabic .
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Python
Python
f = lambda x: x * x * x - 3 * x * x + 2 * x   step = 0.001 # Smaller step values produce more accurate and precise results start = -1 stop = 3   sign = f(start) > 0   x = start while x <= stop: value = f(x)   if value == 0: # We hit a root print "Root found at", x elif (value > 0) != sign: # We passed a root print "Root found near", x   # Update our sign sign = value > 0   x += step
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Perl
Perl
  use 5.012; use warnings; use utf8; use open qw(:encoding(utf-8) :std); use Getopt::Long;   package Game { use List::Util qw(shuffle first);   my $turns = 0; my %human_choice = ( rock => 0, paper => 0, scissors => 0, ); my %comp_choice = ( rock => 0, paper => 0, scissors => 0, ); my %what_beats = ( rock => 'paper', paper => 'scissors', scissors => 'rock', ); my $comp_wins = 0; my $human_wins = 0; my $draws = 0;   sub save_human_choice { my $ch = lc pop; if ( exists $human_choice{ $ch } ) { ++$human_choice{ $ch }; } else { die __PACKAGE__ . ":: wrong choice: '$ch'"; } }   sub get_comp_choice { my @keys = shuffle keys %human_choice; my $ch; my ( $prob, $rand ) = ( 0, rand ); $ch = ( first { $rand <= ( $prob += ( $human_choice{ $_ } / $turns ) ) } @keys ) if $turns > 0; $ch //= $keys[0]; $ch = $what_beats{ $ch }; ++$comp_choice{ $ch }; return $ch; }   sub make_turn { my ( $comp_ch, $human_ch ) = ( pop(), pop() ); ++$turns; if ( $what_beats{ $human_ch } eq $comp_ch ) { ++$comp_wins; return 'I win!'; } elsif ( $what_beats{ $comp_ch } eq $human_ch ) { ++$human_wins; return 'You win!'; } else { ++$draws; return 'Draw!'; } }   sub get_final_report { my $report = "You chose:\n" . " rock = $human_choice{rock} times,\n" . " paper = $human_choice{paper} times,\n" . " scissors = $human_choice{scissors} times,\n" . "I chose:\n" . " rock = $comp_choice{rock} times,\n" . " paper = $comp_choice{paper} times,\n" . " scissors = $comp_choice{scissors} times,\n" . "Turns: $turns\n" . "I won: $comp_wins, you won: $human_wins, draws: $draws\n"; return $report; } }   sub main { GetOptions( 'quiet' => \my $quiet ); greet() if !$quiet; while (1) { print_next_line() if !$quiet; my $input = get_input(); last unless $input; if ( $input eq 'error' ) { print "I don't understand!\n" if !$quiet; redo; } my $comp_choice = Game::get_comp_choice(); Game::save_human_choice($input); my $result = Game::make_turn( $input, $comp_choice ); describe_turn_result( $input, $comp_choice, $result ) if !$quiet; } print Game::get_final_report(); }   sub greet { print "Welcome to the Rock-Paper-Scissors game!\n" . "Choose 'rock', 'paper' or 'scissors'\n" . "Enter empty line or 'quit' to quit\n"; }   sub print_next_line { print 'Your choice: '; }   sub get_input { my $input = <>; print "\n" and return if !$input; # EOF chomp $input; return if !$input or $input =~ m/\A \s* q/xi; return ( $input =~ m/\A \s* r/xi ) ? 'rock' : ( $input =~ m/\A \s* p/xi ) ? 'paper' : ( $input =~ m/\A \s* s/xi ) ? 'scissors' : 'error'; }   sub describe_turn_result { my ( $human_ch, $comp_ch, $result ) = @_; print "You chose \u$human_ch, I chose \u$comp_ch. $result\n"; }   main();  
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.
#Objeck
Objeck
use RegEx;   class RunLengthEncoding { function : Main(args : String[]) ~ Nil { input := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";   encoded := Encode(input); "encoding: {$encoded}"->PrintLine(); test := encoded->Equals("12W1B12W3B24W1B14W"); "encoding match: {$test}"->PrintLine();   decoded := Decode(encoded); test := input->Equals(decoded); "decoding match: {$test}"->PrintLine(); }   function : Encode(source : String) ~ String { dest := ""; each(i : source) { runLength := 1; while(i+1 < source->Size() & source->Get(i) = source->Get(i+1)) { runLength+= 1; i+= 1; }; dest->Append(runLength); dest->Append(source->Get(i)); };   return dest; }   function : Decode(source : String) ~ String { output := ""; regex := RegEx->New("[0-9]+|([A-Z]|[a-z])"); found := regex->Find(source); count : Int; each(i : found) { if(i % 2 = 0) { count := found->Get(i)->As(String)->ToInt(); } else { letter := found->Get(i)->As(String); while(count <> 0) { output->Append(letter); count -= 1; }; }; };   return output; } }
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#IS-BASIC
IS-BASIC
100 PROGRAM "Rot13.bas" 110 DO 120 LINE INPUT PROMPT "Line: ":LINE$ 130 PRINT ROT13$(LINE$) 140 LOOP UNTIL LINE$="" 150 DEF ROT13$(TEXT$) 160 LET RESULT$="" 170 FOR I=1 TO LEN(TEXT$) 180 LET CH$=TEXT$(I) 190 SELECT CASE CH$ 200 CASE "A" TO "M","a" TO "m" 210 LET CH$=CHR$(ORD(CH$)+13) 220 CASE "N" TO "Z","n" TO "z" 230 LET CH$=CHR$(ORD(CH$)-13) 240 CASE ELSE 250 END SELECT 260 LET RESULT$=RESULT$&CH$ 270 NEXT 280 LET ROT13$=RESULT$ 290 END DEF
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Run_BASIC
Run BASIC
haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ") needle$ = "Zag Wally Bush Chicken"   while word$(needle$,i+1," ") <> "" i = i + 1 thisNeedle$ = word$(needle$,i," ") + " " j = instr(haystack$,thisNeedle$) k1 = 0 k = instr(haystack$,thisNeedle$,j+1) while k <> 0 k1 = k k = instr(haystack$,thisNeedle$,k+1) wend if j <> 0 then print thisNeedle$;" located at:";j; if k1 <> 0 then print " Last position located at:";k1; print else print thisNeedle$;" is not in the list" end if wend
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
#ERRE
ERRE
  PROGRAM ARAB2ROMAN   DIM ARABIC%[12],ROMAN$[12]   PROCEDURE TOROMAN(VALUE->ANS$) LOCAL RESULT$ FOR I%=0 TO 12 DO WHILE VALUE>=ARABIC%[I%] DO RESULT$+=ROMAN$[I%] VALUE-=ARABIC%[I%] END WHILE END FOR ANS$=RESULT$ END PROCEDURE   BEGIN ! !Testing ! ARABIC%[]=(1000,900,500,400,100,90,50,40,10,9,5,4,1) ROMAN$[]=("M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I") TOROMAN(2009->ANS$) PRINT("2009 = ";ANS$) TOROMAN(1666->ANS$) PRINT("1666 = ";ANS$) TOROMAN(3888->ANS$) PRINT("3888 = ";ANS$) END PROGRAM  
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.
#Fortran
Fortran
program Roman_decode implicit none   write(*,*) decode("MCMXC"), decode("MMVIII"), decode("MDCLXVI")   contains   function decode(roman) result(arabic) character(*), intent(in) :: roman integer :: i, n, lastval, arabic   arabic = 0 lastval = 0 do i = len(roman), 1, -1 select case(roman(i:i)) case ('M','m') n = 1000 case ('D','d') n = 500 case ('C','c') n = 100 case ('L','l') n = 50 case ('X','x') n = 10 case ('V','v') n = 5 case ('I','i') n = 1 case default n = 0 end select if (n < lastval) then arabic = arabic - n else arabic = arabic + n end if lastval = n end do end function decode end program Roman_decode
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#R
R
f <- function(x) x^3 -3*x^2 + 2*x   findroots <- function(f, begin, end, tol = 1e-20, step = 0.001) { se <- ifelse(sign(f(begin))==0, 1, sign(f(begin))) x <- begin while ( x <= end ) { v <- f(x) if ( abs(v) < tol ) { print(sprintf("root at %f", x)) } else if ( ifelse(sign(v)==0, 1, sign(v)) != se ) { print(sprintf("root near %f", x)) } se <- ifelse( sign(v) == 0 , 1, sign(v)) x <- x + step } }   findroots(f, -1, 3)
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Phix
Phix
--standard game constant rule3 = {"rock blunts scissors", "paper wraps rock", "scissors cut paper"} --extended version constant rule5 = {"rock blunts scissors", "rock crushes lizard", "paper wraps rock", "paper disproves spock", "scissors cut paper", "scissors decapitate lizard", "lizard eats paper", "lizard poisons spock", "spock smashes scissors", "spock vaporizes rock"}   constant rules = iff(rand(2)=1?rule3:rule5)   sequence what = {} sequence beats = {} string wkeys = "" string question = "What is your move " integer choices, hsum sequence history, cplays, pplays   object x, verb, y   for i=1 to length(rules) do {x} = split(rules[i]) if not find(x,what) then what = append(what,x) if find(x[1],wkeys) then wkeys = append(wkeys,x[$]) question &= x[1..-2]&"("&x[$]&"), " else wkeys = append(wkeys,x[1]) question &= "("&x[1]&")"&x[2..$]&", " end if end if end for choices = length(wkeys) history = repeat(1,choices) hsum = 3 cplays = repeat(0,choices) pplays = repeat(0,choices) beats = repeat(repeat(0,choices),choices) question[-2] = '?' for i=1 to length(rules) do {x,verb,y} = split(rules[i]) beats[find(x,what)][find(y,what)] = verb end for   integer cmove, pmove, draws = 0, pwins = 0, cwins = 0 while 1 do cmove = rand(hsum) for i=1 to choices do cmove -= history[i] if cmove<=0 then -- predicted user choice of i, find whatever beats it for j=1 to choices do if string(beats[j][i]) then cmove = j exit end if end for exit end if end for puts(1,question) while 1 do pmove = lower(wait_key()) if pmove='q' then exit end if pmove = find(pmove,wkeys) if pmove!=0 then exit end if end while if pmove='q' then exit end if   printf(1,"you: %s, me: %s, ",{what[pmove],what[cmove]}) cplays[cmove] += 1 pplays[pmove] += 1 if cmove=pmove then printf(1,"a draw.\n") draws += 1 else if string(beats[cmove][pmove]) then printf(1,"%s %s %s. I win.\n",{what[cmove],beats[cmove][pmove],what[pmove]}) cwins += 1 elsif string(beats[pmove][cmove]) then printf(1,"%s %s %s. You win.\n",{what[pmove],beats[pmove][cmove],what[cmove]}) pwins += 1 else  ?9/0 -- sanity check end if end if history[pmove] += 1 hsum += 1 end while printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws}) printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws}) printf(1," ") for i=1 to choices do printf(1,"%9s",what[i]) end for printf(1,"\nyou: ") for i=1 to choices do printf(1,"%9d",pplays[i]) end for printf(1,"\n me: ") for i=1 to choices do printf(1,"%9d",cplays[i]) end for
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.
#Objective-C
Objective-C
let encode str = let len = String.length str in let rec aux i acc = if i >= len then List.rev acc else let c1 = str.[i] in let rec aux2 j = if j >= len then (c1, j-i) else let c2 = str.[j] in if c1 = c2 then aux2 (j+1) else (c1, j-i) in let (c,n) as t = aux2 (i+1) in aux (i+n) (t::acc) in aux 0 [] ;;   let decode lst = let l = List.map (fun (c,n) -> String.make n c) lst in (String.concat "" l)
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
#J
J
rot13=: {&((65 97+/~i.2 13) |.@[} i.256)&.(a.&i.)
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Rust
Rust
fn main() { let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"];   println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush")); println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush")); println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob")); }  
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
#Euphoria
Euphoria
constant arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 } constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}   function toRoman(integer val) sequence result result = "" for i = 1 to 13 do while val >= arabic[i] do result &= roman[i] val -= arabic[i] end while end for return result end function   printf(1,"%d = %s\n",{2009,toRoman(2009)}) printf(1,"%d = %s\n",{1666,toRoman(1666)}) printf(1,"%d = %s\n",{3888,toRoman(3888)})
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function romanDecode(roman As Const String) As Integer If roman = "" Then Return 0 '' zero denotes invalid roman number Dim roman1(0 To 2) As String = {"MMM", "MM", "M"} Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"} Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"} Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"} Dim As Integer i, value = 0, length = 0 Dim r As String = UCase(roman)   For i = 0 To 2 If Left(r, Len(roman1(i))) = roman1(i) Then value += 1000 * (3 - i) length = Len(roman1(i)) r = Mid(r, length + 1) length = 0 Exit For End If Next   For i = 0 To 8 If Left(r, Len(roman2(i))) = roman2(i) Then value += 100 * (9 - i) length = Len(roman2(i)) r = Mid(r, length + 1) length = 0 Exit For End If Next   For i = 0 To 8 If Left(r, Len(roman3(i))) = roman3(i) Then value += 10 * (9 - i) length = Len(roman3(i)) r = Mid(r, length + 1) length = 0 Exit For End If Next   For i = 0 To 8 If Left(r, Len(roman4(i))) = roman4(i) Then value += 9 - i length = Len(roman4(i)) Exit For End If Next   ' Can't be a valid roman number if there are any characters left If Len(r) > length Then Return 0 Return value End Function   Dim a(2) As String = {"MCMXC", "MMVIII" , "MDCLXVI"} For i As Integer = 0 To 2 Print a(i); Tab(8); " =>"; romanDecode(a(i)) Next   Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Racket
Racket
  #lang racket   ;; Attempts to find all roots of a real-valued function f ;; in a given interval [a b] by dividing the interval into N parts ;; and using the root-finding method on each subinterval ;; which proves to contain a root. (define (find-roots f a b #:divisions [N 10] #:method [method secant]) (define h (/ (- b a) N)) (for*/list ([x1 (in-range a b h)] [x2 (in-value (+ x1 h))] #:when (or (root? f x1) (includes-root? f x1 x2))) (find-root f x1 x2 #:method method)))   ;; Finds a root of a real-valued function f ;; in a given interval [a b]. (define (find-root f a b #:method [method secant]) (cond [(root? f a) a] [(root? f b) b] [else (and (includes-root? f a b) (method f a b))]))   ;; Returns #t if x is a root of a real-valued function f ;; with absolute accuracy (tolerance). (define (root? f x) (almost-equal? 0 (f x)))   ;; Returns #t if interval (a b) contains a root ;; (or the odd number of roots) of a real-valued function f. (define (includes-root? f a b) (< (* (f a) (f b)) 0))   ;; Returns #t if a and b are equal with respect to ;; the relative accuracy (tolerance). (define (almost-equal? a b) (or (< (abs (+ b a)) (tolerance)) (< (abs (/ (- b a) (+ b a))) (tolerance))))   (define tolerance (make-parameter 5e-16))  
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Raku
Raku
sub f(\x) { x³ - 3*x² + 2*x }   my $start = -1; my $stop = 3; my $step = 0.001;   for $start, * + $step ... $stop -> $x { state $sign = 0; given f($x) { my $next = .sign; when 0.0 { say "Root found at $x"; } when $sign and $next != $sign { say "Root found near $x"; } NEXT $sign = $next; } }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   0 var wh 0 var wc   ( "Scissors cuts Paper" "Paper covers Rock" "Rock crushes Lizard" "Lizard poisons Spock" "Spock smashes Scissors" "Scissors decapites Lizard" "Lizard eats Paper" "Paper disproves Spock" "Spock vaporizes Rock" "Rock blunts Scissors" )   "'Rock, Paper, Scissors, Lizard, Spock!' rules are: " ? nl len for get ? endfor nl   ( ( "S" "Scissors" ) ( "P" "Paper" ) ( "R" "Rock" ) ( "L" "Lizard" ) ( "K" "Spock" ) )   true while "Choose (S)cissors, (P)paper, (R)ock, (L)izard, Spoc(K) or (Q)uit: " input nl upper dup "Q" == if nl drop false else getd if dup "You choose " print ? var he rand 5 * int 1 + 2 2 tolist sget dup "I choose " print ? var ce he ce == if "Draw" ? else swap len for get dup split 2 del he ce 2 tolist over over == rot rot reverse == or if exitfor else drop endif endfor dup ? he find 1 == if wh 1 + var wh "You win!" else wc 1 + var wc "I win!" endif ? drop swap endif else print " is a invalid input!" ? endif true endif endwhile drop drop "Your punctuation: " print wh ? "Mi punctuation: " print wc ? wh wc > if "You win!" else wh wc < if "I win!" else "Draw!" endif endif ?
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#OCaml
OCaml
let encode str = let len = String.length str in let rec aux i acc = if i >= len then List.rev acc else let c1 = str.[i] in let rec aux2 j = if j >= len then (c1, j-i) else let c2 = str.[j] in if c1 = c2 then aux2 (j+1) else (c1, j-i) in let (c,n) as t = aux2 (i+1) in aux (i+n) (t::acc) in aux 0 [] ;;   let decode lst = let l = List.map (fun (c,n) -> String.make n c) lst in (String.concat "" l)
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
#Java
Java
import java.io.*;   public class Rot13 {   public static void main(String[] args) throws IOException { if (args.length >= 1) { for (String file : args) { try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { rot13(in, System.out); } } } else { rot13(System.in, System.out); } }   private static void rot13(InputStream in, OutputStream out) throws IOException { int ch; while ((ch = in.read()) != -1) { out.write(rot13((char) ch)); } }   private static char rot13(char ch) { if (ch >= 'A' && ch <= 'Z') { return (char) (((ch - 'A') + 13) % 26 + 'A'); } if (ch >= 'a' && ch <= 'z') { return (char) (((ch - 'a') + 13) % 26 + 'a'); } return ch; } }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#S-lang
S-lang
variable haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","Ronald"];   define find(needle) { variable i = where(haystack == needle); if (length(i)) {  % print(sprintf("%s: first=%d, last=%d", needle, i[0], i[-1])); return(i[0], i[-1]); } else throw ApplicationError, "an exception"; }   ($1, $2) = find("Ronald");  % returns 3, 9 ($1, $2) = find("McDonald");  % throws ApplicationError, labelled "an exception"  
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
#Excel
Excel
  =ROMAN(2013,0)  
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.
#FutureBasic
FutureBasic
window 1   local fn RomantoDecimal( roman as CFStringRef ) as long long i, n, preNum = 0, num = 0   for i = len(roman) - 1 to 0 step -1 n = 0 select ( fn StringCharacterAtIndex( roman, i ) ) case _"M" : n = 1000 case _"D" : n = 500 case _"C" : n = 100 case _"L" : n = 50 case _"X" : n = 10 case _"V" : n = 5 case _"I" : n = 1 end select if ( n < preNum ) then num = num - n else num = num + n preNum = n next   end fn = num   print @" MCMXC = "; fn RomantoDecimal( @"MCMXC" ) print @" MMVIII = "; fn RomantoDecimal( @"MMVIII" ) print @" MMXVI = "; fn RomantoDecimal( @"MMXVI" ) print @"MDCLXVI = "; fn RomantoDecimal( @"MDCLXVI" ) print @" MCMXIV = "; fn RomantoDecimal( @"MCMXIV" ) print @" DXIII = "; fn RomantoDecimal( @"DXIII" ) print @" M = "; fn RomantoDecimal( @"M" ) print @" DXIII = "; fn RomantoDecimal( @"DXIII" ) print @" XXXIII = "; fn RomantoDecimal( @"XXXIII" )   HandleEvents
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#REXX
REXX
/*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/ parse arg bot top inc . /*obtain optional arguments from the CL*/ if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/ if top=='' | top=="," then top= +5 /* " " " " " " */ if inc=='' | inc=="," then inc= .0001 /* " " " " " " */ z= f(bot - inc) /*compute 1st value to start compares. */ != sign(z) /*obtain the sign of the initial value.*/ do j=bot to top by inc /*traipse through the specified range. */ z= f(j); $= sign(z) /*compute new value; obtain the sign. */ if z=0 then say 'found an exact root at' j/1 else if !\==$ then if !\==0 then say 'passed a root at' j/1  != $ /*use the new sign for the next compare*/ end /*j*/ /*dividing by unity normalizes J [↑] */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ f: parse arg x; return x * (x * (x-3) +2) /*formula used ──► x^3 - 3x^2 + 2x */ /*with factoring ──► x{ x^2 -3x + 2 } */ /*more " ──► x{ x( x-3 ) + 2 } */
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#PHP
PHP
    <?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo "";   $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";   $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; }   echo "<br>" . $results; ?>  
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.
#Oforth
Oforth
: encode(s) StringBuffer new s group apply(#[ tuck size asString << swap first <<c ]) ;   : decode(s) | c i | StringBuffer new 0 s forEach: c [ c isDigit ifTrue: [ 10 * c asDigit + continue ] loop: i [ c <<c ] 0 ] drop ;
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
#JavaScript
JavaScript
function rot13(c) { return c.replace(/([a-m])|([n-z])/ig, function($0,$1,$2) { return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0; }); } rot13("ABJURER nowhere") // NOWHERE abjurer  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Sather
Sather
class MAIN is main is haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|; needles :ARRAY{STR} := | "Washington", "Bush" |; loop needle ::= needles.elt!; index ::= haystack.index_of(needle); if index < 0 then #OUT + needle + " is not in the haystack\n"; else #OUT + index + " " + needle + "\n"; end; end; end; end;
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Scala
Scala
def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2) def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last
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
#F.23
F#
let digit x y z = function 1 -> x | 2 -> x + x | 3 -> x + x + x | 4 -> x + y | 5 -> y | 6 -> y + x | 7 -> y + x + x | 8 -> y + x + x + x | 9 -> x + z | _ -> failwith "invalid call to digit"   let rec to_roman acc = function | x when x >= 1000 -> to_roman (acc + "M") (x - 1000) | x when x >= 100 -> to_roman (acc + digit "C" "D" "M" (x / 100)) (x % 100) | x when x >= 10 -> to_roman (acc + digit "X" "L" "C" (x / 10)) (x % 10) | x when x > 0 -> acc + digit "I" "V" "X" x | 0 -> acc | _ -> failwith "invalid call to_roman (negative input)"   let roman n = to_roman "" n   [<EntryPoint>] let main args = [1990; 2008; 1666] |> List.map (fun n -> roman n) |> List.iter (printfn "%s") 0
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.
#Gambas
Gambas
'This code will create a GUI Form and Objects and carry out the Roman Numeral convertion as you type 'The input is case insensitive 'A basic check for invalid charaters is made   hTextBox As TextBox 'To allow the creation of a TextBox hValueBox As ValueBox 'To allow the creation of a ValueBox   Public Sub Form_Open() 'Form opens..   SetUpForm 'Go to the SetUpForm Routine hTextBox.text = "MCMXC" 'Put a Roman numeral in the TextBox   End   Public Sub TextBoxInput_Change() 'Each time the TextBox text changes.. Dim cRomanN As Collection = ["M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1] 'Collection of nemerals e.g 'M' = 1000 Dim cMinus As Collection = ["IV": -2, "IX": -2, "XL": -20, "XC": - 20, "CD": -200, "CM": -200] 'Collection of the 'one less than' numbers e.g. 'IV' = 4 Dim sClean, sTemp As String 'Various string variables Dim siCount As Short 'Counter Dim iTotal As Integer 'Stores the total of the calculation   hTextBox.Text = UCase(hTextBox.Text) 'Make any text in the TextBox upper case   For siCount = 1 To Len(hTextBox.Text) 'Loop through each character in the TextBox If InStr("MDCLXVI", Mid(hTextBox.Text, siCount, 1)) Then 'If a Roman numeral exists then.. sClean &= Mid(hTextBox.Text, siCount, 1) 'Put it in 'sClean' (Stops input of non Roman numerals) End If Next   hTextBox.Text = sClean 'Put the now clean text in the TextBox   For siCount = 1 To Len(hTextBox.Text) 'Loop through each character in the TextBox iTotal += cRomanN[Mid(hTextBox.Text, siCount, 1)] 'Total up all the characters, note 'IX' will = 11 not 9 Next   For Each sTemp In cMinus 'Loop through each item in the cMinus Collection If InStr(sClean, cMinus.Key) > 0 Then iTotal += Val(sTemp) 'If a 'Minus' value is in the string e.g. 'IX' which has been calculated at 11 subtract 2 = 9 Next   hValueBox.text = iTotal 'Display the total   End   Public Sub SetUpForm() 'Create the Objects for the Form Dim hLabel1, hLabel2 As Label 'For 2 Labels   Me.height = 150 'Form Height Me.Width = 300 'Form Width Me.Padding = 20 'Form padding (border) Me.Text = "Roman Numeral converter" 'Text in Form header Me.Arrangement = Arrange.Vertical 'Form arrangement   hLabel1 = New Label(Me) 'Create a Label hLabel1.Height = 21 'Label Height hLabel1.expand = True 'Expand the Label hLabel1.Text = "Enter a Roman numeral" 'Put text in the Label   hTextBox = New TextBox(Me) As "TextBoxInput" 'Set up a TextBox with an Event Label hTextBox.Height = 21 'TextBox height hTextBox.expand = True 'Expand the TextBox   hLabel2 = New Label(Me) 'Create a Label hLabel2.Height = 21 'Label Height hLabel2.expand = True 'Expand the Label hLabel2.Text = "The decimal equivelent is: -" 'Put text in the Label   hValueBox = New ValueBox(Me) 'Create a ValueBox hValueBox.Height = 21 'ValuBox Height hValueBox.expand = True 'Expand the ValueBox hValueBox.ReadOnly = True 'Set ValueBox to Read Only   End
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Ring
Ring
  load "stdlib.ring" function = "return pow(x,3)-3*pow(x,2)+2*x" rangemin = -1 rangemax = 3 stepsize = 0.001 accuracy = 0.1 roots(function, rangemin, rangemax, stepsize, accuracy)   func roots funct, min, max, inc, eps oldsign = 0 for x = min to max step inc num = sign(eval(funct)) if num = 0 see "root found at x = " + x + nl num = -oldsign else if num != oldsign and oldsign != 0 if inc < eps see "root found near x = " + x + nl else roots(funct, x-inc, x+inc/8, inc/8, eps) ok ok ok oldsign = num next  
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Picat
Picat
go ?=> println("\nEnd terms with '.'.\n'quit.' ends the session.\n"), Prev = findall(P,beats(P,_)), ChoiceMap = new_map([P=0 : P in Prev]), ResultMap = new_map([computer_wins=0,user_wins=0,draw=0]), play(Prev,ChoiceMap,ResultMap), nl, println("Summary:"), println(choiceMap=ChoiceMap), println(resultMap=ResultMap), nl.   go => true.   % % Play an interactive game. % play(Prev,ChoiceMap,ResultMap) => print("Your choice? "), P = read_term(), if P == quit then nl, print_result(ResultMap) else C = choice(ChoiceMap), printf("The computer chose %w%n", C), result(C,P,Prev,Next,Result), ChoiceMap.put(P,ChoiceMap.get(P)+1), ResultMap.put(Result,ResultMap.get(Result,0)+1), play(Next,ChoiceMap,ResultMap) end.   % % Do a weighted random choice based on the user's previous choices. % weighted_choice(Map) = Choice => Map2 = [(V+1)=K : K=V in Map].sort, % ensure that all choices can be made  % Prepare the probability matrix M Total = sum([P : P=_ in Map2]), Len = Map2.len, M = new_array(Len,2), T = new_list(Len), foreach({I,P=C} in zip(1..Len,Map2)) if I == 1 then M[I,1] := 1, M[I,2] := P else M[I,1] := M[I-1,2]+1, M[I,2] := M[I,1]+P-1 end, T[I] := C end, M[Len,2] := Total,    % Pick a random number in 1..Total R = random(1,Total), Choice = _,  % Check were R match foreach(I in 1..Len, var(Choice)) if M[I,1] <= R, M[I,2] >= R then Choice := T[I] end end.   % % Check probably best counter choice. % choice(Map) = Choice =>  % what is the Player's probably choice PlayersProbablyMove = weighted_choice(Map),  % select the choice that beats it beats(Choice,PlayersProbablyMove).     print_result(ResultMap) => foreach(C in ResultMap.keys) println(C=ResultMap.get(C)) end, nl.   % This part is from the Prolog version. result(C,P,R,[C|R],Result) :- beats(C,P), Result = computer_wins, printf("Computer wins.\n"). result(C,P,R,[B|R],Result) :- beats(P,C), beats(B,P), Result=user_wins, printf("You win!%n"). result(C,C,R,[B|R],Result) :- beats(B,C), Result=draw, printf("It is a draw\n").   beats(paper, rock). beats(rock, scissors). beats(scissors, paper).
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#PicoLisp
PicoLisp
(use (C Mine Your) (let (Rock 0 Paper 0 Scissors 0) (loop (setq Mine (let N (if (gt0 (+ Rock Paper Scissors)) (rand 1 @) 0) (seek '((L) (le0 (dec 'N (caar L)))) '(Rock Paper Scissors .) ) ) ) (prin "Enter R, P or S to play, or Q to quit: ") (loop (and (= "Q" (prinl (setq C (uppc (key))))) (bye)) (T (setq Your (find '((S) (pre? C S)) '(Rock Paper Scissors)))) (prinl "Bad input - try again") ) (prinl "I say " (cadr Mine) ", You say " Your ": " (cond ((== Your (cadr Mine)) "Draw") ((== Your (car Mine)) "I win") (T "You win") ) ) (inc Your) ) ) )
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.
#Ol
Ol
  (define (RLE str) (define iter (string->list str)) (let loop ((iter iter) (chr (car iter)) (n 0) (rle '())) (cond ((null? iter) (reverse (cons (cons n chr) rle))) ((char=? chr (car iter)) (loop (cdr iter) chr (+ n 1) rle)) (else (loop (cdr iter) (car iter) 1 (cons (cons n chr) rle))))))   (define (decode rle) (apply string-append (map (lambda (p) (make-string (car p) (cdr p))) rle)))  
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
#jq
jq
#!/usr/bin/env jq -M -R -r -f # or perhaps: #!/usr/local/bin/jq -M -R -r -f   # If your operating system does not allow more than one option # to be specified on the command line, # then consider using a version of jq that allows # command-line options to be squished together (-MRrf), # or see the following subsection.   def rot13: explode | map( if 65 <= . and . <= 90 then ((. - 52) % 26) + 65 elif 97 <= . and . <= 122 then (. - 84) % 26 + 97 else . end) | implode;   rot13
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Scheme
Scheme
(define haystack '("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))   (define index-of (lambda (needle hackstack) (let ((tail (member needle haystack))) (if tail (- (length haystack) (length tail)) (throw 'needle-missing)))))   (define last-index-of (lambda (needle hackstack) (let ((tail (member needle (reverse haystack)))) (if tail (- (length tail) 1) (throw 'needle-missing)))))
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
#Factor
Factor
USE: roman ( scratchpad ) 3333 >roman . "mmmcccxxxiii"
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.
#Go
Go
package main   import ( "errors" "fmt" )   var m = map[rune]int{ 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, }   func parseRoman(s string) (r int, err error) { if s == "" { return 0, errors.New("Empty string") } is := []rune(s) // easier to convert string up front var c0 rune // c0: roman character last read var cv0 int // cv0: value of cv   // the key to the algorithm is to process digits from right to left for i := len(is) - 1; i >= 0; i-- { // read roman digit c := is[i] k := c == '\u0305' // unicode overbar combining character if k { if i == 0 { return 0, errors.New( "Overbar combining character invalid at position 0") } i-- c = is[i] } cv := m[c] if cv == 0 { if c == 0x0305 { return 0, fmt.Errorf( "Overbar combining character invalid at position %d", i) } else { return 0, fmt.Errorf( "Character unrecognized as Roman digit: %c", c) } } if k { c = -c // convention indicating overbar cv *= 1000 }   // handle cases of new, same, subtractive, changed, in that order. switch { default: // case 4: digit change fallthrough case c0 == 0: // case 1: no previous digit c0 = c cv0 = cv case c == c0: // case 2: same digit case cv*5 == cv0 || cv*10 == cv0: // case 3: subtractive // handle next digit as new. // a subtractive digit doesn't count as a previous digit. c0 = 0 r -= cv // subtract... continue // ...instead of adding } r += cv // add, in all cases except subtractive } return r, nil }   func main() { // parse three numbers mentioned in task description for _, r := range []string{"MCMXC", "MMVIII", "MDCLXVI"} { v, err := parseRoman(r) if err != nil { fmt.Println(err) } else { fmt.Println(r, "==", v) } } }
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#RLaB
RLaB
  f = function(x) { rval = x .^ 3 - 3 * x .^ 2 + 2 * x; return rval; };   >> findroot(f, , [-5,5]) 0  
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#PL.2FI
PL/I
  rock: procedure options (main); /* 30 October 2013 */ declare move character (1), cm fixed binary;   put ('The Rock-Paper-Scissors game'); put skip list ("please type 'r' for rock, 'p' for paper, 's' for scissors."); put skip list ("Anything else finishes:"); do forever; get edit (move) (a(1)); move = lowercase(move); if index('rpsq', move) = 0 then iterate; if move = 'q' then stop; cm = random()*3; /* computer moves: 0 = rock, 1 = paper, 2 = scissors */ select (cm); when (0) select (move); when ('r') put list ('rock and rock: A draw'); when ('p') put list ('paper beats rock: You win'); when ('s') put list ('rock breaks scissors: I win'); end; when (1) select (move); when ('r') put list ('paper beats rock: I win'); when ('p') put list ('paper and paper: A draw'); when ('s') put list ('scissors cut paper: You win'); end; when (2) select (move); when ('r') put list ('rock breaks scissors: You win'); when ('p') put list ('scissors cuts paper: I win'); when ('s') put list ('Scissors and Scissors: A draw'); end; end; end; end rock;  
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.
#Oz
Oz
declare fun {RLEncode Xs} for G in {Group Xs} collect:C do {C {Length G}#G.1} end end   fun {RLDecode Xs} for C#Y in Xs append:Ap do {Ap {Replicate Y C}} end end   %% Helpers %% e.g. "1122" -> ["11" "22"] fun {Group Xs} case Xs of nil then nil [] X|Xr then Ys Zs {List.takeDropWhile Xr fun {$ W} W==X end ?Ys ?Zs} in (X|Ys) | {Group Zs} end end %% e.g. 3,4 -> [3 3 3 3] fun {Replicate X N} case N of 0 then nil else X|{Replicate X N-1} end end   Data = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" Enc = {RLEncode Data} in {System.showInfo Data} {Show Enc} {System.showInfo {RLDecode Enc}}
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
#Jsish
Jsish
#!/usr/local/bin/jsish /* ROT-13 in Jsish */ function rot13(msg:string) { return msg.replace(/([a-m])|([n-z])/ig, function(m,p1,p2,ofs,str) { return String.fromCharCode( p1 ? p1.charCodeAt(0) + 13 : p2 ? p2.charCodeAt(0) - 13 : 0) || m; }); } provide('rot13', Util.verConvert("1.0"));   /* rot13 command line utility */ if (isMain()) { /* Unit testing */ if (Interp.conf('unitTest') > 0) { ; rot13('ABJURER nowhere 123!'); ; rot13(rot13('Same old same old')); return; }   /* rot-13 of data lines from given filenames or stdin, to stdout */ function processFile(fname:string) { var str; if (fname == "stdin") fname = "./stdin"; if (fname == "-") fname = "stdin"; var fin = new Channel(fname, 'r'); while (str = fin.gets()) puts(rot13(str)); fin.close(); }   if (console.args.length == 0) console.args.push('-'); for (var fn of console.args) { try { processFile(fn); } catch(err) { puts(err, "processing", fn); } } }   /* =!EXPECTSTART!= rot13('ABJURER nowhere 123!') ==> NOWHERE abjurer 123! rot13(rot13('Same old same old')) ==> Same old same old =!EXPECTEND!= */
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#SenseTalk
SenseTalk
  put ("apple", "banana", "cranberry" ,"durian", "eggplant", "grape", "banana", "appl", "blackberry") into fruitList   put findInList(fruitList,"banana") // 2 put findInList(fruitList,"banana", true) // 7 put findInList(fruitList,"tomato") // throws an exception   function findInList paramList, paramItem, findLast set temp to every offset of paramItem within paramList if (number of items in temp = 0) Throw InvalidSearch, "Item not found in list" end if if findLast return last item of temp else return first item of temp end if end findInList  
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
#FALSE
FALSE
^$." " [$999>][1000- "M"]# $899> [ 900-"CM"]? $499> [ 500- "D"]? $399> [ 400-"CD"]? [$ 99>][ 100- "C"]# $ 89> [ 90-"XC"]? $ 49> [ 50- "L"]? $ 39> [ 40-"XL"]? [$ 9>][ 10- "X"]# $ 8> [ 9-"IX"]? $ 4> [ 5- "V"]? $ 3> [ 4-"IV"]? [$ ][ 1- "I"]#%
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost 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.
#Golo
Golo
#!/usr/bin/env golosh ---- This module converts a Roman numeral into a decimal number. ---- module Romannumeralsdecode   augment java.lang.Character {   function decode = |this| -> match { when this == 'I' then 1 when this == 'V' then 5 when this == 'X' then 10 when this == 'L' then 50 when this == 'C' then 100 when this == 'D' then 500 when this == 'M' then 1000 otherwise 0 } }   augment java.lang.String {   function decode = |this| { var accumulator = 0 foreach i in [0..this: length()] { let currentChar = this: charAt(i) let nextChar = match { when i + 1 < this: length() then this: charAt(i + 1) otherwise null } if (currentChar: decode() < (nextChar?: decode() orIfNull 0)) { # if this is something like IV or IX or whatever accumulator = accumulator - currentChar: decode() } else { accumulator = accumulator + currentChar: decode() } } return accumulator } }   function main = |args| { println("MCMXC = " + "MCMXC": decode()) println("MMVIII = " + "MMVIII": decode()) println("MDCLXVI = " + "MDCLXVI": decode()) }  
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Ruby
Ruby
def sign(x) x <=> 0 end   def find_roots(f, range, step=0.001) sign = sign(f[range.begin]) range.step(step) do |x| value = f[x] if value == 0 puts "Root found at #{x}" elsif sign(value) == -sign puts "Root found between #{x-step} and #{x}" end sign = sign(value) end end   f = lambda { |x| x**3 - 3*x**2 + 2*x } find_roots(f, -1..3)
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Prolog
Prolog
play :- findall(P,beats(P,_),Prev), play(Prev).   play(Prev) :- write('your choice? '), read(P), random_member(C, Prev), format('The computer chose ~p~n', C), result(C,P,Prev,Next), !, play(Next).   result(C,P,R,[C|R]) :- beats(C,P), format('Computer wins.~n'). result(C,P,R,[B|R]) :- beats(P,C), beats(B,P), format('You win!~n'). result(C,C,R,[B|R]) :- beats(B,C), format('It is a draw~n').   beats(paper, rock). beats(rock, scissors). beats(scissors, paper).
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.
#PARI.2FGP
PARI/GP
rle(s)={ if(s=="", return(s)); my(v=Vec(s),cur=v[1],ct=1,out=""); v=concat(v,99); \\ sentinel for(i=2,#v, if(v[i]==cur, ct++ , out=Str(out,ct,cur); cur=v[i]; ct=1 ) ); out }; elr(s)={ if(s=="", return(s)); my(v=Vec(s),ct=eval(v[1]),out=""); v=concat(v,99); \\ sentinel for(i=2,#v, if(v[i]>="0" && v[i]<="9", ct=10*ct+eval(v[i]) , for(j=1,ct,out=Str(out,v[i])); ct=0 ) ); out }; rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") elr(%)
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
#Julia
Julia
  # Julia 1.0 function rot13(c::Char) shft = islowercase(c) ? 'a' : 'A' isletter(c) ? c = shft + (c - shft + 13) % 26 : c end   rot13(str::AbstractString) = map(rot13, str)
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Sidef
Sidef
var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);   %w(Bush Washington).each { |needle| var i = haystack.first_index{|item| item == needle}; if (i >= 0) { say "#{i} #{needle}"; } else { die "#{needle} is not in haystack"; } }
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
#Fan
Fan
** ** converts a number to its roman numeral representation ** class RomanNumerals {   private Str digit(Str x, Str y, Str z, Int i) { switch (i) { case 1: return x case 2: return x+x case 3: return x+x+x case 4: return x+y case 5: return y case 6: return y+x case 7: return y+x+x case 8: return y+x+x+x case 9: return x+z } return "" }   Str toRoman(Int i) { if (i>=1000) { return "M" + toRoman(i-1000) } if (i>=100) { return digit("C", "D", "M", i/100) + toRoman(i%100) } if (i>=10) { return digit("X", "L", "C", i/10) + toRoman(i%10) } if (i>=1) { return digit("I", "V", "X", i) } return "" }   Void main() { 2000.times |i| { echo("$i = ${toRoman(i)}") } }   }
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost 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.
#Groovy
Groovy
enum RomanDigits { I(1), V(5), X(10), L(50), C(100), D(500), M(1000);   private magnitude; private RomanDigits(magnitude) { this.magnitude = magnitude }   String toString() { super.toString() + "=${magnitude}" }   static BigInteger parse(String numeral) { assert numeral != null && !numeral.empty def digits = (numeral as List).collect { RomanDigits.valueOf(it) } def L = digits.size() (0..<L).inject(0g) { total, i -> def sign = (i == L - 1 || digits[i] >= digits[i+1]) ? 1 : -1 total + sign * digits[i].magnitude } } }
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Rust
Rust
// 202100315 Rust programming solution   use roots::find_roots_cubic;   fn main() {   let roots = find_roots_cubic(1f32, -3f32, 2f32, 0f32);   println!("Result : {:?}", roots); }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#PureBasic
PureBasic
Enumeration ;choices are in listed according to their cycle, weaker followed by stronger #rock #paper #scissors #numChoices ;this comes after all possible choices EndEnumeration   ;give names to each of the choices Dim choices.s(#numChoices - 1) choices(#rock) = "rock" choices(#paper) = "paper" choices(#scissors) = "scissors"   Define gameCount Dim playerChoiceHistory(#numChoices - 1)   Procedure weightedRandomChoice() Shared gameCount, playerChoiceHistory() Protected x = Random(gameCount - 1), t, c   For i = 0 To #numChoices - 1 t + playerChoiceHistory(i) If t >= x c = i Break EndIf Next   ProcedureReturn (c + 1) % #numChoices EndProcedure   If OpenConsole() PrintN("Welcome to the game of rock-paper-scissors") PrintN("Each player guesses one of these three, and reveals it at the same time.") PrintN("Rock blunts scissors, which cut paper, which wraps stone.") PrintN("If both players choose the same, it is a draw!") PrintN("When you've had enough, choose Q.")   Define computerChoice, playerChoice, response.s Define playerWins, computerWins, draw, quit   computerChoice = Random(#numChoices - 1) Repeat Print(#CRLF$ + "What is your move (press R, P, or S)?") Repeat response = LCase(Input()) Until FindString("rpsq", response) > 0   If response = "q": quit = 1 Else gameCount + 1 playerChoice = FindString("rps", response) - 1   result = (playerChoice - computerChoice + #numChoices) % #numChoices Print("You chose " + choices(playerChoice) + " and I chose " + choices(computerChoice)) Select result Case 0 PrintN(". It's a draw.") draw + 1 Case 1 PrintN(". You win!") playerWins + 1 Case 2 PrintN(". I win!") computerWins + 1 EndSelect playerChoiceHistory(playerChoice) + 1 computerChoice = weightedRandomChoice() EndIf Until quit   Print(#CRLF$ + "You chose: ") For i = 0 To #numChoices - 1 Print(choices(i) + " " + StrF(playerChoiceHistory(i) * 100 / gameCount, 1) + "%; ") Next PrintN("") PrintN("You won " + Str(playerWins) + ", and I won " + Str(computerWins) + ". There were " + Str(draw) + " draws.") PrintN("Thanks for playing!")   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#Pascal
Pascal
Program RunLengthEncoding(output);   procedure encode(s: string; var counts: array of integer; var letters: string); var i, j: integer; begin j := 0; letters := ''; if length(s) > 0 then begin j := 1; letters := letters + s[1]; counts[1] := 1; for i := 2 to length(s) do if s[i] = letters[j] then inc(counts[j]) else begin inc(j); letters := letters + s[i]; counts[j] := 1; end; end; end;   procedure decode(var s: string; counts: array of integer; letters: string); var i, j: integer; begin s := ''; for i := 1 to length(letters) do for j := 1 to counts[i] do s := s + letters[i]; end;   var s: string; counts: array of integer; letters: string; i: integer; begin s := 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWW'; writeln(s); setlength(counts, length(s)); encode(s, counts, letters); for i := 1 to length(letters) - 1 do write(counts[i], ' * ', letters[i], ', '); writeln(counts[length(letters)], ' * ', letters[length(letters)]); decode(s, counts, letters); writeln(s); end.
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
#K
K
rot13: {a:+65 97+\:2 13#!26;_ci@[!256;a;:;|a]_ic x}   rot13 "Testing! 1 2 3" "Grfgvat! 1 2 3"
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Slate
Slate
define: #haystack -> ('Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' splitWith: $,). {'Washington'. 'Bush'} do: [| :needle | (haystack indexOf: needle) ifNil: [inform: word ; ' is not in the haystack'] ifNotNilDo: [| :firstIndex lastIndex | inform: word ; ' is in the haystack at index ' ; firstIndex printString. lastIndex: (haystack lastIndexOf: word). lastIndex isNotNil /\ (lastIndex > firstIndex) ifTrue: [inform: 'last occurrence of ' ; word ; ' is at index ' ; lastIndex]]].
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
#Forth
Forth
: vector create ( n -- ) 0 do , loop does> ( n -- ) swap cells + @ execute ; \ these are ( numerals -- numerals ) : ,I dup c@ C, ;  : ,V dup 1 + c@ C, ;  : ,X dup 2 + c@ C, ;   \ these are ( numerals -- ) :noname ,I ,X drop ;  :noname ,V ,I ,I ,I drop ;  :noname ,V ,I ,I drop ; :noname ,V ,I drop ;  :noname ,V drop ;  :noname ,I ,V drop ; :noname ,I ,I ,I drop ;  :noname ,I ,I drop ;  :noname ,I drop ; ' drop ( 0 : no output ) 10 vector ,digit   : roman-rec ( numerals n -- ) 10 /mod dup if >r over 2 + r> recurse else drop then ,digit ; : roman ( n -- c-addr u ) dup 0 4000 within 0= abort" EX LIMITO!" HERE SWAP s" IVXLCDM" drop swap roman-rec HERE OVER - ;   1999 roman type \ MCMXCIX 25 roman type \ XXV 944 roman type \ CMXLIV
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.
#Haskell
Haskell
  module Main where   ------------------------ -- DECODER FUNCTION -- ------------------------   decodeDigit :: Char -> Int decodeDigit 'I' = 1 decodeDigit 'V' = 5 decodeDigit 'X' = 10 decodeDigit 'L' = 50 decodeDigit 'C' = 100 decodeDigit 'D' = 500 decodeDigit 'M' = 1000 decodeDigit _ = error "invalid digit"   -- We process a Roman numeral from right to left, digit by digit, adding the value. -- If a digit is lower than the previous then its value is negative. -- The first digit is always positive.   decode roman = decodeRoman startValue startValue rest where (first:rest) = reverse roman startValue = decodeDigit first   decodeRoman :: Int -> Int -> [Char] -> Int decodeRoman lastSum _ [] = lastSum decodeRoman lastSum lastValue (digit:rest) = decodeRoman updatedSum digitValue rest where digitValue = decodeDigit digit updatedSum = (if digitValue < lastValue then (-) else (+)) lastSum digitValue   ------------------ -- TEST SUITE -- ------------------   main = do test "MCMXC" 1990 test "MMVIII" 2008 test "MDCLXVI" 1666   test roman expected = putStrLn (roman ++ " = " ++ (show (arabic)) ++ remark) where arabic = decode roman remark = " (" ++ (if arabic == expected then "PASS" else ("FAIL, expected " ++ (show expected))) ++ ")"  
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Scala
Scala
object Roots extends App { val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x   private def printRoots(f: Double => Double, lowerBound: Double, upperBound: Double, step: Double): Unit = { val y = f(lowerBound) var (ox, oy, os) = (lowerBound, y, math.signum(y))   for (x <- lowerBound to upperBound by step) { val y = f(x) val s = math.signum(y) if (s == 0) println(x) else if (s != os) println(s"~${x - (x - ox) * (y / (y - oy))}")   ox = x oy = y os = s } }   printRoots(poly, -1.0, 4, 0.002)   }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Python
Python
from random import choice   rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} previous = ['rock', 'paper', 'scissors']   while True: human = input('\nchoose your weapon: ') computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous"   if human in ('quit', 'exit'): break   elif human in rules: previous.append(human) print('the computer played', computer, end='; ')   if rules[computer] == human: # if what beats the computer's choice is the human's choice... print('yay you win!') elif rules[human] == computer: # if what beats the human's choice is the computer's choice... print('the computer beat you... :(') else: print("it's a tie!")   else: print("that's not a valid choice")
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.
#Perl
Perl
sub encode { shift =~ s/(.)\1*/length($&).$1/grse; }   sub decode { shift =~ s/(\d+)(.)/$2 x $1/grse; }
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
#Kotlin
Kotlin
import java.io.*   fun String.rot13() = map { when { it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x } it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x } else -> it } }.toCharArray()   fun InputStreamReader.println() = try { BufferedReader(this).forEachLine { println(it.rot13()) } } catch (e: IOException) { e.printStackTrace() }   fun main(args: Array<String>) { if (args.any()) args.forEach { FileReader(it).println() } else InputStreamReader(System.`in`).println() }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Smalltalk
Smalltalk
| haystack | haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,. { 'Washington' . 'Bush' } do: [:word | |t|   ((t := haystack indexOf: word) = 0) ifTrue: [ ('%1 is not in the haystack' % { word }) displayNl ] ifFalse: [ |l| ('%1 is at index %2' % { word . t }) displayNl. l := ( (haystack size) - (haystack reverse indexOf: word) + 1 ). ( t = l ) ifFalse: [ ('last occurence of %1 is at index %2' % { word . l }) displayNl ] ] ].
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
#Fortran
Fortran
program roman_numerals   implicit none   write (*, '(a)') roman (2009) write (*, '(a)') roman (1666) write (*, '(a)') roman (3888)   contains   function roman (n) result (r)   implicit none integer, intent (in) :: n integer, parameter :: d_max = 13 integer :: d integer :: m integer :: m_div character (32) :: r integer, dimension (d_max), parameter :: d_dec = & & (/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1/) character (32), dimension (d_max), parameter :: d_rom = & & (/'M ', 'CM', 'D ', 'CD', 'C ', 'XC', 'L ', 'XL', 'X ', 'IX', 'V ', 'IV', 'I '/)   r = '' m = n do d = 1, d_max m_div = m / d_dec (d) r = trim (r) // repeat (trim (d_rom (d)), m_div) m = m - d_dec (d) * m_div end do   end function roman   end program roman_numerals
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.
#Icon_and_Unicon
Icon and Unicon
link numbers   procedure main() every R := "MCMXC"|"MDCLXVI"|"MMVIII" do write(R, " = ",unroman(R)) end
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Sidef
Sidef
func f(x) { x*x*x - 3*x*x + 2*x }   var step = 0.001 var start = -1 var stop = 3   for x in range(start+step, stop, step) { static sign = false given (var value = f(x)) { when (0) { say "Root found at #{x}" } case (sign && ((value > 0) != sign)) { say "Root found near #{x}" } } sign = value>0 }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#R
R
play <- function() { bias <- c(r = 1, p = 1, s = 1) repeat { playerChoice <- readline(prompt = "Rock (r), Paper (p), Scissors (s), or Quit (q)? ") if(playerChoice == "q") break rps <- c(Rock = "r", Paper = "p", Scissors = "s") if(!playerChoice %in% rps) next compChoice <- sample(rps, 1, prob = bias / sum(bias)) cat("I choose", names(compChoice), "\n", c("We draw!", "I win!", "I lose!")[1 + (which(compChoice == rps) - which(playerChoice == rps)) %% 3], "\n") bias <- bias + (playerChoice == c("s", "r", "p")) } } play()
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.
#Phix
Phix
with javascript_semantics function encode(string s) sequence r = {} if length(s) then integer ch = s[1], count = 1 for i=2 to length(s) do if s[i]!=ch then r &= {count,ch} ch = s[i] count = 1 else count += 1 end if end for r &= {count,ch} end if return r end function function decode(sequence s) string r = "" for i=1 to length(s) by 2 do r &= repeat(s[i+1],s[i]) end for return r end function sequence s = encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") ?s ?decode(s)
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ksh
Ksh
  #!/bin/ksh   # rot-13 function   # # Variables: # integer ROT_NUM=13 # Generalize to any ROT   string1="A2p" # Default "test" string=${1:-${string1}} # Allow command line input   typeset -a lcalph=( a b c d e f g h i j k l m n o p q r s t u v w x y z ) typeset -a ucalph=( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z )   # # Functions: # # # Function _rotN(char) - return the "rotated" N letter to char # Needs: $ROT_NUM defined # function _rotN { typeset _char ; _char="$1" typeset _casechk _alpha _oldIFS _buff _indx   [[ ${_char} != @(\w) || ${_char} == @(\d) ]] && echo "${_char}" && return # Non-alpha   typeset -l _casechk="${_char}" [[ ${_casechk} == "${_char}" ]] && nameref _aplha=lcalph || nameref _aplha=ucalph   _oldIFS="$IFS" ; IFS='' ; _buff="${_aplha[*]}" ; IFS="${oldIFS}" _indx=${_buff%${_char}*} echo ${_aplha[$(( (${#_indx}+ROT_NUM) % (ROT_NUM * 2) ))]} typeset +n _aplha return }   ###### # main # ######   for ((i=0; i<${#string}; i++)); do buff+=$(_rotN "${string:${i}:1}") done   print "${string}" print "${buff}"
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Standard_ML
Standard ML
fun find_index (pred, lst) = let fun loop (n, []) = NONE | loop (n, x::xs) = if pred x then SOME n else loop (n+1, xs) in loop (0, lst) end;   val haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];   app (fn needle => case find_index (fn x => x = needle, haystack) of SOME i => print (Int.toString i ^ " " ^ needle ^ "\n") | NONE => print (needle ^ " is not in haystack\n")) ["Washington", "Bush"];
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Swift
Swift
let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] for needle in ["Washington","Bush"] { if let index = haystack.indexOf(needle) { print("\(index) \(needle)") } else { print("\(needle) is not in haystack") } }