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/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
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. TOROMAN. DATA DIVISION. working-storage section. 01 ws-number pic 9(4) value 0. 01 ws-save-number pic 9(4). 01 ws-tbl-def. 03 filler pic x(7) value '1000M '. 03 filler pic x(7) value '0900CM '. 03 filler pic x(7) value '0500D '. 03 filler pic x(7) value '0400CD '. 03 filler pic x(7) value '0100C '. 03 filler pic x(7) value '0090XC '. 03 filler pic x(7) value '0050L '. 03 filler pic x(7) value '0040XL '. 03 filler pic x(7) value '0010X '. 03 filler pic x(7) value '0009IX '. 03 filler pic x(7) value '0005V '. 03 filler pic x(7) value '0004IV '. 03 filler pic x(7) value '0001I '. 01 filler redefines ws-tbl-def. 03 filler occurs 13 times indexed by rx. 05 ws-tbl-divisor pic 9(4). 05 ws-tbl-roman-ch pic x(1) occurs 3 times indexed by cx. 01 ocx pic 99. 01 ws-roman. 03 ws-roman-ch pic x(1) occurs 16 times. PROCEDURE DIVISION. accept ws-number perform until ws-number = 0 move ws-number to ws-save-number if ws-number > 0 and ws-number < 4000 initialize ws-roman move 0 to ocx perform varying rx from 1 by +1 until ws-number = 0 perform until ws-number < ws-tbl-divisor (rx) perform varying cx from 1 by +1 until ws-tbl-roman-ch (rx, cx) = spaces compute ocx = ocx + 1 move ws-tbl-roman-ch (rx, cx) to ws-roman-ch (ocx) end-perform compute ws-number = ws-number - ws-tbl-divisor (rx) end-perform end-perform display 'inp=' ws-save-number ' roman=' ws-roman else display 'inp=' ws-save-number ' invalid' end-if accept ws-number end-perform .  
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.
#D
D
import std.regex, std.algorithm;   int toArabic(in string s) /*pure nothrow*/ { static immutable weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; static immutable symbols = ["M","CM","D","CD","C","XC", "L","XL","X","IX","V","IV","I"];   int arabic; foreach (m; s.matchAll("CM|CD|XC|XL|IX|IV|[MDCLXVI]".regex)) arabic += weights[symbols.countUntil(m.hit)]; return arabic; }   void main() { assert("MCMXC".toArabic == 1990); assert("MMVIII".toArabic == 2008); assert("MDCLXVI".toArabic == 1666); }
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
#Lua
Lua
-- Function to have roots found function f (x) return x^3 - 3*x^2 + 2*x end   -- Find roots of f within x=[start, stop] or approximations thereof function root (f, start, stop, step) local roots, x, sign, foundExact, value = {}, start, f(start) > 0 while x <= stop do value = f(x) if value == 0 then table.insert(roots, {val = x, err = 0}) foundExact = true end if value > 0 ~= sign then if foundExact then foundExact = false else table.insert(roots, {val = x, err = step}) end end sign = value > 0 x = x + step end return roots end   -- Main procedure print("Root (to 12DP)\tMax. Error\n") for _, r in pairs(root(f, -1, 3, 10^-6)) do print(string.format("%0.12f", r.val), r.err) end
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.
#Java
Java
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random;   public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, /*LIZARD, SPOCK*/; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK/*, SPOCK*/); ROCK.losesToList = Arrays.asList(PAPER/*, SPOCK*/); PAPER.losesToList = Arrays.asList(SCISSORS/*, LIZARD*/); /* SPOCK.losesToList = Arrays.asList(PAPER, LIZARD); LIZARD.losesToList = Arrays.asList(SCISSORS, ROCK); */ } } //EnumMap uses a simple array under the hood public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }};   private int totalThrows = Item.values().length;   public static void main(String[] args){ RPS rps = new RPS(); rps.run(); }   public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } }   private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
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.
#jq
jq
def runs: reduce .[] as $item ( []; if . == [] then [ [ $item, 1] ] else .[length-1] as $last | if $last[0] == $item then .[length-1] = [$item, $last[1] + 1] else . + [[$item, 1]] end end ) ;
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Tcl
Tcl
package require Tcl 8.5 namespace import tcl::mathfunc::*   set pi 3.14159265 for {set n 2} {$n <= 10} {incr n} { set angle 0.0 set row $n: for {set i 1} {$i <= $n} {incr i} { lappend row [format %5.4f%+5.4fi [cos $angle] [sin $angle]] set angle [expr {$angle + 2*$pi/$n}] } puts $row }
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#TI-89_BASIC
TI-89 BASIC
cZeros(x^n - 1, x)
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle non-real roots, but it need not check that a ≠ 0 {\displaystyle a\neq 0} . The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1 {\displaystyle a=1} , b = − 10 5 {\displaystyle b=-10^{5}} , and c = 1 {\displaystyle c=1} . (For double-precision floats, set b = − 10 9 {\displaystyle b=-10^{9}} .) Consider the following implementation in Ada: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Quadratic_Equation is type Roots is array (1..2) of Float; function Solve (A, B, C : Float) return Roots is SD : constant Float := sqrt (B**2 - 4.0 * A * C); AA : constant Float := 2.0 * A; begin return ((- B + SD) / AA, (- B - SD) / AA); end Solve;   R : constant Roots := Solve (1.0, -10.0E5, 1.0); begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; Output: X1 = 1.00000E+06 X2 = 0.00000E+00 As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10 − 6 {\displaystyle 10^{-6}} . The naive method is numerically unstable. Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters q = a c / b {\displaystyle q={\sqrt {ac}}/b} and f = 1 / 2 + 1 − 4 q 2 / 2 {\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2} and the two roots of the quardratic are: − b a f {\displaystyle {\frac {-b}{a}}f} and − c b f {\displaystyle {\frac {-c}{bf}}} Task: do it better. This means that given a = 1 {\displaystyle a=1} , b = − 10 9 {\displaystyle b=-10^{9}} , and c = 1 {\displaystyle c=1} , both of the roots your program returns should be greater than 10 − 11 {\displaystyle 10^{-11}} . Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = − 10 6 {\displaystyle b=-10^{6}} . Either way, show what your program gives as the roots of the quadratic in question. See page 9 of "What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
#Stata
Stata
mata : polyroots((-2,0,1)) 1 2 +-----------------------------+ 1 | 1.41421356 -1.41421356 | +-----------------------------+   : polyroots((2,0,1)) 1 2 +-------------------------------+ 1 | -1.41421356i 1.41421356i | +-------------------------------+
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle non-real roots, but it need not check that a ≠ 0 {\displaystyle a\neq 0} . The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1 {\displaystyle a=1} , b = − 10 5 {\displaystyle b=-10^{5}} , and c = 1 {\displaystyle c=1} . (For double-precision floats, set b = − 10 9 {\displaystyle b=-10^{9}} .) Consider the following implementation in Ada: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Quadratic_Equation is type Roots is array (1..2) of Float; function Solve (A, B, C : Float) return Roots is SD : constant Float := sqrt (B**2 - 4.0 * A * C); AA : constant Float := 2.0 * A; begin return ((- B + SD) / AA, (- B - SD) / AA); end Solve;   R : constant Roots := Solve (1.0, -10.0E5, 1.0); begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; Output: X1 = 1.00000E+06 X2 = 0.00000E+00 As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10 − 6 {\displaystyle 10^{-6}} . The naive method is numerically unstable. Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters q = a c / b {\displaystyle q={\sqrt {ac}}/b} and f = 1 / 2 + 1 − 4 q 2 / 2 {\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2} and the two roots of the quardratic are: − b a f {\displaystyle {\frac {-b}{a}}f} and − c b f {\displaystyle {\frac {-c}{bf}}} Task: do it better. This means that given a = 1 {\displaystyle a=1} , b = − 10 9 {\displaystyle b=-10^{9}} , and c = 1 {\displaystyle c=1} , both of the roots your program returns should be greater than 10 − 11 {\displaystyle 10^{-11}} . Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = − 10 6 {\displaystyle b=-10^{6}} . Either way, show what your program gives as the roots of the quadratic in question. See page 9 of "What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
#Tcl
Tcl
package require math::complexnumbers namespace import math::complexnumbers::complex math::complexnumbers::tostring   proc quadratic {a b c} { set discrim [expr {$b**2 - 4*$a*$c}] set roots [list] if {$discrim < 0} { set term1 [expr {(-1.0*$b)/(2*$a)}] set term2 [expr {sqrt(abs($discrim))/(2*$a)}] lappend roots [tostring [complex $term1 $term2]] \ [tostring [complex $term1 [expr {-1 * $term2}]]] } elseif {$discrim == 0} { lappend roots [expr {-1.0*$b / (2*$a)}] } else { lappend roots [expr {(-1*$b + sqrt($discrim)) / (2 * $a)}] \ [expr {(-1*$b - sqrt($discrim)) / (2 * $a)}] } return $roots }   proc report_quad {a b c} { puts [format "%sx**2 + %sx + %s = 0" $a $b $c] foreach root [quadratic $a $b $c] { puts " x = $root" } }   # examples on this page report_quad 3 4 [expr {4/3.0}] ;# {-2/3} report_quad 3 2 -1 ;# {1/3, -1} report_quad 3 2 1 ;# {(-1/3 + sqrt(2/9)i), (-1/3 - sqrt(2/9)i)} report_quad 1 0 1 ;# {(0+i), (0-i)} report_quad 1 -1e6 1 ;# {1e6, 1e-6} # examples from http://en.wikipedia.org/wiki/Quadratic_equation report_quad -2 7 15 ;# {5, -3/2} report_quad 1 -2 1 ;# {1} report_quad 1 3 3 ;# {(-3 - sqrt(3)i)/2), (-3 + sqrt(3)i)/2)}
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
#Forth
Forth
: r13 ( c -- o ) dup 32 or \ tolower dup [char] a [char] z 1+ within if [char] m > if -13 else 13 then + else drop then ;
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Woma
Woma
(sieve(n = /0 -> int; limit = /0 -> int; is_prime = [/0] -> *)) * i<@>range(n*n, limit+1, n) is_prime = is_prime[$]i,False <*>is_prime   (primes_upto(limit = 4 -> int)) list(int) primes = [] -> list f = [False, False] -> list(bool) t = [True] -> list(bool) u = limit - 1 -> int tt = t * u -> list(bool) is_prime = flatten(f[^]tt) -> list(bool) limit_sqrt = limit ** 0.5 -> float iter1 = int(limit_sqrt + 1.5) -> int   n<@>range(iter1) is_prime[n]<?>is_prime = sieve(n, limit, is_prime)   i,prime<@>enumerate(is_prime) prime<?>primes = primes[^]i <*>primes
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
#PicoLisp
PicoLisp
(de lastIndex (Item Lst) (- (length Lst) (index Item (reverse Lst)) -1) )   (de findNeedle (Fun Sym Lst) (prinl Sym " " (or (Fun Sym Lst) "not found")) )   (let Lst '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo) (findNeedle index 'Washington Lst) (findNeedle index 'Bush Lst) (findNeedle lastIndex 'Bush Lst) )
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#Stata
Stata
copy "http://rosettacode.org/wiki/Category:Programming_Languages" lang.html, replace import delimited lang.html, delim("@") enc("utf-8") clear keep if ustrpos(v1,"/wiki/Category:") gen i = ustrpos(v1,"title=") gen j = ustrpos(v1,char(34),i+1) gen k = ustrpos(v1,char(34),j+1) gen s = usubstr(v1,j,k-j+1) keep if usubstr(s,2,9)=="Category:" gen lang=usubstr(s,11,ustrlen(s)-11) keep lang save lang, replace   copy "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" categ.html, replace import delimited categ.html, delim("@") enc("utf-8") clear keep if ustrpos(v1,"/wiki/Category:") & ustrpos(v1,"member") gen i = ustrpos(v1,"title=") gen j = ustrpos(v1,char(34),i+1) gen k = ustrpos(v1,char(34),j+1) gen s = usubstr(v1,j,k-j+1) keep if usubstr(s,2,9)=="Category:" gen lang=usubstr(s,11,ustrlen(s)-11) drop i j k s gen i = ustrrpos(v1,"(") gen j = ustrrpos(v1,")") gen s = usubstr(v1,i,j-i+1) gen k = ustrpos(s," ") gen t = usubstr(s,2,k-1) destring t, gen(count) drop v1 i j k s t merge 1:1 lang using lang, keep(2 3) nogen replace count=0 if missing(count) gsort -count lang gen rank=1 replace rank=rank[_n-1]+(count[_n]!=count[_n-1]) in 2/l save tasks, replace
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
#CoffeeScript
CoffeeScript
  decimal_to_roman = (n) -> # This should work for any positive integer, although it # gets a bit preposterous for large numbers. if n >= 4000 thousands = decimal_to_roman n / 1000 ones = decimal_to_roman n % 1000 return "M(#{thousands})#{ones}"   s = '' translate_each = (min, roman) -> while n >= min n -= min s += roman translate_each 1000, "M" translate_each 900, "CM" translate_each 500, "D" translate_each 400, "CD" translate_each 100, "C" translate_each 90, "XC" translate_each 50, "L" translate_each 40, "XL" translate_each 10, "X" translate_each 9, "IX" translate_each 5, "V" translate_each 4, "IV" translate_each 1, "I" s   ################### tests = IV: 4 XLII: 42 MCMXC: 1990 MMVIII: 2008 MDCLXVI: 1666 'M(IV)': 4000 'M(VI)IX': 6009 'M(M(CXXIII)CDLVI)DCCLXXXIX': 123456789 'M(MMMV)I': 3005001   for expected, decimal of tests roman = decimal_to_roman(decimal) if roman == expected console.log "#{decimal} = #{roman}" else console.log "error for #{decimal}: #{roman} is wrong"  
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.
#Delphi.2FPascal
Delphi/Pascal
program RomanNumeralsDecode;   {$APPTYPE CONSOLE}   function RomanToInteger(const aRoman: string): Integer; function DecodeRomanDigit(aChar: Char): Integer; begin case aChar of 'M', 'm': Result := 1000; 'D', 'd': Result := 500; 'C', 'c': Result := 100; 'L', 'l': Result := 50; 'X', 'x': Result := 10; 'V', 'v': Result := 5; 'I', 'i': Result := 1 else Result := 0; end; end;   var i: Integer; lCurrVal: Integer; lLastVal: Integer; begin Result := 0;   lLastVal := 0; for i := Length(aRoman) downto 1 do begin lCurrVal := DecodeRomanDigit(aRoman[i]); if lCurrVal < lLastVal then Result := Result - lCurrVal else Result := Result + lCurrVal; lLastVal := lCurrVal; end; end;   begin Writeln(RomanToInteger('MCMXC')); // 1990 Writeln(RomanToInteger('MMVIII')); // 2008 Writeln(RomanToInteger('MDCLXVI')); // 1666 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
#Maple
Maple
f := x^3-3*x^2+2*x; roots(f,x);
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Solve[x^3-3*x^2+2*x==0,x]
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.
#JavaScript
JavaScript
  const logic = { rock: { w: 'scissor', l: 'paper'}, paper: {w:'rock', l:'scissor'}, scissor: {w:'paper', l:'rock'}, }   class Player { constructor(name){ this.name = name; } setChoice(choice){ this.choice = choice; } challengeOther(PlayerTwo){ return logic[this.choice].w === PlayerTwo.choice; } }   const p1 = new Player('Chris'); const p2 = new Player('John');   p1.setChoice('rock'); p2.setChoice('scissor');   p1.challengeOther(p2); //true (Win)  
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.
#Julia
Julia
using IterTools   encode(str::String) = collect((length(g), first(g)) for g in groupby(first, str)) decode(cod::Vector) = join(repeat("$l", n) for (n, l) in cod)   for original in ["aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa", "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"] encoded = encode(original) decoded = decode(encoded) println("Original: $original\n -> encoded: $encoded\n -> decoded: $decoded") end
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Ursala
Ursala
#import std #import nat #import flo   roots = ~&htxPC+ c..mul:-0^*DlSiiDlStK9\iota c..mul@iiX+ c..cpow/-1.+ div/1.+ float   #cast %jLL   tests = roots* <1,2,3,4,5,6>
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#VBA
VBA
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Wren
Wren
import "/complex" for Complex import "/fmt" for Fmt   var roots = Fn.new { |n| var r = List.filled(n, null) for (i in 0...n) r[i] = Complex.fromPolar(1, 2 * Num.pi * i / n) return r }   for (n in 2..5) { Fmt.print("$d roots of 1:", n) for (r in roots.call(n)) Fmt.print(" $17.14z", r) }
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle non-real roots, but it need not check that a ≠ 0 {\displaystyle a\neq 0} . The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1 {\displaystyle a=1} , b = − 10 5 {\displaystyle b=-10^{5}} , and c = 1 {\displaystyle c=1} . (For double-precision floats, set b = − 10 9 {\displaystyle b=-10^{9}} .) Consider the following implementation in Ada: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Quadratic_Equation is type Roots is array (1..2) of Float; function Solve (A, B, C : Float) return Roots is SD : constant Float := sqrt (B**2 - 4.0 * A * C); AA : constant Float := 2.0 * A; begin return ((- B + SD) / AA, (- B - SD) / AA); end Solve;   R : constant Roots := Solve (1.0, -10.0E5, 1.0); begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; Output: X1 = 1.00000E+06 X2 = 0.00000E+00 As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10 − 6 {\displaystyle 10^{-6}} . The naive method is numerically unstable. Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters q = a c / b {\displaystyle q={\sqrt {ac}}/b} and f = 1 / 2 + 1 − 4 q 2 / 2 {\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2} and the two roots of the quardratic are: − b a f {\displaystyle {\frac {-b}{a}}f} and − c b f {\displaystyle {\frac {-c}{bf}}} Task: do it better. This means that given a = 1 {\displaystyle a=1} , b = − 10 9 {\displaystyle b=-10^{9}} , and c = 1 {\displaystyle c=1} , both of the roots your program returns should be greater than 10 − 11 {\displaystyle 10^{-11}} . Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = − 10 6 {\displaystyle b=-10^{6}} . Either way, show what your program gives as the roots of the quadratic in question. See page 9 of "What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
#TI-89_BASIC
TI-89 BASIC
solve(x^2-1E9x+1.0)
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle non-real roots, but it need not check that a ≠ 0 {\displaystyle a\neq 0} . The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1 {\displaystyle a=1} , b = − 10 5 {\displaystyle b=-10^{5}} , and c = 1 {\displaystyle c=1} . (For double-precision floats, set b = − 10 9 {\displaystyle b=-10^{9}} .) Consider the following implementation in Ada: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Quadratic_Equation is type Roots is array (1..2) of Float; function Solve (A, B, C : Float) return Roots is SD : constant Float := sqrt (B**2 - 4.0 * A * C); AA : constant Float := 2.0 * A; begin return ((- B + SD) / AA, (- B - SD) / AA); end Solve;   R : constant Roots := Solve (1.0, -10.0E5, 1.0); begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; Output: X1 = 1.00000E+06 X2 = 0.00000E+00 As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10 − 6 {\displaystyle 10^{-6}} . The naive method is numerically unstable. Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters q = a c / b {\displaystyle q={\sqrt {ac}}/b} and f = 1 / 2 + 1 − 4 q 2 / 2 {\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2} and the two roots of the quardratic are: − b a f {\displaystyle {\frac {-b}{a}}f} and − c b f {\displaystyle {\frac {-c}{bf}}} Task: do it better. This means that given a = 1 {\displaystyle a=1} , b = − 10 9 {\displaystyle b=-10^{9}} , and c = 1 {\displaystyle c=1} , both of the roots your program returns should be greater than 10 − 11 {\displaystyle 10^{-11}} . Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = − 10 6 {\displaystyle b=-10^{6}} . Either way, show what your program gives as the roots of the quadratic in question. See page 9 of "What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
#Wren
Wren
import "/complex" for Complex   var quadratic = Fn.new { |a, b, c| var d = b*b - 4*a*c if (d == 0) { // single root return [[-b/(2*a)], null] } if (d > 0) { // two real roots var sr = d.sqrt d = (b < 0) ? sr - b : -sr - b return [[d/(2*a), 2*c/d], null] } // two complex roots var den = 1 / (2*a) var t1 = Complex.new(-b*den, 0) var t2 = Complex.new(0, (-d).sqrt * den) return [[], [t1+t2, t1-t2]] }   var test = Fn.new { |a, b, c| System.write("coefficients: %(a), %(b), %(c) -> ") var roots = quadratic.call(a, b, c) var r = roots[0] if (r.count == 1) { System.print("one real root: %(r[0])") } else if (r.count == 2) { System.print("two real roots: %(r[0]) and %(r[1])") } else { var i = roots[1] System.print("two complex roots: %(i[0]) and %(i[1])") } }   var coeffs = [ [1, -2, 1], [1, 0, 1], [1, -10, 1], [1, -1000, 1], [1, -1e9, 1] ]   for (c in coeffs) test.call(c[0], c[1], c[2])
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
#Fortran
Fortran
program test_rot_13   implicit none integer, parameter :: len_max = 256 integer, parameter :: unit = 10 character (len_max) :: file character (len_max) :: fmt character (len_max) :: line integer :: arg integer :: arg_max integer :: iostat   write (fmt, '(a, i0, a)') '(a', len_max, ')' arg_max = iargc () if (arg_max > 0) then ! Encode all files listed on the command line. do arg = 1, arg_max call getarg (arg, file) open (unit, file = file, iostat = iostat) if (iostat /= 0) cycle do read (unit, fmt = fmt, iostat = iostat) line if (iostat /= 0) exit write (*, '(a)') trim (rot_13 (line)) end do close (unit) end do else ! Encode standard input. do read (*, fmt = fmt, iostat = iostat) line if (iostat /= 0) exit write (*, '(a)') trim (rot_13 (line)) end do end if   contains   function rot_13 (input) result (output)   implicit none character (len_max), intent (in) :: input character (len_max) :: output integer :: i   output = input do i = 1, len_trim (output) select case (output (i : i)) case ('A' : 'M', 'a' : 'm') output (i : i) = char (ichar (output (i : i)) + 13) case ('N' : 'Z', 'n' : 'z') output (i : i) = char (ichar (output (i : i)) - 13) end select end do   end function rot_13   end program test_rot_13
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Wren
Wren
var sieveOfE = Fn.new { |n| if (n < 2) return [] var comp = List.filled(n-1, false) var p = 2 while (true) { var p2 = p * p if (p2 > n) break var i = p2 while (i <= n) { comp[i-2] = true i = i + p } while (true) { p = p + 1 if (!comp[p-2]) break } } var primes = [] for (i in 0..n-2) { if (!comp[i]) primes.add(i+2) } return primes }   System.print(sieveOfE.call(100))
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
#PL.2FI
PL/I
search: procedure () returns (fixed binary); declare haystack (0:9) character (200) varying static initial ('apple', 'banana', 'celery', 'dumpling', 'egg', 'flour', 'grape', 'pomegranate', 'raisin', 'sugar' ); declare needle character (200) varying; declare i fixed binary; declare missing_needle condition;   on condition(missing_needle) begin; put skip list ('your string ''' || needle || ''' does not exist in the haystack.'); end;   put ('Please type a string'); get edit (needle) (L); do i = lbound(haystack,1) to hbound(haystack,1); if needle = haystack(i) then return (i); end; signal condition(missing_needle); return (lbound(haystack,1)-1); end search;
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#Tcl
Tcl
package require Tcl 8.5 package require http   set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]   array set ignore { "Basic language learning" 1 "Encyclopedia" 1 "Implementations" 1 "Language Implementations" 1 "Language users" 1 "Maintenance/OmitCategoriesCreated" 1 "Programming Languages" 1 "Programming Tasks" 1 "RCTemplates" 1 "Solutions by Library" 1 "Solutions by Programming Language" 1 "Solutions by Programming Task" 1 "Unimplemented tasks by language" 1 "WikiStubs" 1 "Examples needing attention" 1 "Impl needed" 1 } # need substring filter proc filterLang {n} { return [expr {[string first "User" $n] > 0}] } # (sorry the 1 double quote in the regexp kills highlighting) foreach line [split [http::data $response] \n] { if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} { if {![info exists ignore($lang)] && ![filterLang $lang]} { lappend langs [list $num $lang] } } }   foreach entry [lsort -integer -index 0 -decreasing $langs] { lassign $entry num lang puts [format "%d. %d - %s" [incr i] $num $lang] }
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
#Common_Lisp
Common Lisp
(defun roman-numeral (n) (format nil "~@R" n))
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#EasyLang
EasyLang
rom_digs$[] = [ "M" "D" "C" "L" "X" "V" "I" ] rom_vals[] = [ 1000 500 100 50 10 5 1 ] # func rom2int rom_numb$ . val . val = 0 for dig$ in strchars rom_numb$ for i range len rom_digs$[] if rom_digs$[i] = dig$ v = rom_vals[i] . . val += v if old_v < v val -= 2 * old_v . old_v = v . . call rom2int "MCMXC" v print v call rom2int "MMVIII" v print v call rom2int "MDCLXVI" v print 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
#Maxima
Maxima
e: x^3 - 3*x^2 + 2*x$   /* Number of roots in a real interval, using Sturm sequences */ nroots(e, -10, 10); 3   solve(e, x); [x=1, x=2, x=0]   /* 'solve sets the system variable 'multiplicities */   solve(x^4 - 2*x^3 + 2*x - 1, x); [x=-1, x=1]   multiplicities; [1, 3]   /* Rational approximation of roots using Sturm sequences and bisection */   realroots(e); [x=1, x=2, x=0]   /* 'realroots also sets the system variable 'multiplicities */   multiplicities; [1, 1, 1]   /* Numerical root using Brent's method (here with another equation) */   find_root(sin(t) - 1/2, t, 0, %pi/2); 0.5235987755983   fpprec: 60$   bf_find_root(sin(t) - 1/2, t, 0, %pi/2); 5.23598775598298873077107230546583814032861566562517636829158b-1   /* Numerical root using Newton's method */   load(newton1)$ newton(e, x, 1.1, 1e-6); 1.000000017531147   /* For polynomials, Jenkins–Traub algorithm */   allroots(x^3 + x + 1); [x=1.161541399997252*%i+0.34116390191401, x=0.34116390191401-1.161541399997252*%i, x=-0.68232780382802]   bfallroots(x^3 + x + 1); [x=1.16154139999725193608791768724717407484314725802151429063617b0*%i + 3.41163901914009663684741869855524128445594290948999288901864b-1, x=3.41163901914009663684741869855524128445594290948999288901864b-1 - 1.16154139999725193608791768724717407484314725802151429063617b0*%i, x=-6.82327803828019327369483739711048256891188581897998577803729b-1]
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
#Nim
Nim
import math import strformat   func f(x: float): float = x ^ 3 - 3 * x ^ 2 + 2 * x   var step = 0.01 start = -1.0 stop = 3.0 sign = f(start) > 0 x = start   while x <= stop: var value = f(x)   if value == 0: echo fmt"Root found at {x:.5f}" elif (value > 0) != sign: echo fmt"Root found near {x:.5f}"   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.
#Julia
Julia
function rps() print("Welcome to Rock, paper, scissors! Go ahead and type your pick.\n r(ock), p(aper), or s(cissors)\n Enter 'q' to quit.\n>") comp_score = 0 user_score = 0 options = ["r","p","s"] new_pick() = options[rand(1:3)] i_win(m,y) = ((m == "r" && y == "s")|(m == "s" && y == "p")|(m == "p" && y == "r")) while true input = string(readline(STDIN)[1]) input == "q" && break !ismatch(r"^[rps]",input) && begin print("Invalid guess: Please enter 'r', 'p', or 's'\n"); continue end answer = new_pick() if input == answer print("\nTie!\nScore still: \nyou $user_score\nme $comp_score\n>") continue else i_win(answer,input) ? (comp_score += 1) : (user_score += 1) print(i_win(answer,input) ? "\nSorry you lose!\n" : "\nYou win!","Score: \nyou $user_score\nme $comp_score\n>") end end end
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#K
K
rle: {,/($-':i,#x),'x@i:&1,~=':x}
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#zkl
zkl
PI2:=(0.0).pi*2; foreach n,i in ([1..9],n){ c:=s:=0; if(not i) c = 1; else if(n==4*i) s = 1; else if(n==2*i) c = -1; else if(3*n==4*i) s = -1; else a,c,s:=PI2*i/n,a.cos(),a.sin();   if(c) print("%.2g".fmt(c)); print( (s==1 and "i") or (s==-1 and "-i" or (s and "%+.2gi" or"")).fmt(s)); print( (i==n-1) and "\n" or ", "); }
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle non-real roots, but it need not check that a ≠ 0 {\displaystyle a\neq 0} . The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1 {\displaystyle a=1} , b = − 10 5 {\displaystyle b=-10^{5}} , and c = 1 {\displaystyle c=1} . (For double-precision floats, set b = − 10 9 {\displaystyle b=-10^{9}} .) Consider the following implementation in Ada: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Quadratic_Equation is type Roots is array (1..2) of Float; function Solve (A, B, C : Float) return Roots is SD : constant Float := sqrt (B**2 - 4.0 * A * C); AA : constant Float := 2.0 * A; begin return ((- B + SD) / AA, (- B - SD) / AA); end Solve;   R : constant Roots := Solve (1.0, -10.0E5, 1.0); begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; Output: X1 = 1.00000E+06 X2 = 0.00000E+00 As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10 − 6 {\displaystyle 10^{-6}} . The naive method is numerically unstable. Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters q = a c / b {\displaystyle q={\sqrt {ac}}/b} and f = 1 / 2 + 1 − 4 q 2 / 2 {\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2} and the two roots of the quardratic are: − b a f {\displaystyle {\frac {-b}{a}}f} and − c b f {\displaystyle {\frac {-c}{bf}}} Task: do it better. This means that given a = 1 {\displaystyle a=1} , b = − 10 9 {\displaystyle b=-10^{9}} , and c = 1 {\displaystyle c=1} , both of the roots your program returns should be greater than 10 − 11 {\displaystyle 10^{-11}} . Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = − 10 6 {\displaystyle b=-10^{6}} . Either way, show what your program gives as the roots of the quadratic in question. See page 9 of "What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
#zkl
zkl
fcn quadratic(a,b,c){ b=b.toFloat(); println("Roots of a quadratic function %s, %s, %s".fmt(a,b,c)); d,a2:=(b*b - 4*a*c), a+a; if(d>0){ sd:=d.sqrt(); println(" the real roots are %s and %s".fmt((-b + sd)/a2,(-b - sd)/a2)); } else if(d==0) println(" the single root is ",-b/a2); else{ sd:=(-d).sqrt(); println(" the complex roots are %s and \U00B1;%si".fmt(-b/a2,sd/a2)); } }
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' uses in place encoding/decoding Sub rot13(ByRef s As String) If s = "" Then Exit Sub Dim code As Integer For i As Integer = 0 To Len(s) - 1 Select Case As Const s[i] Case 65 To 90 '' A to Z code = s[i] + 13 If code > 90 Then code -= 26 s[i] = code Case 97 To 122 '' a to z code = s[i] + 13 If code > 122 Then code -= 26 s[i] = code End Select Next End Sub   Dim s As String = "nowhere ABJURER" Print "Before encoding : "; s rot13(s) Print "After encoding  : "; s rot13(s) Print "After decoding  : "; s Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Size, Prime, I, Kill; char Flag; [Size:= IntIn(0); Flag:= Reserve(Size+1); for I:= 2 to Size do Flag(I):= true; for I:= 2 to Size do if Flag(I) then \found a prime [Prime:= I; IntOut(0, Prime); CrLf(0); Kill:= Prime + Prime; \first multiple to kill while Kill <= Size do [Flag(Kill):= false; \zero a non-prime Kill:= Kill + Prime; \next multiple ]; ]; ]
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
#Plain_English
Plain English
To run: Start up. Make an example haystack. Find "b" in the example haystack giving a count. Destroy the example haystack. Write "The index of ""b"" is " then the count on the console. Wait for the escape key. Shut down.   A needle is a string.   Some hay is some strings.   A bale is a thing with some hay.   A haystack is some bales.   To add some hay to a haystack: Allocate memory for a bale. Put the hay into the bale's hay. Append the bale to the haystack.   To make an example haystack: Add "a" to the example haystack. Add "a" to the example haystack. Add "b" to the example haystack. Add "c" to the example haystack. Add "d" to the example haystack.   \ As Plain English doesn't have exceptions, return -1 if the needle is not found. To find a needle in a haystack giving a count: Get a bale from the haystack. Loop. If the bale is nil, put -1 into the count; exit. If the bale's hay is the needle, exit. Put the bale's next into the bale. Bump the count. Repeat.
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT remotedata = REQUEST ("http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000") allmembers=allnames="" COMPILE LOOP d=remotedata IF (d.sw."<li>") THEN name=EXTRACT (d,":<<a<><%>>:"|,":<</a>>:") IF (name.eq."Language users") CYCLE IF (name.sw."Unimplemented tasks") CYCLE IF (name.sw."Programming") CYCLE IF (name.sw."Solutions") CYCLE IF (name.sw."Garbage") CYCLE IF (name.sw."Typing") CYCLE IF (name.sw."BASIC LANG") CYCLE IF (name.ew."USER") CYCLE IF (name.ew."tasks") CYCLE IF (name.ew."attention") CYCLE IF (name.ew."related") CYCLE IF (name.ct."*omit*") CYCLE IF (name.ct.":*Categor*:") CYCLE IF (name.ct.":WikiSTUBS:") CYCLE IF (name.ct.":Impl needed:") CYCLE IF (name.ct.":Implementations:") CYCLE IF (name.ct.":':") name = EXCHANGE (name,":'::") members = STRINGS (d,":><1<>>/><<> member:") IF (members!="") THEN allmembers=APPEND (allmembers,members) allnames =APPEND (allnames,name) ENDIF ENDIF ENDLOOP index = DIGIT_INDEX (allmembers) index = REVERSE (index) allmembers = INDEX_SORT (allmembers,index) allnames = INDEX_SORT (allnames, index) ERROR/STOP CREATE ("list",SEQ-E,-std-) time=time(),balt=nalt="" FILE "list" = time LOOP n, a=allnames,b=allmembers IF (b==balt) THEN nr=nalt ELSE nalt=nr=n ENDIF content=concat (nr,". ",a," --- ",b) FILE "list" = CONTENT balt=b ENDLOOP ENDCOMPILE
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
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # Encode the given number as a Roman numeral sub decimalToRoman(num: uint16, buf: [uint8]): (rslt: [uint8]) is # return the start of the buffer for easy printing rslt := buf;   # Add string to buffer sub Add(str: [uint8]) is while [str] != 0 loop [buf] := [str]; buf := @next buf; str := @next str; end loop; end sub;   # Table of Roman numerals record Roman is value: uint16; string: [uint8]; end record;   var numerals: Roman[] := { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} };   var curNum := &numerals as [Roman]; while num != 0 loop while num >= curNum.value loop Add(curNum.string); num := num - curNum.value; end loop; curNum := @next curNum; end loop;   [buf] := 0; # terminate the string end sub;   # Read numbers from the command line and print the corresponding Roman numerals ArgvInit(); var buffer: uint8[100]; loop var argmt := ArgvNext(); if argmt == (0 as [uint8]) then break; end if;   var dummy: [uint8]; var number: int32; (number, dummy) := AToI(argmt);   print(decimalToRoman(number as uint16, &buffer as [uint8])); print_nl(); end loop;
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.
#ECL
ECL
  MapChar(STRING1 c) := CASE(c,'M'=>1000,'D'=>500,'C'=>100,'L'=>50,'X'=>10,'V'=>5,'I'=>1,0);   RomanDecode(STRING s) := FUNCTION dsS := DATASET([{s}],{STRING Inp}); R := { INTEGER2 i; };   R Trans1(dsS le,INTEGER pos) := TRANSFORM SELF.i := MapChar(le.Inp[pos]) * IF ( MapChar(le.Inp[pos]) < MapChar(le.Inp[pos+1]), -1, 1 ); END;   RETURN SUM(NORMALIZE(dsS,LENGTH(TRIM(s)),Trans1(LEFT,COUNTER)),i); END;   RomanDecode('MCMLIV'); //1954 RomanDecode('MCMXC'); //1990 RomanDecode('MMVIII'); //2008 RomanDecode('MDCLXVI'); //1666 RomanDecode('MDLXVI'); //1566
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
#Objeck
Objeck
  bundle Default { class Roots { function : f(x : Float) ~ Float { return (x*x*x - 3.0*x*x + 2.0*x); }   function : Main(args : String[]) ~ Nil { step := 0.001; start := -1.0; stop := 3.0; value := f(start); sign := (value > 0);   if(0.0 = value) { start->PrintLine(); };   for(x := start + step; x <= stop; x += step;) { value := f(x);   if((value > 0) <> sign) { IO.Console->Instance()->Print("~")->PrintLine(x); } else if(0 = value) { IO.Console->Instance()->Print("~")->PrintLine(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.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   const val choices = "rpsq" val rand = Random()   var pWins = 0 // player wins var cWins = 0 // computer wins var draws = 0 // neither wins var games = 0 // games played val pFreqs = arrayOf(0, 0, 0) // player frequencies for each choice (rps)   fun printScore() = println("Wins: You $pWins, Computer $cWins, Neither $draws\n")   fun getComputerChoice(): Char { // make a completely random choice until 3 games have been played if (games < 3) return choices[rand.nextInt(3)] val num = rand.nextInt(games) return when { num < pFreqs[0] -> 'p' num < pFreqs[0] + pFreqs[1] -> 's' else -> 'r' } }   fun main(args: Array<String>) { println("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n") while (true) { printScore() var pChoice: Char while (true) { print("Your choice r/p/s/q : ") val input = readLine()!!.toLowerCase() if (input.length == 1) { pChoice = input[0] if (pChoice in choices) break } println("Invalid choice, try again") } if (pChoice == 'q') { println("OK, quitting") return } val cChoice = getComputerChoice() println("Computer's choice  : $cChoice") if (pChoice == 'r' && cChoice == 's') { println("Rock breaks scissors - You win!") pWins++ } else if (pChoice == 'p' && cChoice == 'r') { println("Paper covers rock - You win!") pWins++ } else if (pChoice == 's' && cChoice == 'p') { println("Scissors cut paper - You win!") pWins++ } else if (pChoice == 's' && cChoice == 'r') { println("Rock breaks scissors - Computer wins!") cWins++ } else if (pChoice == 'r' && cChoice == 'p') { println("Paper covers rock - Computer wins!") cWins++ } else if (pChoice == 'p' && cChoice == 's') { println("Scissors cut paper - Computer wins!") cWins++ } else { println("It's a draw!") draws++ } pFreqs[choices.indexOf(pChoice)]++ games++ println() } }
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.
#Kotlin
Kotlin
tailrec fun runLengthEncoding(text:String,prev:String=""):String { if (text.isEmpty()){ return prev } val initialChar = text.get(0) val count = text.takeWhile{ it==initialChar }.count() return runLengthEncoding(text.substring(count),prev + "$count$initialChar" ) }   fun main(args: Array<String>) { assert(runLengthEncoding("TTESSST") == "2T1E3S1T") assert(runLengthEncoding("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
#FunL
FunL
import io.{lines, stdin}   def rot13( s ) = buf = StringBuilder()   for c <- s if isalpha( c ) n = ((ord(c) and 0x1F) - 1 + 13)%26 + 1   buf.append( chr(n or (if isupper(c) then 64 else 96)) ) else buf.append( c )   buf.toString()   def rot13lines( ls ) = for l <- ls println( rot13(l) )   if _name_ == '-main-' if args.isEmpty() rot13lines( stdin() ) else for f <- args rot13lines( lines(f) )
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Yabasic
Yabasic
#!/usr/bin/yabasic   // --------------------------- // Prime Sieve Benchmark -- // "Shootout" Version -- // --------------------------- // usage: // yabasic sieve8k.yab 90000     SIZE = 8192 ONN = 1 : OFF = 0 dim flags(SIZE)   sub main()   cmd = peek("arguments") if cmd = 1 then iterations = val(peek$("argument")) if iterations = 0 then print "Argument wrong. Done 1000." : iterations = 1000 end if else print "1000 iterations." iterations = 1000 end if   for iter = 1 to iterations count = 0 for n= 1 to SIZE : flags(n) = ONN: next n for i = 2 to SIZE if flags(i) = ONN then let k = i + i if k < SIZE then for k = k to SIZE step i flags(k) = OFF next k end if count = count + 1 end if next i next iter print "Count: ", count // 1028 end sub   clear screen   print "Prime Sieve Benchmark\n"   main()   t = val(mid$(time$,10))   print "time: ", t, "\n" print peek("millisrunning")
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
#PowerBASIC
PowerBASIC
FUNCTION PBMAIN () AS LONG DIM haystack(54) AS STRING ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _ "bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", _ "bar", "bletch", "foo", "bar", "fum", "fred", "jim", _ "sheila", "barney", "flarp", "zxc", "spqr", ";wombat", "shme", _ "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", _ "bar", "zot", "blarg", "wibble", "toto", "titi", "tata", _ "tutu", "pippo", "pluto", "paperino", "aap", "noot", "mies", _ "oogle", "foogle", "boogle", "zork", "gork", "bork" DIM needle AS STRING, found AS LONG, lastFound AS LONG DO needle = INPUTBOX$("Word to search for? (Leave blank to exit)") IF needle <> "" THEN ' collate ucase -> case insensitive ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found IF found > 0 THEN lastFound = found MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1)) IF found < UBOUND(haystack) THEN DO ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found IF found > 0 THEN MSGBOX "Another occurence of """ & needle & """ at index " & _ TRIM$(STR$(found + lastFound - 1)) lastFound = found + lastFound ELSE MSGBOX "No more occurences of """ & needle & """ found" EXIT DO 'will exit inner DO, not outer END IF LOOP END IF ELSE MSGBOX "No occurences of """ & needle & """ found" END IF ELSE EXIT DO END IF LOOP END FUNCTION
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#UnixPipes
UnixPipes
curl 'http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000' | sed -nre 's/^<li.*title="Category:([^"(]+)".*\(([0-9]+) members\).*/\2 - \1/p' | sort -nr | awk '{printf "%2d. %s\n",NR,$0}'
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
#D
D
string toRoman(int n) pure nothrow in { assert(n < 5000); } body { static immutable weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; static immutable symbols = ["M","CM","D","CD","C","XC","L", "XL","X","IX","V","IV","I"];   string roman; foreach (i, w; weights) { while (n >= w) { roman ~= symbols[i]; n -= w; } if (n == 0) break; } return roman; } unittest { assert(toRoman(455) == "CDLV"); assert(toRoman(3456) == "MMMCDLVI"); assert(toRoman(2488) == "MMCDLXXXVIII"); }   void main() {}
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.
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make local numbers: ARRAY [STRING] do numbers := <<"MCMXC", "MMVIII", "MDCLXVI", -- 1990 2008 1666 "MMMCLIX", "MCMLXXVII", "MMX">> -- 3159 1977 2010 across numbers as n loop print (n.item + " in Roman numerals is " + roman_to_decimal (n.item).out + " in decimal Arabic numerals.") print ("%N") end end   feature -- Roman numerals   roman_to_decimal (a_str: STRING): INTEGER -- Decimal representation of Roman numeral `a_str' require is_roman (a_str) local l_pos: INTEGER cur: INTEGER -- Value of the digit read in the current iteration prev: INTEGER -- Value of the digit read in the previous iteration do from l_pos := 0 Result := 0 prev := 1 + max_digit_value until l_pos = a_str.count loop l_pos := l_pos + 1 cur := roman_digit_to_decimal (a_str.at (l_pos)) if cur <= prev then -- Add nonincreasing digit Result := Result + cur else -- Subtract previous digit from increasing digit Result := Result - prev + (cur - prev) end prev := cur end ensure Result >= 0 end   is_roman (a_string: STRING): BOOLEAN -- Is `a_string' a valid sequence of Roman digits? do Result := across a_string as c all is_roman_digit (c.item) end end   feature {NONE} -- Implementation   max_digit_value: INTEGER = 1000   is_roman_digit (a_char: CHARACTER): BOOLEAN -- Is `a_char' a valid Roman digit? local l_char: CHARACTER do l_char := a_char.as_upper inspect l_char when 'I', 'V', 'X', 'L', 'C', 'D', 'M' then Result := True else Result := False end end   roman_digit_to_decimal (a_char: CHARACTER): INTEGER -- Decimal representation of Roman digit `a_char' require is_roman_digit (a_char) local l_char: CHARACTER do l_char := a_char.as_upper inspect l_char when 'I' then Result := 1 when 'V' then Result := 5 when 'X' then Result := 10 when 'L' then Result := 50 when 'C' then Result := 100 when 'D' then Result := 500 when 'M' then Result := 1000 end ensure Result > 0 end   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
#OCaml
OCaml
let bracket u v = ((u > 0.0) && (v < 0.0)) || ((u < 0.0) && (v > 0.0));;   let xtol a b = (a = b);; (* or use |a-b| < epsilon *)   let rec regula_falsi a b fa fb f = if xtol a b then (a, fa) else let c = (fb*.a -. fa*.b) /. (fb -. fa) in let fc = f c in if fc = 0.0 then (c, fc) else if bracket fa fc then regula_falsi a c fa fc f else regula_falsi c b fc fb f;;   let search lo hi step f = let rec next x fx = if x > hi then [] else let y = x +. step in let fy = f y in if fx = 0.0 then (x,fx) :: next y fy else if bracket fx fy then (regula_falsi x y fx fy f) :: next y fy else next y fy in next lo (f lo);;   let showroot (x,fx) = Printf.printf "f(%.17f) = %.17f [%s]\n" x fx (if fx = 0.0 then "exact" else "approx") in let f x = ((x -. 3.0)*.x +. 2.0)*.x in List.iter showroot (search (-5.0) 5.0 0.1 f);;
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.
#Lasso
Lasso
session_start('user') session_addvar('user', 'historic_choices') session_addvar('user', 'win_record') session_addvar('user', 'plays') var(historic_choices)->isNotA(::map) ? var(historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0)) var(plays)->isNotA(::integer) ? var(plays = 0) var(win_record)->isNotA(::array) ? var(win_record = array)   define br => '<br>' define winner(c::string,p::string) => { if(#c == $superior->find(#p)) => { $win_record->insert('lasso') return 'Lasso' else(#p == $superior->find(#c)) $win_record->insert('user') return 'User' else $win_record->insert('tie') return 'Nobody' } }   var( choice = web_request->param('choice')->asString, lookup = array('rock', 'paper', 'scissors'), computer_choice = $lookup->get(math_random(3,1)), superior = map('rock'='paper', 'paper'='scissors', 'scissors'='rock'), controls = '<a href=?choice=rock>Rock</a> <a href=?choice=paper>Paper</a> <a href=?choice=scissors>Scissors</a> <a href=?choice=quit>Quit</a><br/>' ) if($choice == 'quit') => {^ 'See ya. <a href=?>Start over</a>' session_end('user') $historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0) $plays = 0 $win_record = array   else(array('rock','paper','scissors') >> $choice) $controls   if($plays != 0) => { local('possibilities') = array with i in $lookup do => { loop($historic_choices->find(#i)) => { #possibilities->insert(#i) } }   $computer_choice = $superior->find(#possibilities->get(math_random($plays,1))) }   'User chose ' + $choice + br 'Lasso chose ' + $computer_choice + br winner($computer_choice->asString, $choice) + ' wins!'   $historic_choices->find($choice) = $historic_choices->find($choice)+1 $plays += 1   else($choice->size == 0) $controls   else 'Invalid Choice.'+ br + $controls ^} if($win_record->size) => {^ br br 'Win record: '+br 'Lasso: '+($win_record->find('lasso')->size)+br 'User: '+($win_record->find('user')->size)+br 'Tie: '+($win_record->find('tie')->size)+br ^}
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.
#Lasso
Lasso
define rle(str::string)::string => { local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string) while(#orig->size) => { if(not #newi->size) => { #newi->insert(1) #newc->insert(#orig->first) #orig->remove(1) else if(#orig->first == #newc->last) => { #newi->get(#newi->size) += 1 else #newi->insert(1) #newc->insert(#orig->first) } #orig->remove(1) } } loop(#newi->size) => { #compiled->append(#newi->get(loop_count)+#newc->get(loop_count)) } return #compiled } define rlde(str::string)::string => { local(o = string) while(#str->size) => { loop(#str->size) => { if(#str->isualphabetic(loop_count)) => { if(loop_count == 1) => { #o->append(#str->get(loop_count)) #str->removeLeading(#str->get(loop_count)) loop_abort } local(num = integer(#str->substring(1,loop_count))) #o->append(#str->get(loop_count)*#num) #str->removeLeading(#num+#str->get(loop_count)) loop_abort } } } return #o } //Tests: rle('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW') rle('dsfkjhhkdsjfhdskhshdjjfhhdlsllw')   rlde('12W1B12W3B24W1B14W') rlde('1d1s1f1k1j2h1k1d1s1j1f1h1d1s1k1h1s1h1d2j1f2h1d1l1s2l1w')
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
#GAP
GAP
rot13 := function(s) local upper, lower, c, n, t; upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; lower := "abcdefghijklmnopqrstuvwxyz"; t := [ ]; for c in s do n := Position(upper, c); if n <> fail then Add(t, upper[((n+12) mod 26) + 1]); else n := Position(lower, c); if n <> fail then Add(t, lower[((n+12) mod 26) + 1]); else Add(t, c); fi; fi; od; return t; end;   a := "England expects that every man will do his duty"; # "England expects that every man will do his duty" b := rot13(a); # "Ratynaq rkcrpgf gung rirel zna jvyy qb uvf qhgl" c := rot13(b); # "England expects that every man will do his duty"
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   pub fn main() !void { try sieve(1000); }   // using a comptime limit ensures that there's no need for dynamic memory. fn sieve(comptime limit: usize) !void { var prime = [_]bool{true} ** limit; prime[0] = false; prime[1] = false; var i: usize = 2; while (i*i < limit) : (i += 1) { if (prime[i]) { var j = i*i; while (j < limit) : (j += i) prime[j] = false; } } var c: i32 = 0; for (prime) |yes, p| if (yes) { c += 1; try stdout.print("{:5}", .{p}); if (@rem(c, 10) == 0) try stdout.print("\n", .{}); }; try stdout.print("\n", .{}); }  
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
#PowerShell
PowerShell
  function index($haystack,$needle) { $index = $haystack.IndexOf($needle) if($index -eq -1) { Write-Warning "$needle is absent" } else { $index }   } $haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house") index $haystack "house" index $haystack "paragraph"  
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#VBScript
VBScript
''''''''''''''''''''''''''''''''''''''''''''' ' Rosetta Code/Rank Languages by Popularity ' ' VBScript Implementation ' '...........................................' 'API Links (From C Code) URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue" URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="   'Get Contents of the API from the Web... Function ScrapeGoat(link) On Error Resume Next ScrapeGoat = "" Err.Clear Set objHttp = CreateObject("Msxml2.ServerXMLHTTP") objHttp.Open "GET", link, False objHttp.Send If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText Set objHttp = Nothing End Function   'HACK: Setup HTML for help of my partner/competitor that is better than me, JavaScript... Set HTML = CreateObject("HtmlFile") Set HTMLWindow = HTML.ParentWindow     '''''''''''''''''''' ' Main code begins ' '..................' On Error Resume Next   isComplete = 0 ' 1 -> Complete Already cntLoop = 0 ' Counts Number of Loops Done Set outputData = CreateObject("Scripting.Dictionary")   Do 'Scrape Data From API If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont) If Len(strData) = 0 Then Set HTML = Nothing WScript.StdErr.WriteLine "Processing of data stopped because API query failed." WScript.Quit(1) End If   'Parse JSON HACK HTMLWindow.ExecScript "var json = " & strData, "JavaScript" Set ObjJS = HTMLWindow.json   Err.Clear 'Test if Query is Complete Already batchCompl = ObjJS.BatchComplete If Err.Number = 438 Then 'Query not yet complete. Get gcmContinue instead. gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue Else isComplete = 1 'Yes! End If   'HACK #2: Put all language page ids into a JS array to be accessed by VBScript HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _ "var nums=langs.length;", "JavaScript" Set arrLangs = HTMLWindow.langs arrLength = HTMLWindow.nums   For i = 0 to arrLength - 1 BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]" EachStr = Eval(BuffStr & ".title")   Err.Clear CntLang = Eval(BuffStr & ".CategoryInfo.Pages") If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang End If Next   cntLoop = cntLoop + 1 Loop While isComplete = 0 'The outputData now contains the data we need. We should now sort and print it! 'Make a 2D array with copy of outputData arrRelease = Array() ReDim arrRelease(UBound(outputData.Keys), 1)   outKeys = outputData.Keys outItem = outputData.Items For i = 0 To UBound(outKeys) arrRelease(i, 0) = outKeys(i) arrRelease(i, 1) = outItem(i) Next   'Bubble Sort (Greatest to Least Number of Examples) For i = 0 to UBound(arrRelease, 1) For j = 0 to UBound(arrRelease, 1) - 1 If arrRelease(j, 1) < arrRelease(j + 1, 1) Then temp1 = arrRelease(j + 1, 0) temp2 = arrRelease(j + 1, 1) arrRelease(j + 1, 0) = arrRelease(j, 0) arrRelease(j + 1, 1) = arrRelease(j, 1) arrRelease(j, 0) = temp1 arrRelease(j, 1) = temp2 End If Next Next   'Save contents to file instead to support Unicode Names Set objFSO = CreateObject("Scripting.FileSystemObject") Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)   txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages." txtOut.WriteLine "" For i = 0 to UBound(arrRelease) txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0) Next   'Successfully Done :) Set HTML = Nothing Set objFSO = Nothing WScript.Quit(0)
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
#Delphi
Delphi
program RomanNumeralsEncode;   {$APPTYPE CONSOLE}   function IntegerToRoman(aValue: Integer): string; var i: Integer; const WEIGHTS: array[0..12] of Integer = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); SYMBOLS: array[0..12] of string = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'); begin for i := Low(WEIGHTS) to High(WEIGHTS) do begin while aValue >= WEIGHTS[i] do begin Result := Result + SYMBOLS[i]; aValue := aValue - WEIGHTS[i]; end; if aValue = 0 then Break; end; end;   begin Writeln(IntegerToRoman(1990)); // MCMXC Writeln(IntegerToRoman(2008)); // MMVIII Writeln(IntegerToRoman(1666)); // MDCLXVI 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.
#Elena
Elena
import extensions; import system'collections; import system'routines;   static RomanDictionary = Dictionary.new() .setAt("I".toChar(), 1) .setAt("V".toChar(), 5) .setAt("X".toChar(), 10) .setAt("L".toChar(), 50) .setAt("C".toChar(), 100) .setAt("D".toChar(), 500) .setAt("M".toChar(), 1000);   extension op : String { toRomanInt() { var minus := 0; var s := self.upperCase(); var total := 0;   for(int i := 0, i < s.Length, i += 1) { var thisNumeral := RomanDictionary[s[i]] - minus; if (i >= s.Length - 1 || thisNumeral + minus >= RomanDictionary[s[i + 1]]) { total += thisNumeral; minus := 0 } else { minus := thisNumeral } };   ^ total } }   public program() { console.printLine("MCMXC: ", "MCMXC".toRomanInt()); console.printLine("MMVIII: ", "MMVIII".toRomanInt()); console.printLine("MDCLXVI:", "MDCLXVI".toRomanInt()) }
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
#Octave
Octave
a = [ 1, -3, 2, 0 ]; r = roots(a); % let's print it for i = 1:3 n = polyval(a, r(i)); printf("x%d = %f (%f", i, r(i), n); if (n != 0.0) printf(" not"); endif printf(" exact)\n"); endfor
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.
#Liberty_BASIC
Liberty BASIC
  dim rps( 2), g$( 3)   g$( 0) ="rock": g$( 1) ="paper": g$( 2) ="scissors" global total   total =0: draw =0: pwin =0: cwin =0   rps( 0) =1: rps( 1) =1: rps( 2) =1 ' at first computer will play all three with equal probability   c =int( 3 *rnd( 1)) ' first time, computer response is random   ' In the following code we set three integer %ages for the <human>'s biassed throws. ' set up the <human> player's key frequencies as %ages. ' Done like this it's easy to mimic the <human> input of q$ ' It allows only integer %age frequency- not an important thing. rockP =45 ' <<<<<<<<< Set here the <human>'s %age of 'rock' choices. for i =1 to rockP: qF$ =qF$ +"R": next i   paprP =24 ' <<<<<<<<< Set here the %age of 'paper' choices. for i =1 to paprP: qF$ =qF$ +"P": next i   scisP =100 -rockP -paprP ' <<<<<<<<< %age 'scissors' calculated to make 100% for i =1 to scisP: qF$ =qF$ +"S": next i 'print qF$   do 'do: input q$:loop until instr( "RPSrpsQq", q$) ' for actual human input... possibly biassed. <<<<<<<<<<<<< REM one or the other line... q$ =mid$( qF$, int( 100 *rnd( 1)), 1) ' simulated <human> input with controlled bias. <<<<<<<<<<<<<   if total >10000 then q$ ="Q"   g =int( ( instr( "RrPpSsQq", q$) -1) / 2) if g >2 then [endGame]   total =total +1 rps( g) =rps( g) +1 ' accumulate plays the <human> has chosen. ( & hence their (biassed?) frequencies.) 'print " You chose "; g$( g); " and I chose "; g$( c); ". "   select case g -c case 0 draw =draw +1 ':print "It's a draw" case 1, -2 pwin =pwin +1 ':print "You win!" case -1, 2 cwin =cwin +1 ':print "I win!" end select   r =int( total *rnd( 1)) ' Now select computer's choice for next confrontation. select case ' Using the accumulating data about <human>'s frequencies so far. case r <=rps( 0) c =1 case r <=( rps( 0) +rps( 1)) c =2 case else c =0 end select   scan loop until 0   [endGame] print print " You won "; pwin; ", and I won "; cwin; ". There were "; draw; " draws." if cwin >pwin then print " I AM THE CHAMPION!!" else print " You won this time." print print " At first I assumed you'd throw each equally often." print " This means I'd win 1 time in 3; draw 1 in 3; lose 1 in 3." print " However if I detect a bias in your throws,...." print " ....this allows me to anticipate your most likely throw & on average beat it." print print " In fact, keyboard layout & human frailty mean even if you TRY to be even & random..." print " ... you may be typing replies with large bias. In 100 tries I gave 48 'P's, 29 'R' & 23 'S'!" print print " This time I played.." print " Rock "; using( "##.##", rps( 2)* 100 /total); "% Paper "; using( "##.##", rps( 0) *100 /total); "% Scissors "; using( "##.##", rps( 1) *100 /total); "%." print print " ( PS. I have since learned your actual bias had been.." print " Rock "; using( "##.##", rockP); "% Paper "; using( "##.##", paprP ); "% Scissors "; using( "##.##", ( 100 -rockP -paprP)); "%.)" print print " The advantage I can gain gets bigger the further the 'human' entries are biassed." print " The results statistically smooth out better with large runs." print " Try 10,000,000, & have a cuppa while you wait." print print " Can you see what will happen if, say, the 'human' is set to give 'Rock' EVERY time?" print " Try different %ages by altering the marked code lines." print print " Thanks for playing!" end  
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#Liberty_BASIC
Liberty BASIC
mainwin 100 20   'In$ ="aaaaaaaaaaaaaaaaaccbbbbbbbbbbbbbbba" ' testing... In$ ="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" ' Out$= "12W1B12W3B24W1B14W"   Out$ =Encoded$( In$) Inv$ =Decoded$( Out$)   print " Supplied string ="; In$ Print " RLE version ="; Out$ print " Decoded back to ="; Inv$   end   function Encoded$( k$) r$ ="" r =1 for i =2 to len( k$) prev$ =mid$( k$, i -1, 1) c$ =mid$( k$, i, 1) if c$ =prev$ then ' entering a run of this character r =r +1 else ' it occurred only once r$ =r$ +str$( r) +prev$ r =1 end if next i r$ =r$ +str$( r) +c$ Encoded$ =r$ end function   function Decoded$( k$) r$ ="" v =0 for i =1 to len( k$) i$ =mid$( k$, i, 1) if instr( "0123456789", i$) then v =v *10 +val( i$) else for m =1 to v r$ =r$ +i$ next m v =0 end if next i Decoded$ =r$ end function
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Gema
Gema
/[a-mA-M]/=@int-char{@add{@char-int{$1};13}} /[n-zN-Z]/=@int-char{@sub{@char-int{$1};13}}
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#zkl
zkl
fcn sieve(limit){ composite:=Data(limit+1).fill(1); // bucket of bytes set to 1 (prime) (2).pump(limit.toFloat().sqrt()+1, Void, // Void==no results, just loop composite.get, Void.Filter, // if prime, zero multiples 'wrap(n){ [n*n..limit,n].pump(Void,composite.set.fp1(0)) }); //composite[n*p]=0 (2).filter(limit-1,composite.get); // bytes still 1 are prime } sieve(53).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
#Prolog
Prolog
search_a_list(N1, N2) :- L = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"],   write('List is :'), maplist(my_write, L), nl, nl,   ( nth1(Ind1, L, N1) -> format('~s is in position ~w~n', [N1, Ind1]) ; format('~s is not present~n', [N1])), ( nth1(Ind2, L, N2) -> format('~s is in position ~w~n', [N2, Ind2]) ; format('~s is not present~n', [N2])), ( reverse_nth1(Ind3, L, N1) -> format('~s last position is ~w~n', [N1, Ind3]) ; format('~s is not present~n', [N1])).   reverse_nth1(Ind, L, N) :- reverse(L, RL), length(L, Len), nth1(Ind1, RL, N), Ind is Len - Ind1 + 1.   my_write(Name) :- writef(' %s', [Name]).  
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#Wren
Wren
/* rc_rank_languages_by_popularity.wren */   import "./pattern" for Pattern import "./fmt" for Fmt   var CURLOPT_URL = 10002 var CURLOPT_FOLLOWLOCATION = 52 var CURLOPT_WRITEFUNCTION = 20011 var CURLOPT_WRITEDATA = 10001   foreign class Buffer { construct new() {} // C will allocate buffer of a suitable size   foreign value // returns buffer contents as a string }   foreign class Curl { construct easyInit() {}   foreign easySetOpt(opt, param)   foreign easyPerform()   foreign easyCleanup() }   var curl = Curl.easyInit()   var getContent = Fn.new { |url| var buffer = Buffer.new() curl.easySetOpt(CURLOPT_URL, url) curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C curl.easySetOpt(CURLOPT_WRITEDATA, buffer) curl.easyPerform() return buffer.value }   var unescs = [ ["_", " "], ["\%2B", "+"], ["\%C3\%A9", "é"], ["\%C3\%A0", "à"], ["\%C5\%8D", "ō"], ["\%C3\%A6", "æ"], ["\%CE\%9C", "μ"], ["\%D0\%9C\%D0\%9A", "МК"], ["\%E0\%AE\%89\%E0\%AE\%AF\%E0\%AE\%BF\%E0\%AE\%B0\%E0\%AF\%8D", "உயிர்"] ]   var unescape = Fn.new { |text| for (u in unescs) text = text.replace(u[0], u[1]) return text }   var url1 = "https://rosettacode.org/wiki/Category:Programming_Languages" var content1 = getContent.call(url1) var p1 = Pattern.new("<li><a href/=\"//wiki//Category:[+1^\"]\"") var matches1 = p1.findAll(content1) var languages = matches1.map { |l| unescape.call(l.capsText[0]) }.toList[0..-4] // the last 3 are spurious var p2 = Pattern.new("\">[+1^<]<//a>\u200f\u200e ([/d~,#03/d] member~s)") var url2 = "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=4000" var content2 = getContent.call(url2) var matches2 = p2.findAll(content2) var results = [] for (m in matches2) { var language = m.capsText[0] if (languages.contains(language)) { var numEntries = Num.fromString(m.capsText[1].replace(",", "")) results.add([language, numEntries]) } } results.sort { |a, b| a[1] > b[1] } System.print("Languages with most entries as at 4 January, 2022:") var rank = 0 var lastScore = 0 var lastRank = 0 for (i in 0...results.count) { var pair = results[i] var eq = " " rank = i + 1 if (lastScore == pair[1]) { eq = "=" rank = lastRank } else { lastScore = pair[1] lastRank = rank } Fmt.print("$-3d$s $-20s $,5d", rank, eq, pair[0], pair[1]) }
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
#DWScript
DWScript
const weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];   function toRoman(n : Integer) : String; var i, w : Integer; begin for i := 0 to weights.High do begin w := weights[i]; while n >= w do begin Result += symbols[i]; n -= w; end; if n = 0 then Break; end; end;   PrintLn(toRoman(455)); PrintLn(toRoman(3456)); PrintLn(toRoman(2488));
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.
#Elixir
Elixir
defmodule Roman_numeral do def decode([]), do: 0 def decode([x]), do: to_value(x) def decode([h1, h2 | rest]) do case {to_value(h1), to_value(h2)} do {v1, v2} when v1 < v2 -> v2 - v1 + decode(rest) {v1, _} -> v1 + decode([h2 | rest]) end end   defp to_value(?M), do: 1000 defp to_value(?D), do: 500 defp to_value(?C), do: 100 defp to_value(?L), do: 50 defp to_value(?X), do: 10 defp to_value(?V), do: 5 defp to_value(?I), do: 1 end   Enum.each(['MCMXC', 'MMVIII', 'MDCLXVI', 'IIIID'], fn clist -> IO.puts "#{clist}\t: #{Roman_numeral.decode(clist)}" 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
#Oforth
Oforth
: findRoots(f, a, b, st) | x y lasty | a f perform dup ->y ->lasty   a b st step: x [ x f perform -> y y ==0 ifTrue: [ System.Out "Root found at " << x << cr ] else: [ y lasty * sgn -1 == ifTrue: [ System.Out "Root near " << x << cr ] ] y ->lasty ] ;   : f(x) x 3 pow x sq 3 * - x 2 * + ;
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
#ooRexx
ooRexx
/* REXX program to solve a cubic polynom equation a*x**3+b*x**2+c*x+d =(x-x1)*(x-x2)*(x-x3) */ Numeric Digits 16 pi3=Rxcalcpi()/3 Parse Value '1 -3 2 0' with a b c d p=3*a*c-b**2 q=2*b**3-9*a*b*c+27*a**2*d det=q**2+4*p**3 say 'p='p say 'q='q Say 'det='det If det<0 Then Do phi=Rxcalcarccos(-q/(2*rxCalcsqrt(-p**3)),16,'R') Say 'phi='phi phi3=phi/3 y1=rxCalcsqrt(-p)*2*Rxcalccos(phi3,16,'R') y2=rxCalcsqrt(-p)*2*Rxcalccos(phi3+2*pi3,16,'R') y3=rxCalcsqrt(-p)*2*Rxcalccos(phi3+4*pi3,16,'R') End Else Do t=q**2+4*p**3 tu=-4*q+4*rxCalcsqrt(t) tv=-4*q-4*rxCalcsqrt(t) u=qroot(tu)/2 v=qroot(tv)/2 y1=u+v y2=-(u+v)/2 (u+v)/2*rxCalcsqrt(3) y3=-(u+v)/2 (-(u+v)/2*rxCalcsqrt(3)) End say 'y1='y1 say 'y2='y2 say 'y3='y3 x1=y2x(y1) x2=y2x(y2) x3=y2x(y3) Say 'x1='x1 Say 'x2='x2 Say 'x3='x3 Exit   qroot: Procedure Parse Arg a return sign(a)*rxcalcpower(abs(a),1/3,16)   y2x: Procedure Expose a b Parse Arg real imag xr=(real-b)/(3*a) If imag<>'' Then Do xi=(imag-b)/(3*a) Return xr xi'i' End Else Return xr ::requires 'rxmath' LIBRARY
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.
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z:randomize time 20 rps$="rps" 30 msg$(1)="Rock breaks scissors" 40 msg$(2)="Paper covers rock" 50 msg$(3)="Scissors cut paper" 60 print "Rock Paper Scissors":print 70 print "Enter r, p, or s as your play." 80 print "Running score shown as <your wins>:<my wins>" 90 achoice=rnd*2.99+.5 ' get integer between 1 and 3 from real between .5 and <3.5 100 ' get key 110 pin$=inkey$ 120 if pin$="" then 110 130 pchoice=instr(rps$,pin$) 140 if pchoice=0 then print "Sorry?":goto 110 150 pcf(pchoice)=pcf(pchoice)+1 160 plays=plays+1 170 print "My play: "mid$(rps$,achoice,1) 180 sw=(achoice-pchoice+3) mod 3 190 if sw=0 then print "Tie." else if sw=1 then print msg$(achoice);". My point.":ascore=ascore+1 else print msg$(pchoice);". Your point.":pscore=pscore+1 200 print pscore":"ascore 210 rn=rnd*plays 220 if rn<pcf(1) then achoice=2 else if rn<pcf(1)+pcf(2) then achoice=3 else achoice=1 230 goto 110
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.
#LiveCode
LiveCode
function rlEncode str local charCount put 1 into charCount repeat with i = 1 to the length of str if char i of str = char (i + 1) of str then add 1 to charCount else put char i of str & charCount after rle put 1 into charCount end if end repeat return rle end rlEncode   function rlDecode str repeat with i = 1 to the length of str if char i of str is not a number then put char i of str into curChar put 0 into curNum else repeat with n = i to len(str) if isnumber(char n of str) then put char n of str after curNum else put repeatString(curChar,curNum) after rldec put n - 1 into i exit repeat end if end repeat end if if i = len(str) then --dump last char put repeatString(curChar,curNum) after rldec end if end repeat return rldec end rlDecode   function repeatString str,rep repeat rep times put str after repStr end repeat return repStr end repeatString
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
#GML
GML
#define rot13 var in, out, i, working; in = argument0; out = ""; for (i = 1; i <= string_length(in); i += 1) { working = ord(string_char_at(in, i)); if ((working > 64) && (working < 91)) { working += 13; if (working > 90) { working -= 26; } } else if ((working > 96) && (working < 123)) { working += 13; if (working > 122) working -= 26; } out += chr(working); } return out;
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
#PureBasic
PureBasic
If OpenConsole() ; Open a simple console to interact with user NewList Straws.s() Define Straw$, target$="TBA" Define found   Restore haystack ; Read in all the straws of the haystack. Repeat Read.s Straw$ If Straw$<>"" AddElement(Straws()) Straws()=UCase(Straw$) Continue Else Break EndIf ForEver   While target$<>"" Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input() ResetList(Straws()): found=#False While NextElement(Straws()) If UCase(target$)=Straws() found=#True PrintN(target$+" found as index #"+Str(ListIndex(Straws()))) EndIf Wend If Not found PrintN("Not found.") EndIf Wend EndIf   DataSection haystack: Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","" EndDataSection
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#zkl
zkl
var [const] CURL=Import("zklCurl"), YAJL=Import("zklYAJL")[0];   fcn getLangCounts(language){ // -->( (count,lang), ...) continueValue,tasks,curl := "",List(), CURL(); // "nm\0nm\0...." do{ // eg 5 times page:=curl.get(("http://rosettacode.org/mw/api.php?" "format=json" "&action=query" "&generator=categorymembers" "&gcmtitle=Category:Programming%%20Languages" "&gcmlimit=500" "&prop=categoryinfo" "&rawcontinue" // remove warning "&gcmcontinue=%s") .fmt(continueValue)); page=page[0].del(0,page[1]); // get rid of HTML header json:=YAJL().write(page).close();   json["query"]["pages"].howza(9).pump(tasks,fcn(d){ #dictionary values,only // { title:Category:AWK,categoryinfo:{ pages:398,size:401,... },... } // Gotta take care of no categoryinfo case count:=d.find("categoryinfo",Dictionary).find("size",0); // or pages? if(count<300) return(Void.Skip); // prune T(count,d["title"].del(0,9)); // "Category:RPL" --> "RPL" });   if(continueValue=json.find("query-continue")) // subcat|524558580a52455858|4331 or void continueValue=continueValue["categorymembers"]["gcmcontinue"]; }while(continueValue); tasks }   langCounts:=getLangCounts() .sort(fcn(a,b){ a[0]>b[0] }); // reverse sort   println("Most popular Rosetta Code languages as of ",Time.Date.prettyDay()); foreach n,name in ([1..15].zip(langCounts)) { println("%2d: %3d %s".fmt(n,name.xplode())) }
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
#EasyLang
EasyLang
values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ] symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ] func num2rom num . rom$ . rom$ = "" for i range len values[] while num >= values[i] rom$ &= symbol$[i] num -= values[i] . . . call num2rom 1990 r$ print r$ call num2rom 2008 r$ print r$ call num2rom 1666 r$ print r$
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.
#Emacs_Lisp
Emacs Lisp
(defun ro2ar (RN) "Translate a roman number RN into arabic number. Its argument RN is wether a symbol, wether a list. Returns the arabic number. (ro2ar 'C) gives 100, (ro2ar '(X X I V)) gives 24" (cond ((eq RN 'M) 1000) ((eq RN 'D) 500) ((eq RN 'C) 100) ((eq RN 'L) 50) ((eq RN 'X) 10) ((eq RN 'V) 5) ((eq RN 'I) 1) ((null (cdr RN)) (ro2ar (car RN))) ;; stop recursion ((< (ro2ar (car RN)) (ro2ar (car (cdr RN)))) (- (ro2ar (cdr RN)) (ro2ar (car RN)))) ;; "IV" -> 5-1=4 (t (+ (ro2ar (car RN)) (ro2ar (cdr RN)))))) ;; "VI" -> 5+1=6
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
#PARI.2FGP
PARI/GP
polroots(x^3-3*x^2+2*x)
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.
#Lua
Lua
function cpuMove() local totalChance = record.R + record.P + record.S if totalChance == 0 then -- First game, unweighted random local choice = math.random(1, 3) if choice == 1 then return "R" end if choice == 2 then return "P" end if choice == 3 then return "S" end end local choice = math.random(1, totalChance) -- Weighted random bit if choice <= record.R then return "P" end if choice <= record.R + record.P then return "S" end return "R" end   function playerMove() -- Get user input for choice of 'weapon' local choice repeat os.execute("cls") -- Windows specific command, change per OS print("\nRock, Paper, Scissors") print("=====================\n") print("Scores -\tPlayer:", score.player) print("\t\tCPU:", score.cpu .. "\n\t\tDraws:", score.draws) io.write("\nChoose [R]ock [P]aper or [S]cissors: ") choice = io.read():upper():sub(1, 1) until choice == "R" or choice == "P" or choice == "S" return choice end   -- Decide who won, increment scores function checkWinner (c, p) io.write("I chose ") if c == "R" then print("rock...") end if c == "P" then print("paper...") end if c == "S" then print("scissors...") end if c == p then print("\nDraw!") score.draws = score.draws + 1 elseif (c == "R" and p == "P") or (c == "P" and p == "S") or (c == "S" and p == "R") then print("\nYou win!") score.player = score.player + 1 else print("\nYou lose!") score.cpu = score.cpu + 1 end end   -- Main procedure math.randomseed(os.time()) score = {player = 0, cpu = 0, draws = 0} record = {R = 0, P = 0, S = 0} local playerChoice, cpuChoice repeat cpuChoice = cpuMove() playerChoice = playerMove() record[playerChoice] = record[playerChoice] + 1 checkWinner(cpuChoice, playerChoice) io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ") until io.read():upper():sub(1, 1) == "Q"
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.
#Logo
Logo
to encode :str [:out "||] [:count 0] [:last first :str] if empty? :str [output (word :out :count :last)] if equal? first :str :last [output (encode bf :str :out :count+1 :last)] output (encode bf :str (word :out :count :last) 1 first :str) end   to reps :n :w output ifelse :n = 0 ["||] [word :w reps :n-1 :w] end to decode :str [:out "||] [:count 0] if empty? :str [output :out] if number? first :str [output (decode bf :str :out 10*:count + first :str)] output (decode bf :str word :out reps :count first :str) end   make "foo "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW make "rle encode :foo show equal? :foo decode :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
#Go
Go
package main   import ( "fmt" "strings" )   func rot13char(c rune) rune { if c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' { return c + 13 } else if c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' { return c - 13 } return c }   func rot13(s string) string { return strings.Map(rot13char, s) }   func main() { fmt.Println(rot13("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
#Python
Python
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]   for needle in ("Washington","Bush"): try: print haystack.index(needle), needle except ValueError, value_error: print 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
#ECL
ECL
RomanEncode(UNSIGNED Int) := FUNCTION SetWeights := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; SetSymbols := ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; ProcessRec := RECORD UNSIGNED val; STRING Roman; END; dsWeights  := DATASET(13,TRANSFORM(ProcessRec,SELF.val := Int, SELF := []));   SymbolStr(i,n,STRING s) := CHOOSE(n+1,'',SetSymbols[i],SetSymbols[i]+SetSymbols[i],SetSymbols[i]+SetSymbols[i]+SetSymbols[i],s);   RECORDOF(dsWeights) XF(dsWeights L, dsWeights R, INTEGER C) := TRANSFORM ThisVal := IF(C=1,R.Val,L.Val); IsDone := ThisVal = 0; SELF.Roman := IF(IsDone,L.Roman,L.Roman + SymbolStr(C,ThisVal DIV SetWeights[C],L.Roman)); SELF.val := IF(IsDone,0,ThisVal - ((ThisVal DIV SetWeights[C])*SetWeights[C])); END; i := ITERATE(dsWeights,XF(LEFT,RIGHT,COUNTER)); RETURN i[13].Roman; END;   RomanEncode(1954); //MCMLIV RomanEncode(1990 ); //MCMXC RomanEncode(2008 ); //MMVIII RomanEncode(1666); //MDCLXVI
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.
#Erlang
Erlang
  -module( roman_numerals ).   -export( [decode_from_string/1]).   to_value($M) -> 1000; to_value($D) -> 500; to_value($C) -> 100; to_value($L) -> 50; to_value($X) -> 10; to_value($V) -> 5; to_value($I) -> 1.   decode_from_string([]) -> 0; decode_from_string([H1]) -> to_value(H1); decode_from_string([H1, H2 |Rest]) -> case {to_value(H1), to_value(H2)} of {V1, V2} when V1 < V2 -> V2 - V1 + decode_from_string(Rest); {V1, V1} -> V1 + V1 + decode_from_string(Rest); {V1, _} -> V1 + decode_from_string([H2|Rest]) 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
#Pascal
Pascal
Program RootsFunction;   var e, x, step, value: double; s: boolean; i, limit: integer; x1, x2, d: double;   function f(const x: double): double; begin f := x*x*x - 3*x*x + 2*x; end;   begin x := -1; step := 1.0e-6; e := 1.0e-9; s := (f(x) > 0);   writeln('Version 1: simply stepping x:'); while x < 3.0 do begin value := f(x); if abs(value) < e then begin writeln ('root found at x = ', x); s := not s; end else if ((value > 0) <> s) then begin writeln ('root found at x = ', x); s := not s; end; x := x + step; end;   writeln('Version 2: secant method:'); x1 := -1.0; x2 := 3.0; e := 1.0e-15; i := 1; limit := 300; while true do begin if i > limit then begin writeln('Error: function not converging'); exit; end; d := (x2 - x1) / (f(x2) - f(x1)) * f(x2); if abs(d) < e then begin if d = 0 then write('Exact ') else write('Approximate '); writeln('root found at x = ', x2); exit; end; x1 := x2; x2 := x2 - d; i := i + 1; end; end.  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{record, play, text = "\nRock-paper-scissors\n", choices = {"Rock", "Paper", "Scissors"}}, Evaluate[record /@ choices] = {1, 1, 1}; play[x_] := Module[{y = RandomChoice[record /@ choices -> RotateLeft@choices]}, record[x]++; text = "Your Choice:" <> x <> "\nComputer's Choice:" <> y <> "\n" <> Switch[{x, y}, Alternatives @@ Partition[choices, 2, 1, 1], "You lost.", Alternatives @@ Reverse /@ Partition[choices, 2, 1, 1], "You win.", _, "Draw."]]; Column@{Dynamic[text], ButtonBar[# :> play[#] & /@ choices]}]
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.
#Lua
Lua
local C, Ct, R, Cf, Cc = lpeg.C, lpeg.Ct, lpeg.R, lpeg.Cf, lpeg.Cc astable = Ct(C(1)^0)   function compress(t) local ret = {} for i, v in ipairs(t) do if t[i-1] and v == t[i-1] then ret[#ret - 1] = ret[#ret - 1] + 1 else ret[#ret + 1] = 1 ret[#ret + 1] = v end end t = ret return table.concat(ret) end q = io.read() print(compress(astable:match(q)))   undo = Ct((Cf(Cc"0" * C(R"09")^1, function(a, b) return 10 * a + b end) * C(R"AZ"))^0)   function decompress(s) t = undo:match(s) local ret = "" for i = 1, #t - 1, 2 do for _ = 1, t[i] do ret = ret .. t[i+1] end end return ret 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
#Golo
Golo
#!/usr/bin/env golosh ---- This module encrypts strings by rotating each character by 13. ---- module Rot13   augment java.lang.Character {   function rot13 = |this| -> match { when this >= 'a' and this <= 'z' then charValue((this - 'a' + 13) % 26 + 'a') when this >= 'A' and this <= 'Z' then charValue((this - 'A' + 13) % 26 + 'A') otherwise this } }   augment java.lang.String {   function rot13 = |this| -> vector[this: charAt(i): rot13() foreach i in [0..this: length()]]: join("") }   function main = |args| {   require('A': rot13() == 'N', "A is not N") require("n": rot13() == "a", "n is not a") require("nowhere ABJURER": rot13() == "abjurer NOWHERE", "nowhere is not abjurer")   foreach string in args { print(string: rot13()) print(" ") } 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
#R
R
find.needle <- function(haystack, needle="needle", return.last.index.too=FALSE) { indices <- which(haystack %in% needle) if(length(indices)==0) stop("no needles in the haystack") if(return.last.index.too) range(indices) else min(indices) }
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
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make local numbers: ARRAY [INTEGER] do numbers := <<1990, 2008, 1666, 3159, 1977, 2010>> -- "MCMXC", "MMVIII", "MDCLXVI", "MMMCLIX", "MCMLXXVII", "MMX" across numbers as n loop print (n.item.out + " in decimal Arabic numerals is " + decimal_to_roman (n.item) + " in Roman numerals.%N") end end   feature -- Roman numerals   decimal_to_roman (a_int: INTEGER): STRING -- Representation of integer `a_int' as Roman numeral require a_int > 0 local dnums: ARRAY[INTEGER] rnums: ARRAY[STRING]   dnum: INTEGER rnum: STRING   i: INTEGER do dnums := <<1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1>> rnums := <<"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I">>   dnum := a_int rnum := ""   from i := 1 until i > dnums.count or dnum <= 0 loop from until dnum < dnums[i] loop dnum := dnum - dnums[i] rnum := rnum + rnums[i] end i := i + 1 end   Result := rnum end 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.
#ERRE
ERRE
  PROGRAM ROMAN2ARAB   DIM R%[7]   PROCEDURE TOARAB(ROMAN$->ANS%) LOCAL I%,J%,P%,N% FOR I%=LEN(ROMAN$) TO 1 STEP -1 DO J%=INSTR("IVXLCDM",MID$(ROMAN$,I%,1)) IF J%=0 THEN ANS%=-9999  ! illegal character EXIT PROCEDURE END IF IF J%>=P% THEN N%+=R%[J%] ELSE N%-=R%[J%] END IF P%=J% END FOR ANS%=N% END PROCEDURE   BEGIN R%[]=(0,1,5,10,50,100,500,1000) TOARAB("MCMXCIX"->ANS%) PRINT(ANS%) TOARAB("MMXII"->ANS%) PRINT(ANS%) TOARAB("MDCLXVI"->ANS%) PRINT(ANS%) TOARAB("MMMDCCCLXXXVIII"->ANS%) PRINT(ANS%) END PROGRAM  
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
#Perl
Perl
sub f { my $x = shift;   return ($x * $x * $x - 3*$x*$x + 2*$x); }   my $step = 0.001; # Smaller step values produce more accurate and precise results my $start = -1; my $stop = 3; my $value = &f($start); my $sign = $value > 0;   # Check for root at start   print "Root found at $start\n" if ( 0 == $value );   for( my $x = $start + $step; $x <= $stop; $x += $step ) { $value = &f($x);   if ( 0 == $value ) { # We hit a root print "Root found at $x\n"; } elsif ( ( $value > 0 ) != $sign ) { # We passed a root print "Root found near $x\n"; }   # Update our sign $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.
#Mercury
Mercury
:- module rps. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- use_module random, exception. :- import_module list, string.   :- type play ---> rock  ; paper  ; scissors.   :- pred beats(play, play). :- mode beats(in, in) is semidet. beats(rock, scissors). beats(paper, rock). beats(scissors, paper).   :- pred random(play::out, random.supply::mdi, random.supply::muo) is det. random(Play, !RS) :- random.random(1, 3, N, !RS), ( if N = 1 then Play = rock else if N = 2 then Play = paper else Play = scissors ).   main(!IO) :- seed(Seed, !IO), random.init(Seed, RS), play(RS, !IO).   :- pred play(random.supply::mdi, io::di, io::uo) is det. play(!.RS, !IO) :- io.write_string("Your choice? ", !IO), io.read(Res, !IO), ( Res = ok(Play), random(Counter, !RS), io.format("The computer chose %s\n", [s(string(Counter))], !IO), ( if beats(Counter, Play) then io.write_string("Computer wins.\n", !IO) else if beats(Play, Counter) then io.write_string("You win!\n", !IO) else io.write_string("It is a draw\n", !IO) ), play(!.RS, !IO)  ; Res = eof  ; Res = error(_, _), exception.throw(Res) ).   :- pragma foreign_decl("C", "#include <time.h>"). :- pred seed(int::out, io::di, io::uo) is det. :- pragma foreign_proc("C", seed(Seed::out, _IO0::di, _IO::uo), [promise_pure, will_not_call_mercury], " Seed = time(NULL); ").
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.
#M2000_Interpreter
M2000 Interpreter
  Module RLE_example { inp$="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" Print "Input: ";inp$ Function RLE$(r$){ Function rle_run$(&r$) { if len(r$)=0 then exit p=1 c$=left$(r$,1) while c$=mid$(r$, p, 1) {p++} =format$("{0}{1}",p-1, c$) r$=mid$(r$, p) } def repl$ while len(r$)>0 {repl$+=rle_run$(&r$)} =repl$ } RLE_encode$=RLE$(inp$) Print "RLE Encoded: ";RLE_encode$ Function RLE_decode$(r$) { def repl$ def long m, many=1 while r$<>"" and many>0 { many=val(r$, "INT", &m) repl$+=string$(mid$(r$, m, 1), many) r$=mid$(r$,m+1) } =repl$ } RLE_decode$=RLE_decode$(RLE_encode$) Print "RLE Decoded: ";RLE_decode$ Print "Checked: ";RLE_decode$=inp$ } RLE_example  
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
#Groovy
Groovy
def rot13 = { String s -> (s as List).collect { ch -> switch (ch) { case ('a'..'m') + ('A'..'M'): return (((ch as char) + 13) as char) case ('n'..'z') + ('N'..'Z'): return (((ch as char) - 13) as char) default: return ch } }.inject ("") { string, ch -> string += 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
#Racket
Racket
(define (index xs y) (for/first ([(x i) (in-indexed xs)] #:when (equal? x y)) i))
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
#Ela
Ela
open number string math   digit x y z k = [[x],[x,x],[x,x,x],[x,y],[y],[y,x],[y,x,x],[y,x,x,x],[x,z]] : (toInt k - 1)   toRoman 0 = "" toRoman x | x < 0 = fail "Negative roman numeral" | x >= 1000 = 'M' :: toRoman (x - 1000) | x >= 100 = let (q,r) = x `divrem` 100 in digit 'C' 'D' 'M' q ++ toRoman r | x >= 10 = let (q,r) = x `divrem` 10 in digit 'X' 'L' 'C' q ++ toRoman r | else = digit 'I' 'V' 'X' x   map (join "" << toRoman) [1999,25,944]
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.
#Euphoria
Euphoria
constant symbols = "MDCLXVI", weights = {1000,500,100,50,10,5,1} function romanDec(sequence roman) integer n, lastval, arabic lastval = 0 arabic = 0 for i = length(roman) to 1 by -1 do n = find(roman[i],symbols) if n then n = weights[n] end if if n < lastval then arabic -= n else arabic += n end if lastval = n end for return arabic end function   ? romanDec("MCMXCIX") ? romanDec("MDCLXVI") ? romanDec("XXV") ? romanDec("CMLIV") ? romanDec("MMXI")
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
#Phix
Phix
procedure print_roots(integer f, atom start, stop, step) -- -- Print approximate roots of f between x=start and x=stop, using -- sign changes as an indicator that a root has been encountered. -- atom x = start, y = 0 puts(1,"-----\n") while x<=stop do atom last_y = y y = f(x) if y=0 or (last_y<0 and y>0) or (last_y>0 and y<0) then printf(1,"Root found %s %.10g\n", {iff(y=0?"at":"near"),x}) end if x += step end while end procedure -- Smaller steps produce more accurate/precise results in general, -- but for many functions we'll never get exact roots, either due -- to imperfect binary representation or irrational roots. constant step = 1/256 function f1(atom x) return x*x*x-3*x*x+2*x end function function f2(atom x) return x*x-4*x+3 end function function f3(atom x) return x-1.5 end function function f4(atom x) return x*x-2 end function print_roots(f1, -1, 5, step) print_roots(f2, -1, 5, step) print_roots(f3, 0, 4, step) print_roots(f4, -2, 2, step)