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/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.
#Maple
Maple
count_sizes := proc(arr_name,arr_pop,i,lst) local index := i; local language; for language in lst do language := language[1]: arr_name(index) := txt["query"]["pages"][language]["title"][10..]: if(assigned(txt["query"]["pages"][language]["categoryinfo"]["size"])) then arr_pop(index) := txt["query"]["pages"][language]["categoryinfo"]["size"]: else: arr_pop(index) := 0: end if: index++: end do: return index: end proc:   txt := JSON:-ParseFile("http://rosettacode.org/mw/api.php?action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=350&prop=categoryinfo&format=json"): arr_name := Array(): arr_pop := Array(): i := count_sizes(arr_name, arr_pop, 1, [indices(txt["query"]["pages"])]): while (assigned(txt["continue"]["gcmcontinue"])) do continue := txt["continue"]["gcmcontinue"]: txt := JSON:-ParseFile(cat("http://rosettacode.org/mw/api.php?action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=350&prop=categoryinfo&format=json", "&continue=", txt["continue"]["continue"], "&gcmcontinue=", txt["continue"]["gcmcontinue"])): i:=count_sizes(arr_name,arr_pop,i,[indices(txt["query"]["pages"])]): end do: arr_name:= arr_name[sort(arr_pop,output=permutation)]: arr_pop := sort(arr_pop, output=sorted): i := i-1: for x from i to 1 by -1 do printf("rank %d  %d examples  %s\n", i-x+1, arr_pop[x], arr_name[x]): end do:
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Roman_Numeral_Test is function To_Roman (Number : Positive) return String is subtype Digit is Integer range 0..9; function Roman (Figure : Digit; I, V, X : Character) return String is begin case Figure is when 0 => return ""; when 1 => return "" & I; when 2 => return I & I; when 3 => return I & I & I; when 4 => return I & V; when 5 => return "" & V; when 6 => return V & I; when 7 => return V & I & I; when 8 => return V & I & I & I; when 9 => return I & X; end case; end Roman; begin pragma Assert (Number >= 1 and Number < 4000); return Roman (Number / 1000, 'M', ' ', ' ') & Roman (Number / 100 mod 10, 'C', 'D', 'M') & Roman (Number / 10 mod 10, 'X', 'L', 'C') & Roman (Number mod 10, 'I', 'V', 'X'); end To_Roman; begin Put_Line (To_Roman (1999)); Put_Line (To_Roman (25)); Put_Line (To_Roman (944)); end Roman_Numeral_Test;
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.
#ANTLR
ANTLR
/* Parse Roman Numerals   Nigel Galloway March 16th., 2012 */ grammar ParseRN ;   options { language = Java; } @members { int rnValue; int ONE; }   parseRN: ({rnValue = 0;} rn NEWLINE {System.out.println($rn.text + " = " + rnValue);})* ;   rn : (Thousand {rnValue += 1000;})* hundreds? tens? units?;   hundreds: {ONE = 0;} (h9 | h5) {if (ONE > 3) System.out.println ("Too many hundreds");}; h9 : Hundred {ONE += 1;} (FiveHund {rnValue += 400;}| Thousand {rnValue += 900;}|{rnValue += 100;} (Hundred {rnValue += 100; ONE += 1;})*); h5 : FiveHund {rnValue += 500;} (Hundred {rnValue += 100; ONE += 1;})*;   tens : {ONE = 0;} (t9 | t5) {if (ONE > 3) System.out.println ("Too many tens");}; t9 : Ten {ONE += 1;} (Fifty {rnValue += 40;}| Hundred {rnValue += 90;}|{rnValue += 10;} (Ten {rnValue += 10; ONE += 1;})*); t5 : Fifty {rnValue += 50;} (Ten {rnValue += 10; ONE += 1;})*;   units : {ONE = 0;} (u9 | u5) {if (ONE > 3) System.out.println ("Too many ones");}; u9 : One {ONE += 1;} (Five {rnValue += 4;}| Ten {rnValue += 9;}|{rnValue += 1;} (One {rnValue += 1; ONE += 1;})*); u5 : Five {rnValue += 5;} (One {rnValue += 1; ONE += 1;})*;   One : 'I'; Five : 'V'; Ten : 'X'; Fifty : 'L'; Hundred: 'C'; FiveHund: 'D'; Thousand: 'M' ; NEWLINE: '\r'? '\n' ;
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
#Clojure
Clojure
    (defn findRoots [f start stop step eps] (filter #(-> (f %) Math/abs (< eps)) (range start stop 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.
#Bash
Bash
#!/bin/bash echo "What will you choose? [rock/paper/scissors]" read response aiThought=$(echo $[ 1 + $[ RANDOM % 3 ]]) case $aiThought in 1) aiResponse="rock" ;; 2) aiResponse="paper" ;; 3) aiResponse="scissors" ;; esac echo "AI - $aiResponse" responses="$response$aiResponse" case $responses in rockrock) isTie=1 ;; rockpaper) playerWon=0 ;; rockscissors) playerWon=1 ;; paperrock) playerWon=1 ;; paperpaper) isTie=1 ;; paperscissors) playerWon=0 ;; scissorsrock) playerWon=0 ;; scissorspaper) playerWon=1 ;; scissorsscissors) isTie=1 ;; esac if [[ $isTie == 1 ]] ; then echo "It's a tie!" && exit 1 ; fi if [[ $playerWon == 0 ]] ; then echo "Sorry, $aiResponse beats $response , try again.." && exit 1 ; fi if [[ $playerWon == 1 ]] ; then echo "Good job, $response beats $aiResponse!" && exit 1 ; fi
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
rle: if not dup: drop return []   swap ]   local :source chars pop-from source 1 for c in source: if = c over: ++ else: 1 c & & return [   rld: ) for pair in swap: repeat &< pair: &> pair concat(     rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" !. dup !. rld
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.
#IDL
IDL
n = 5 print, exp( dcomplex( 0, 2*!dpi/n) ) ^ ( 1 + indgen(n) )
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.
#J
J
rou=: [: ^ 0j2p1 * i. % ]   rou 4 1 0j1 _1 0j_1   rou 5 1 0.309017j0.951057 _0.809017j0.587785 _0.809017j_0.587785 0.309017j_0.951057
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Python
Python
  """Count bare `lang` tags in wiki markup. Requires Python >=3.6.   Uses the Python standard library `urllib` to make MediaWiki API requests. """   from __future__ import annotations   import functools import gzip import json import logging import platform import re   from collections import Counter from collections import defaultdict   from typing import Any from typing import Iterator from typing import Iterable from typing import List from typing import Mapping from typing import NamedTuple from typing import Optional from typing import Tuple   from urllib.parse import urlencode from urllib.parse import urlunparse from urllib.parse import quote_plus   import urllib.error import urllib.request   logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG)     # Parse wiki markup with these regular expression patterns. Any headings and # `lang` tags found inside `nowiki`, `pre` or other `lang` tags (bare or not) # should not count as "bare". # # NOTE: The order of these patterns is significant. RE_SPEC = [ ("NOWIKI", r"<\s*nowiki\s*>.*?</\s*nowiki\s*>"), ("PRE", r"<\s*pre\s*>.*?</\s*pre\s*>"), ("LANG", r"<\s*lang\s+.+?>.*?</\s*lang\s*>"), ("HEAD", r"==\{\{\s*header\s*\|\s*(?P<header>.+?)\s*}}=="), ("BARE", r"<\s*lang\s*>.*?</\s*lang\s*>"), ]   RE_BARE_LANG = re.compile( "|".join(rf"(?P<{name}>{pattern})" for name, pattern in RE_SPEC), re.DOTALL | re.IGNORECASE, )   # Some wiki headings look like this "=={{header|Some}} / {{header|Other}}==". # We'll use this regular expression to strip out the markup. RE_MULTI_HEADER = re.compile(r"(}|(\{\{\s*header\s*\|\s*))", re.IGNORECASE)     def find_bare_lang_section_headers(wiki_text: str) -> Iterator[str]: """Generate a sequence of wiki section headings that contain bare 'lang' tags.   If there are multiple bare lang tags in a section, that section heading will appear multiple times in the sequence. """ current_heading = "no language"   for match in RE_BARE_LANG.finditer(wiki_text): kind = match.lastgroup   if kind == "HEAD": current_heading = RE_MULTI_HEADER.sub("", match.group("header")) elif kind == "BARE": yield current_heading     class Error(Exception): """Exception raised when we get an unexpected response from the MediaWiki API."""     class TagCounter: """Count bare `lang` tags in wiki markup. Group them by heading and remember what page they're in."""   def __init__(self): self.counter = Counter() self.pages = defaultdict(set) self.total = 0   def __len__(self): return len(self.counter)   @classmethod def from_section_headers( cls, page_title: str, section_headers: Iterable[str] ) -> TagCounter: """Return a new `TagCounter` initialized with the given section headings.""" counter = cls()   for heading in section_headers: counter.add(page_title, heading)   return counter   @classmethod def from_wiki_text(cls, page_title: str, wiki_text: str) -> TagCounter: """Return a new `TagCounter` initialized with bare lang tags from the given wiki text.""" return cls.from_section_headers( page_title, find_bare_lang_section_headers(wiki_text), )   def add(self, page_title: str, section_heading: str): """Increment the counter by one for the given section heading an page.""" self.counter[section_heading] += 1 self.pages[section_heading].add(page_title) self.total += 1   def update(self, other): """Union this counter with `other`, another counter.""" assert isinstance(other, TagCounter)   self.counter.update(other.counter)   for section_heading, pages in other.pages.items(): self.pages[section_heading].update(pages)   self.total += other.total   def most_common(self, n=None) -> str: """Return a formatted string of the most common wiki sections to have bare lang tags.""" buf = [f"{sum(self.counter.values())} bare lang tags.\n"]   for section_heading, count in self.counter.most_common(n=n): pages = list(self.pages[section_heading]) buf.append(f"{count} in {section_heading} {pages}")   return "\n".join(buf)     def quote_underscore(string, safe="", encoding=None, errors=None): """Like urllib.parse.quote but replaces spaces with underscores.""" string = quote_plus(string, safe, encoding, errors) return string.replace("+", "_")     class URL(NamedTuple): """A `urllib.parse.urlunparse` compatible Tuple with some helper methods. We'll use this to build and pass around our MediaWiki API URLs. """   scheme: str netloc: str path: str params: str query: str fragment: str   def __str__(self): return urlunparse(self)   def with_query(self, query: Mapping[str, Any]) -> URL: query_string = urlencode(query, safe=":", quote_via=quote_underscore) return self._replace(query=query_string)     API_BASE_URL = URL( scheme="http", netloc="rosettacode.org", path="/mw/api.php", params="", query="", fragment="", )   UGLY_RAW_URL = URL( scheme="http", netloc="rosettacode.org", path="/mw/index.php", params="", query="", fragment="", )   # NOTE: Cloudflare was blocking requests with the default user agent. DEFAULT_HEADERS = { "User-agent": f"python/{platform.python_version()}", "Accept-encoding": "gzip, deflate", "Accept": "*/*", "Connection": "keep-alive", }     class Response(NamedTuple): headers: Mapping[str, str] body: bytes     def get(url: URL, headers=DEFAULT_HEADERS) -> Response: """Make an HTTP GET request to the given URL.""" logger.debug(f"GET {url}") request = urllib.request.Request(str(url), headers=headers)   try: with urllib.request.urlopen(request) as response: return Response( headers=dict(response.getheaders()), body=response.read(), ) except urllib.error.HTTPError as e: logging.debug(e.code) logging.debug(gzip.decompress(e.read())) raise     def raise_for_header(headers: Mapping[str, str], header: str, expect: str): got = headers.get(header) if got != expect: raise Error(f"expected '{expect}', got '{got}'")     raise_for_content_type = functools.partial(raise_for_header, header="Content-Type")     class CMContinue(NamedTuple): continue_: str cmcontinue: str     Pages = Tuple[List[str], Optional[CMContinue]]     def get_wiki_page_titles(chunk_size: int = 500, continue_: CMContinue = None) -> Pages: """Return a list of wiki page titles and any continuation information.""" query = { "action": "query", "list": "categorymembers", "cmtitle": "Category:Programming_Tasks", "cmlimit": chunk_size, "format": "json", "continue": "", }   if continue_: query["continue"] = continue_.continue_ query["cmcontinue"] = continue_.cmcontinue   response = get(API_BASE_URL.with_query(query))   # Fail early if the response is not what we are expecting. raise_for_content_type(response.headers, expect="application/json; charset=utf-8") raise_for_header(response.headers, "Content-Encoding", "gzip")   data = json.loads(gzip.decompress(response.body)) page_titles = [p["title"] for p in data["query"]["categorymembers"]]   if data.get("continue", {}).get("cmcontinue"): _continue = CMContinue( data["continue"]["continue"], data["continue"]["cmcontinue"], ) else: _continue = None   return (page_titles, _continue)     def get_wiki_page_markup(page_title: str) -> str: """Return raw MediaWiki markup from the page `page_title`.""" query = {"action": "raw", "title": page_title} response = get(UGLY_RAW_URL.with_query(query))   # Fail early if the response is not what we are expecting. raise_for_content_type(response.headers, expect="text/x-wiki; charset=UTF-8")   return response.body.decode()     def example(limit=30): # Get the first chunk of wiki page titles from the MediaWiki API page_titles, continue_ = get_wiki_page_titles()   # Get more chunks if there are any. while continue_ is not None: more_page_titles, continue_ = get_wiki_page_titles(continue_=continue_) page_titles.extend(more_page_titles)   # Aggregate counts from all pages. counter = TagCounter()   for i, page_title in enumerate(page_titles): if i > limit: break   # Read and parse raw wiki page markup. wiki_text = get_wiki_page_markup(page_title) counts = TagCounter.from_wiki_text(page_title, wiki_text) counter.update(counts)   # Dump the results to stdout. print(counter.most_common())     if __name__ == "__main__": logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG) example()  
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.
#IDL
IDL
compile_OPT IDL2   print, "input a, press enter, input b, press enter, input c, press enter" read,a,b,c Promt='Enter values of a,b,c and hit enter'   a0=0.0 b0=0.0 c0=0.0 ;make them floating point variables   x=-b+sqrt((b^2)-4*a*c) y=-b-sqrt((b^2)-4*a*c) z=2*a d= x/z e= y/z   print, d,e
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.
#IS-BASIC
IS-BASIC
  100 PROGRAM "Quadratic.bas" 110 PRINT "Enter coefficients a, b and c:":INPUT PROMPT "a= ,b= ,c= ":A,B,C 120 IF A=0 THEN 130 PRINT "The coefficient of x^2 can not be 0." 140 ELSE 150 LET D=B^2-4*A*C 160 SELECT CASE SGN(D) 170 CASE 0 180 PRINT "The single root is ";-B/2/A 190 CASE 1 200 PRINT "The real roots are ";(-B+SQR(D))/(2*A);"and ";(-B-SQR(D))/(2*A) 210 CASE -1 220 PRINT "The complex roots are ";-B/2/A;"+/- ";STR$(SQR(-D)/2/A);"*i" 230 END SELECT 240 END IF
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
#C.2B.2B
C++
#include <iostream> #include <istream> #include <ostream> #include <fstream> #include <cstdlib> #include <string>   // the rot13 function std::string rot13(std::string s) { static std::string const lcalph = "abcdefghijklmnopqrstuvwxyz", ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   std::string result; std::string::size_type pos;   result.reserve(s.length());   for (std::string::iterator it = s.begin(); it != s.end(); ++it) { if ( (pos = lcalph.find(*it)) != std::string::npos ) result.push_back(lcalph[(pos+13) % 26]); else if ( (pos = ucalph.find(*it)) != std::string::npos ) result.push_back(ucalph[(pos+13) % 26]); else result.push_back(*it); }   return result; }   // function to output the rot13 of a file on std::cout // returns false if an error occurred processing the file, true otherwise // on entry, the argument is must be open for reading int rot13_stream(std::istream& is) { std::string line; while (std::getline(is, line)) { if (!(std::cout << rot13(line) << "\n")) return false; } return is.eof(); }   // the main program int main(int argc, char* argv[]) { if (argc == 1) // no arguments given return rot13_stream(std::cin)? EXIT_SUCCESS : EXIT_FAILURE;   std::ifstream file; for (int i = 1; i < argc; ++i) { file.open(argv[i], std::ios::in); if (!file) { std::cerr << argv[0] << ": could not open for reading: " << argv[i] << "\n"; return EXIT_FAILURE; } if (!rot13_stream(file)) { if (file.eof()) // no error occurred for file, so the error must have been in output std::cerr << argv[0] << ": error writing to stdout\n"; else std::cerr << argv[0] << ": error reading from " << argv[i] << "\n"; return EXIT_FAILURE; } file.clear(); file.close(); if (!file) std::cerr << argv[0] << ": warning: closing failed for " << argv[i] << "\n"; } return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#OCaml
OCaml
let y' t y = t *. sqrt y let exact t = let u = 0.25*.t*.t +. 1.0 in u*.u   let rk4_step (y,t) h = let k1 = h *. y' t y in let k2 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k1) in let k3 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k2) in let k4 = h *. y' (t +. h) (y +. k3) in (y +. (k1+.k4)/.6.0 +. (k2+.k3)/.3.0, t +. h)   let rec loop h n (y,t) = if n mod 10 = 1 then Printf.printf "t = %f,\ty = %f,\terr = %g\n" t y (abs_float (y -. exact t)); if n < 102 then loop h (n+1) (rk4_step (y,t) h)   let _ = loop 0.1 1 (1.0, 0.0)
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Ring
Ring
  # Project: Rosetta Code/Find unimplemented tasks   load "stdlib.ring" ros= download("http://rosettacode.org/wiki/Category:Programming_Tasks") lang = "Ring" pos = 1 num = 0 totalros = 0 rosname = "" rostitle = "" see "Tasks not implemented in " + lang + " language:" + nl for n = 1 to len(ros) nr = searchstring(ros,'<li><a href="/wiki/',pos) if nr = 0 exit else pos = nr + 1 ok nr = searchname(nr) nr = searchtitle(nr) next see nl see "Total: " + totalros + " examples." + nl   func searchstring(str,substr,n) newstr=right(str,len(str)-n+1) nr = substr(newstr, substr) if nr = 0 return 0 else return n + nr -1 ok   func searchname(sn) nr2 = searchstring(ros,'">',sn) nr3 = searchstring(ros,"</a></li>",sn) rosname = substr(ros,nr2+2,nr3-nr2-2) return sn   func searchtitle(sn) st = searchstring(ros,"title=",sn) rostitle = substr(ros,sn+19,st-sn-21) rostitle = "rosettacode.org/wiki/" + rostitle rostitle = download(rostitle) s = substr(rostitle,lang) if s = 0 num = num + 1 totalros = totalros + 1 see "" + num + ". " + rosname + nl ok return sn   func count(cstring,dstring) sum = 0 while substr(cstring,dstring) > 0 sum = sum + 1 cstring = substr(cstring,substr(cstring,dstring)+len(string(sum))) end return sum  
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Ruby
Ruby
require 'rosettacode' require 'time'   module RosettaCode def self.get_unimplemented(lang) programming_tasks = [] category_members("Programming_Tasks") {|task| programming_tasks << task}   lang_tasks = [] category_members(lang) {|task| lang_tasks << task}   lang_tasks_omit = [] category_members("#{lang}/Omit") {|task| lang_tasks_omit << task}   [programming_tasks - lang_tasks, lang_tasks_omit] end   def self.created_time(title) url = get_api_url({ "action" => "query", "titles" => title, "format" => "xml", "rvlimit" => 500, "prop" => "revisions", "rvprop" => "timestamp" }) doc = REXML::Document.new open(url) REXML::XPath.each(doc, "//rev").collect do |node| Time.parse( node.attribute("timestamp").value ) end.min end   end   puts Time.now lang = ARGV[0] || "Ruby" unimplemented, omitted = RosettaCode.get_unimplemented(lang) unimplemented.collect {|title| [title, RosettaCode.created_time(title)]} . sort_by {|e| e[1]} . each do |title, date| puts "%s %6s %s" % [ date.strftime("%Y-%m-%d"), omitted.include?(title) ? "[omit]" : "" , title ] end  
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#PicoLisp
PicoLisp
: (any "((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))") -> ((data "quoted data" 123 5) (data (!@# (5) "(more" "data)")))   : (view @) +---+-- data | | | +-- "quoted data" | | | +-- 123 | | | +-- 5 | +---+-- data | +---+-- !@# | +---+-- 5 | +-- "(more" | +-- "data)"
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#Phix
Phix
with javascript_semantics sequence numbers = repeat(0,6) integer t,n while true do for i=1 to length(numbers) do sequence ni = sq_rand(repeat(6,4)) numbers[i] = sum(ni)-min(ni) end for t = sum(numbers) n = sum(sq_ge(numbers,15)) if t>=75 and n>=2 then exit end if ?"re-rolling..." -- (occasionally >20) end while printf(1,"The 6 attributes generated are:\n") printf(1,"strength %d, dexterity %d, constitution %d, "& "intelligence %d, wisdom %d, and charisma %d.\n", numbers) printf(1,"\nTheir sum is %d and %d of them are >=15\n",{t,n})
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
#Sidef
Sidef
func sieve(limit) { var sieve_arr = [false, false, (limit-1).of(true)...] gather { sieve_arr.each_kv { |number, is_prime| if (is_prime) { take(number) for i in (number**2 .. limit `by` number) { sieve_arr[i] = false } } } } }   say sieve(100).join(",")
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Objeck
Objeck
use HTTP; use XML;   class RosettaCount { function : Main(args : String[]) ~ Nil { taks_xml := HttpGet("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"); parser := XmlParser->New(taks_xml); if(parser->Parse()) { task_names := parser->FindElements("/api/query/categorymembers/cm"); if(task_names <> Nil) { each(i : task_names) { task_name := task_names->Get(i)->As(XmlElement)->GetAttribute("title")->GetValue(); task_url := "http://rosettacode.org/mw/index.php?title="; task_url->Append(task_name); task_url->Append("&action=raw");   task := HttpGet(task_url); counts := task->FindAll("=={{header|"); if(counts->Size() > 0) { IO.Console->Print(UrlUtility->Decode(task_name))->Print(": ")->PrintLine(counts->Size()); }; }; }; }; }   function : HttpGet(url : String) ~ String { xml := "";   client := HttpClient->New(); lines := client->Get(url); each(i : lines) { xml->Append(lines->Get(i)->As(String)); };   return xml; } }
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
#Lingo
Lingo
haystack = ["apples", "oranges", "bananas", "oranges"] needle = "oranges"   pos = haystack.getPos(needle) if pos then put "needle found at index "&pos else put "needle not found in haystack" end if   -- "needle found at index 2"
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]]; Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}]; b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"], "category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages; For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], 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
#ALGOL_68
ALGOL 68
[]CHAR roman = "MDCLXVmdclxvi"; # UPPERCASE for thousands # []CHAR adjust roman = "CCXXmmccxxii"; []INT arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1); []INT adjust arabic = (100000, 100000, 10000, 10000, 1000, 1000, 100, 100, 10, 10, 1, 1, 0);   PROC arabic to roman = (INT dclxvi)STRING: ( INT in := dclxvi; # 666 # STRING out := ""; FOR scale TO UPB roman WHILE in /= 0 DO INT multiples = in OVER arabic[scale]; in -:= arabic[scale] * multiples; out +:= roman[scale] * multiples; IF in >= -adjust arabic[scale] + arabic[scale] THEN in -:= -adjust arabic[scale] + arabic[scale]; out +:= adjust roman[scale] + roman[scale] FI OD; out );   main:( []INT test = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,69,70, 80,90,99,100,200,300,400,500,600,666,700,800,900,1000,1009,1444,1666,1945,1997,1999, 2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000,max int); FOR key TO UPB test DO INT val = test[key]; print((val, " - ", arabic to roman(val), new line)) OD )
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.
#APL
APL
fromRoman←{ rmn←(⎕A,⎕A,'*')[(⎕A,⎕UCS 96+⍳26)⍳⍵] ⍝ make input uppercase dgt←↑'IVXLCDM' (1 5 10 50 100 500 1000) ⍝ values of roman digits ~rmn∧.∊⊂dgt[1;]:⎕SIGNAL 11 ⍝ domain error if non-roman input map←dgt[2;dgt[1;]⍳rmn] ⍝ map digits to values +/map×1-2×(2</map),0 ⍝ subtractive principle }
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
#CoffeeScript
CoffeeScript
  print_roots = (f, begin, end, step) -> # Print approximate roots of f between x=begin and x=end, # using sign changes as an indicator that a root has been # encountered. x = begin y = f(x) last_y = y   cross_x_axis = -> (last_y < 0 and y > 0) or (last_y > 0 and y < 0)   console.log '-----' while x <= end y = f(x) if y == 0 console.log "Root found at", x else if cross_x_axis() console.log "Root found near", x x += step last_y = y   do -> # 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. step = 1 / 256   f1 = (x) -> x*x*x - 3*x*x + 2*x print_roots f1, -1, 5, step f2 = (x) -> x*x - 4*x + 3 print_roots f2, -1, 5, step f3 = (x) -> x - 1.5 print_roots f3, 0, 4, step f4 = (x) -> x*x - 2 print_roots f4, -2, 2, 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.
#BASIC
BASIC
DIM pPLchoice(1 TO 3) AS INTEGER, pCMchoice(1 TO 3) AS INTEGER DIM choices(1 TO 3) AS STRING DIM playerwins(1 TO 3) AS INTEGER DIM playerchoice AS INTEGER, compchoice AS INTEGER DIM playerwon AS INTEGER, compwon AS INTEGER, tie AS INTEGER DIM tmp AS INTEGER   ' Do it this way for QBasic; FreeBASIC supports direct array assignment. DATA "rock", "paper", "scissors" FOR tmp = 1 TO 3 READ choices(tmp) NEXT DATA 3, 1, 2 FOR tmp = 1 TO 3 READ playerwins(tmp) NEXT   RANDOMIZE TIMER   DO ' Computer chooses first to ensure there's no "cheating". compchoice = INT(RND * (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 3)) SELECT CASE compchoice CASE 0 TO (pPLchoice(1)) ' Player past choice: rock; choose paper. compchoice = 2 CASE (pPLchoice(1) + 1) TO (pPLchoice(1) + pPLchoice(2) + 1) ' Player past choice: paper; choose scissors. compchoice = 3 CASE (pPLchoice(1) + pPLchoice(2) + 2) TO (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 2) ' Player past choice: scissors; choose rock. compchoice = 1 END SELECT   PRINT "Rock, paper, or scissors "; DO PRINT "[1 = rock, 2 = paper, 3 = scissors, 0 to quit]"; INPUT playerchoice LOOP WHILE (playerchoice < 0) OR (playerchoice > 3)   IF 0 = playerchoice THEN EXIT DO   pCMchoice(compchoice) = pCMchoice(compchoice) + 1 pPLchoice(playerchoice) = pPLchoice(playerchoice) + 1 PRINT "You chose "; choices(playerchoice); " and I chose "; choices(compchoice); ". "; IF (playerchoice) = compchoice THEN PRINT "Tie!" tie = tie + 1 ELSEIF (compchoice) = playerwins(playerchoice) THEN PRINT "You won!" playerwon = playerwon + 1 ELSE PRINT "I won!" compwon = compwon + 1 END IF LOOP   PRINT "Some useless statistics:" PRINT "You won "; STR$(playerwon); " times, and I won "; STR$(compwon); " times; "; STR$(tie); " ties." PRINT , choices(1), choices(2), choices(3) PRINT "You chose:", pPLchoice(1), pPLchoice(2), pPLchoice(3) PRINT " I chose:", pCMchoice(1), pCMchoice(2), pCMchoice(3)
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.
#Delphi
Delphi
  program RunLengthTest;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TRLEPair = record count: Integer; letter: Char; end;   TRLEncoded = TArray<TRLEPair>;   TRLEncodedHelper = record helper for TRLEncoded public procedure Clear; function Add(c: Char): Integer; procedure Encode(Data: string); function Decode: string; function ToString: string; end;   { TRLEncodedHelper }   function TRLEncodedHelper.Add(c: Char): Integer; begin SetLength(self, length(self) + 1); Result := length(self) - 1; with self[Result] do begin count := 1; letter := c; end; end;   procedure TRLEncodedHelper.Clear; begin SetLength(self, 0); end;   function TRLEncodedHelper.Decode: string; var p: TRLEPair; begin Result := ''; for p in Self do Result := Result + string.Create(p.letter, p.count); end;   procedure TRLEncodedHelper.Encode(Data: string); var pivot: Char; i, index: Integer; begin Clear; if Data.Length = 0 then exit;   pivot := Data[1]; index := Add(pivot);   for i := 2 to Data.Length do begin if pivot = Data[i] then inc(self[index].count) else begin pivot := Data[i]; index := Add(pivot); end; end; end;   function TRLEncodedHelper.ToString: string; var p: TRLEPair; begin Result := ''; for p in Self do Result := Result + p.count.ToString + p.letter; end;   const Input = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';   var Data: TRLEncoded;   begin Data.Encode(Input); Writeln(Data.ToString); writeln(Data.Decode); Readln; 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.
#Java
Java
import java.util.Locale;   public class Test {   public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); }   public static void unity(int n) { System.out.printf("%n%d: ", n);   //all the way around the circle at even intervals for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {   double real = Math.cos(angle); //real axis is the x axis   if (Math.abs(real) < 1.0E-3) real = 0.0; //get rid of annoying sci notation   double imag = Math.sin(angle); //imaginary axis is the y axis   if (Math.abs(imag) < 1.0E-3) imag = 0.0;   System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Racket
Racket
  #lang racket   (require net/url net/uri-codec json)   (define (get-text page) (define ((get k) x) (dict-ref x k)) ((compose1 (get '*) car (get 'revisions) cdar hash->list (get 'pages) (get 'query) read-json get-pure-port string->url format) "http://rosettacode.org/mw/api.php?~a" (alist->form-urlencoded `([titles . ,page] [prop . "revisions"] [rvprop . "content"] [format . "json"] [action . "query"]))))   (define (find-bare-tags page) (define in (open-input-string (get-text page))) (define rx ((compose1 pregexp string-append) "<\\s*lang\\s*>|" "==\\s*\\{\\{\\s*header\\s*\\|\\s*([^{}]*?)\\s*\\}\\}\\s*==")) (let loop ([lang "no language"] [bare '()]) (match (regexp-match rx in) [(list _ #f) (loop lang (dict-update bare lang add1 0))] [(list _ lang) (loop lang bare)] [#f (if (null? bare) (printf "no bare language tags\n") (begin (printf "~a bare language tags\n" (apply + (map cdr bare))) (for ([b bare]) (printf " ~a in ~a\n" (cdr b) (car b)))))])))   (find-bare-tags "Rosetta Code/Find bare lang tags")  
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Raku
Raku
my $lang = '(no language)'; my $total = 0; my %blanks;   for lines() { when / '<lang>' / { %blanks{$lang}++; $total++; } when ms/ '==' '{{' 'header' '|' ( <-[}]>+? ) '}}' '==' / { $lang = $0.lc; } }   say "$total bare language tag{ 's' if $total != 1 }\n"; say .value, ' in ', .key for %blanks.sort;
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.
#J
J
p.
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.
#Java
Java
public class QuadraticRoots { private static class Complex { double re, im;   public Complex(double re, double im) { this.re = re; this.im = im; }   @Override public boolean equals(Object obj) { if (obj == this) {return true;} if (!(obj instanceof Complex)) {return false;} Complex other = (Complex) obj; return (re == other.re) && (im == other.im); }   @Override public String toString() { if (im == 0.0) {return String.format("%g", re);} if (re == 0.0) {return String.format("%gi", im);} return String.format("%g %c %gi", re, (im < 0.0 ? '-' : '+'), Math.abs(im)); } }   private static Complex[] quadraticRoots(double a, double b, double c) { Complex[] roots = new Complex[2]; double d = b * b - 4.0 * a * c; // discriminant double aa = a + a;   if (d < 0.0) { double re = -b / aa; double im = Math.sqrt(-d) / aa; roots[0] = new Complex(re, im); roots[1] = new Complex(re, -im); } else if (b < 0.0) { // Avoid calculating -b - Math.sqrt(d), to avoid any // subtractive cancellation when it is near zero. double re = (-b + Math.sqrt(d)) / aa; roots[0] = new Complex(re, 0.0); roots[1] = new Complex(c / (a * re), 0.0); } else { // Avoid calculating -b + Math.sqrt(d). double re = (-b - Math.sqrt(d)) / aa; roots[1] = new Complex(re, 0.0); roots[0] = new Complex(c / (a * re), 0.0); } return roots; }   public static void main(String[] args) { double[][] equations = { {1.0, 22.0, -1323.0}, // two distinct real roots {6.0, -23.0, 20.0}, // with a != 1.0 {1.0, -1.0e9, 1.0}, // with one root near zero {1.0, 2.0, 1.0}, // one real root (double root) {1.0, 0.0, 1.0}, // two imaginary roots {1.0, 1.0, 1.0} // two complex roots }; for (int i = 0; i < equations.length; i++) { Complex[] roots = quadraticRoots( equations[i][0], equations[i][1], equations[i][2]); System.out.format("%na = %g b = %g c = %g%n", equations[i][0], equations[i][1], equations[i][2]); if (roots[0].equals(roots[1])) { System.out.format("X1,2 = %s%n", roots[0]); } else { System.out.format("X1 = %s%n", roots[0]); System.out.format("X2 = %s%n", roots[1]); } } } }
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
#Clojure
Clojure
(ns rosettacode.rot-13)   (let [a (int \a) m (int \m) A (int \A) M (int \M) n (int \n) z (int \z) N (int \N) Z (int \Z)] (defn rot-13 [^Character c] (char (let [i (int c)] (cond-> i (or (<= a i m) (<= A i M)) (+ 13) (or (<= n i z) (<= N i Z)) (- 13))))))   (apply str (map rot-13 "The Quick Brown Fox Jumped Over The Lazy Dog!"))   ; An alternative implementation using a map: (let [A (into #{} "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") Am (->> (cycle A) (drop 26) (take 52) (zipmap A))] (defn rot13 [^String in] (apply str (map #(Am % %) in))))   (rot13 "The Quick Brown Fox Jumped Over The Lazy Dog!")
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#Octave
Octave
  #Applying the Runge-Kutta method (This code must be implement on a different file than the main one).   function temp = rk4(func,x,pvi,h) K1 = h*func(x,pvi); K2 = h*func(x+0.5*h,pvi+0.5*K1); K3 = h*func(x+0.5*h,pvi+0.5*K2); K4 = h*func(x+h,pvi+K3); temp = pvi + (K1 + 2*K2 + 2*K3 + K4)/6; endfunction   #Main Program.   f = @(t) (1/16)*((t.^2 + 4).^2); df = @(t,y) t*sqrt(y);   pvi = 1.0; h = 0.1; Yn = pvi;   for x = 0:h:10-h pvi = rk4(df,x,pvi,h); Yn = [Yn pvi]; endfor   fprintf('Time \t Exact Value \t ODE4 Value \t Num. Error\n');   for i=0:10 fprintf('%d \t %.5f \t %.5f \t %.4g \n',i,f(i),Yn(1+i*10),f(i)-Yn(1+i*10)); endfor  
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Run_BASIC
Run BASIC
WordWrap$ = "style='white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word'" a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages") a$ = word$(a$,2,"mw-subcategories") a$ = word$(a$,1,"</table>") i = instr(a$,"/wiki/Category:") html "<B> Select language from list<BR>" html "<SELECT name='lang'>" while i <> 0 j = instr(a$,""" title=""Category:",i) lang$ = mid$(a$,i+15,j-i-15) k = instr(a$,""">",j + 18) langName$ = mid$(a$,j + 18,k-(j+18)) count = count + 1 html "<option value='";lang$;"'>";langName$;"</option>" i = instr(a$,"/wiki/Category:",k) wend html "</select>" html "<p>Number of Languages:";count;"<BR> " button #go,"GO", [go] html " " button #ex, "Exit", [exit] wait   [go] cls lang$ = #request get$("lang") h$ = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_";lang$ a$ = httpGet$(h$) a$ = word$(a$,3,"mw-content-ltr") html "<table border=1><tr>" i = instr(a$,"<a href=""/wiki/") while i > 0 i = instr(a$,"title=""",i) j = instr(a$,""">",i+7) if c mod 4 = 0 then html "</tr><tr ";WordWrap$;">" c = c + 1 html "<td>";mid$(a$,i+7,j-(i+7));"</td>" i = instr(a$,"<a href=""/wiki/",i+7) wend html "</tr></table>" print "Total unImplemented Tasks:";c [exit] end
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Rust
Rust
  use std::collections::{BTreeMap, HashSet};   use reqwest::Url; use serde::Deserialize; use serde_json::Value;   /// A Rosetta Code task. #[derive(Clone, PartialEq, Eq, Hash, Debug, Deserialize)] pub struct Task { /// The ID of the page containing the task in the MediaWiki API. #[serde(rename = "pageid")] pub id: u64,   /// The human-readable title of the task. pub title: String, }   /// Encapsulates errors that might occur during JSON parsing. #[derive(Debug)] enum TaskParseError { /// Something went wrong with the HTTP request to the API. Http(reqwest::Error),   /// There was a problem parsing the API response into JSON. Json(serde_json::Error),   /// The response JSON contained unexpected keys or values. UnexpectedFormat, }   impl From<serde_json::Error> for TaskParseError { fn from(err: serde_json::Error) -> Self { TaskParseError::Json(err) } }   impl From<reqwest::Error> for TaskParseError { fn from(err: reqwest::Error) -> Self { TaskParseError::Http(err) } }   /// Represents a category of pages on Rosetta Code, such as "Rust". struct Category { name: String, continue_params: Option<BTreeMap<String, String>>, }   impl Category { fn new(name: &str) -> Category { let mut continue_params = BTreeMap::new(); continue_params.insert("continue".to_owned(), "".to_owned());   Category { name: name.to_owned(), continue_params: Some(continue_params), } } }   /// Sends a request to Rosetta Code through the MediaWiki API. If successful, returns the response /// as a JSON object. fn query_api( category_name: &str, continue_params: &BTreeMap<String, String>, ) -> Result<Value, TaskParseError> { let mut url = Url::parse("http://rosettacode.org/mw/api.php").expect("invalid URL"); url.query_pairs_mut() .append_pair("action", "query") .append_pair("list", "categorymembers") .append_pair("cmtitle", &format!("Category:{}", category_name)) .append_pair("cmlimit", "500") .append_pair("format", "json") .extend_pairs(continue_params);   Ok(reqwest::blocking::get(url)?.json()?) }   /// Given a JSON object, parses the task information from the MediaWiki API response. fn parse_tasks(json: &Value) -> Result<Vec<Task>, TaskParseError> { let tasks_json = json .pointer("/query/categorymembers") .and_then(Value::as_array) .ok_or(TaskParseError::UnexpectedFormat)?;   tasks_json .iter() .map(|json| Task::deserialize(json).map_err(From::from)) .collect() }   impl Iterator for Category { type Item = Vec<Task>;   fn next(&mut self) -> Option<Self::Item> { self.continue_params.as_ref()?;   query_api(&self.name, self.continue_params.as_ref()?) .and_then(|result| { // If there are more pages of results to request, save them for the next iteration. self.continue_params = result .get("continue") .and_then(Value::as_object) .map(|continue_params| { continue_params .iter() .map(|(key, value)| { (key.to_owned(), value.as_str().unwrap().to_owned()) }) .collect() });   parse_tasks(&result) }) .map_err(|err| println!("Error parsing response: {:?}", err)) .ok() } }   pub fn all_tasks() -> Vec<Task> { Category::new("Programming Tasks").flatten().collect() }   pub fn unimplemented_tasks(lang: &str) -> Vec<Task> { let all_tasks = all_tasks().iter().cloned().collect::<HashSet<_>>(); let implemented_tasks = Category::new(lang).flatten().collect::<HashSet<_>>(); let mut unimplemented_tasks = all_tasks .difference(&implemented_tasks) .cloned() .collect::<Vec<Task>>(); unimplemented_tasks.sort_by(|a, b| a.title.cmp(&b.title)); unimplemented_tasks }     fn main() { for task in find_unimplemented_tasks::unimplemented_tasks("Rust") { println!("{:6} {}", task.id, task.title); } }  
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#Pike
Pike
class Symbol(string name) { string _sprintf(int type) { switch(type) { case 's': return name; case 'O': return sprintf("(Symbol: %s)", name||""); case 'q': return name; case 't': return "Symbol"; default: return sprintf("%"+int2char(type), name); } }   mixed cast(string type) { switch(type) { case "string": return name; default: throw(sprintf("can not cast 'Symbol' to '%s'", type)); } } }   mixed value(string token) { if ((string)(int)token==token) return (int)token; array result = array_sscanf(token, "%f%s"); if (sizeof(result) && floatp(result[0]) && ! sizeof(result[1])) return result[0]; else return Symbol(token); }   array tokenizer(string input) { array output = ({}); for(int i=0; i<sizeof(input); i++) { switch(input[i]) { case '(': output+= ({"("}); break; case ')': output += ({")"}); break; case '"': //" output+=array_sscanf(input[++i..], "%s\"%[ \t\n]")[0..0]; i+=sizeof(output[-1]); break; case ' ': case '\t': case '\n': break; default: string token = array_sscanf(input[i..], "%s%[) \t\n]")[0]; output+=({ value(token) }); i+=sizeof(token)-1; break; } } return output; }   // this function is based on the logic in Parser.C.group() in the pike library; array group(array tokens) { ADT.Stack stack=ADT.Stack(); array ret =({});   foreach(tokens;; string token) { switch(token) { case "(": stack->push(ret); ret=({}); break; case ")": if (!sizeof(ret) || !stack->ptr) { // Mismatch werror ("unmatched close parenthesis\n"); return ret; } ret=stack->pop()+({ ret }); break; default: ret+=({token}); break; } } return ret; }   string sexp(array input) { array output = ({}); foreach(input;; mixed item) { if (arrayp(item)) output += ({ sexp(item) }); else if (intp(item)) output += ({ sprintf("%d", item) }); else if (floatp(item)) output += ({ sprintf("%f", item) }); else output += ({ sprintf("%q", item) }); } return "("+output*" "+")"; }   string input = "((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))"; array data = group(tokenizer(input))[0]; string output = sexp(data);
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#PHP
PHP
<?php   $attributesTotal = 0; $count = 0;   while($attributesTotal < 75 || $count < 2) { $attributes = [];   foreach(range(0, 5) as $attribute) { $rolls = [];   foreach(range(0, 3) as $roll) { $rolls[] = rand(1, 6); }   sort($rolls); array_shift($rolls);   $total = array_sum($rolls);   if($total >= 15) { $count += 1; }   $attributes[] = $total; }   $attributesTotal = array_sum($attributes); }   print_r($attributes);
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
#Simula
Simula
BEGIN INTEGER ARRAY t(0:1000); INTEGER i,j,k; FOR i:=0 STEP 1 UNTIL 1000 DO t(i):=1; t(0):=0; t(1):=0; i:=0; FOR i:=i WHILE i<1000 DO BEGIN FOR i:=i WHILE i<1000 AND t(i)=0 DO i:=i+1; IF i<1000 THEN BEGIN j:=2; k:=j*i; FOR k:=k WHILE k<1000 DO BEGIN t(k):=0; j:=j+1; k:=j*i END; i:=i+1 END END; FOR i:=0 STEP 1 UNTIL 999 DO IF t(i)<>0 THEN BEGIN OutInt(i,5); OutImage END END
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#OCaml
OCaml
ocaml str.cma unix.cma -I +pcre pcre.cma -I +netsys netsys.cma -I +equeue equeue.cma \ -I +netstring netstring.cma -I +netclient netclient.cma -I +xml-light xml-light.cma countex.ml
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} [StringX] = {Module.link ['x-oz://system/String.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   AllTasksUrl = "http://rosettacode.org/mw/api.php?action=query&list="# "categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"   proc {Main} AllTasks = {Parse {GetPage AllTasksUrl}} TaskTitles = {GetTitles AllTasks} Total = {NewCell 0} in for Task in TaskTitles do TaskPage = {GetPage {TaskUrl Task}} RE = {Regex.compile "{{header\\|" [extended newline icase]} NumMatches = {Length {Regex.allMatches RE TaskPage}} in {System.showInfo Task#": "#NumMatches#" examples."} Total := @Total + NumMatches end {System.showInfo "Total: "#@Total#" examples."} end   fun {TaskUrl Task} "http://rosettacode.org/mw/index.php?"# "title="#{PercentEncode {StringX.replace Task " " "_"}}# "&action=raw" end   %% GetPage local Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} in fun {GetPage RawUrl} Url = {VirtualString.toString RawUrl} OutParams HttpResponseParams in {Client getService(Url ?OutParams ?HttpResponseParams)} OutParams.sOut end end   %% Parse local Parser = {New XMLParser.parser init} in fun {Parse Xs} {Parser parseVS(Xs $)} end end   fun {GetTitles Doc} CMs = Doc.2.1.children.1.children.1.children fun {Attributes element(attributes:As ...)} As end fun {IsTitle attribute(name:N ...)} N == title end in {Map {Filter {Flatten {Map CMs Attributes}} IsTitle} fun {$ A} {Atom.toString A.value} end} end   fun {PercentEncode Xs} case Xs of nil then nil [] X|Xr then if {Char.isDigit X} orelse {Member X [&- &_ &. &~]} orelse X >= &a andthen X =< &z orelse X >= &z andthen X =< &Z then X|{PercentEncode Xr} else {Append &%|{ToHex2 X} {PercentEncode Xr}} end end end   fun {ToHex2 X} [{ToHex1 X div 16} {ToHex1 X mod 16}] end   fun {ToHex1 X} if X >= 0 andthen X =< 9 then &0 + X elseif X >= 10 andthen X =< 15 then &A + X - 10 end end in {Main}
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
#Lisaac
Lisaac
+ haystack : ARRAY[STRING]; haystack := "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo".split; "Washington Bush".split.foreach { needle : STRING; haystack.has(needle).if { haystack.first_index_of(needle).print; ' '.print; needle.print; '\n'.print; } else { needle.print; " is not in haystack\n".print; }; };
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.
#Nim
Nim
import httpclient, json, re, strformat, strutils, algorithm   const LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json" CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"   type Rank = tuple[lang: string, count: int]   proc cmp(a, b: Rank): int = result = cmp(b.count, a.count) if result == 0: result = cmp(a.lang, b.lang)   proc add(langs: var seq[string]; fromJson: JsonNode) = for entry in fromJson{"query", "categorymembers"}: langs.add entry["title"].getStr.split("Category:")[1]   var client = newHttpClient() var langs: seq[string] var url = LangSite while true: let response = client.get(url) if response.status != $Http200: break let fromJson = response.body.parseJson() langs.add fromJson if "continue" notin fromJson: break let cmcont = fromJson{"continue", "cmcontinue"}.getStr let cont = fromJson{"continue", "continue"}.getStr url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"   var ranks: seq[Rank] for line in client.getContent(CatSite).findAll(regex): let lang = line.replacef(regex, "$1") if lang in langs: let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip()) ranks.add (lang, count)   ranks.sort(cmp) for i, rank in ranks: echo &"{i + 1:3} {rank.count:4} - {rank.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
#ALGOL_W
ALGOL W
BEGIN   PROCEDURE ROMAN (INTEGER VALUE NUMBER; STRING(15) RESULT CHARACTERS; INTEGER RESULT LENGTH); COMMENT Returns the Roman number of an integer between 1 and 3999. "MMMDCCCLXXXVIII" (15 characters long) is the longest Roman number under 4000; BEGIN INTEGER PLACE, POWER;   PROCEDURE APPEND (STRING(1) VALUE C); BEGIN CHARACTERS(LENGTH|1) := C; LENGTH := LENGTH + 1 END;   PROCEDURE I; APPEND(CASE PLACE OF ("I","X","C","M")); PROCEDURE V; APPEND(CASE PLACE OF ("V","L","D")); PROCEDURE X; APPEND(CASE PLACE OF ("X","C","M"));   ASSERT (NUMBER >= 1) AND (NUMBER < 4000);   CHARACTERS := " "; LENGTH := 0; POWER := 1000; PLACE := 4; WHILE PLACE > 0 DO BEGIN CASE NUMBER DIV POWER + 1 OF BEGIN BEGIN END; BEGIN I END; BEGIN I; I END; BEGIN I; I; I END; BEGIN I; V END; BEGIN V END; BEGIN V; I END; BEGIN V; I; I END; BEGIN V; I; I; I END; BEGIN I; X END END; NUMBER := NUMBER REM POWER; POWER := POWER DIV 10; PLACE := PLACE - 1 END END ROMAN;   INTEGER I; STRING(15) S;   ROMAN(1, S, I); WRITE(S, I); ROMAN(3999, S, I); WRITE(S, I); ROMAN(3888, S, I); WRITE(S, I); ROMAN(2009, S, I); WRITE(S, I); ROMAN(405, S, I); WRITE(S, I); 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.
#AppleScript
AppleScript
  ------------- INTEGER VALUE OF A ROMAN STRING ------------   -- romanValue :: String -> Int on romanValue(s) script roman property mapping : [["M", 1000], ["CM", 900], ["D", 500], ["CD", 400], ¬ ["C", 100], ["XC", 90], ["L", 50], ["XL", 40], ["X", 10], ["IX", 9], ¬ ["V", 5], ["IV", 4], ["I", 1]]   -- Value of first Roman glyph + value of remaining glyphs -- toArabic :: [Char] -> Int on toArabic(xs) -- transcribe :: (String, Number) -> Maybe (Number, [String]) script transcribe on |λ|(pair) set {r, v} to pair if isPrefixOf(characters of r, xs) then   -- Value of this matching glyph, with any remaining glyphs {v, drop(length of r, xs)} else {} end if end |λ| end script   if 0 < length of xs then set parsed to concatMap(transcribe, mapping) (item 1 of parsed) + toArabic(item 2 of parsed) else 0 end if end toArabic end script   toArabic(characters of s) of roman end romanValue   --------------------------- TEST ------------------------- on run map(romanValue, {"MCMXC", "MDCLXVI", "MMVIII"})   --> {1990, 1666, 2008} end run     -------------------- GENERIC FUNCTIONS -------------------   -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) set lng to length of xs set acc to {} tell mReturn(f) repeat with i from 1 to lng set acc to acc & (|λ|(item i of xs, i, xs)) end repeat end tell if {text, string} contains class of xs then acc as text else acc end if end concatMap     -- drop :: Int -> [a] -> [a] -- drop :: Int -> String -> String on drop(n, xs) set c to class of xs if script is not c then if string is not c then if n < length of xs then items (1 + n) thru -1 of xs else {} end if else if n < length of xs then text (1 + n) thru -1 of xs else "" end if end if else take(n, xs) -- consumed return xs end if end drop     -- isPrefixOf :: [a] -> [a] -> Bool -- isPrefixOf :: String -> String -> Bool on isPrefixOf(xs, ys) -- isPrefixOf takes two lists or strings and returns -- true if and only if the first is a prefix of the second. script go on |λ|(xs, ys) set intX to length of xs if intX < 1 then true else if intX > length of ys then false else if class of xs is string then (offset of xs in ys) = 1 else set {xxt, yyt} to {uncons(xs), uncons(ys)} ((item 1 of xxt) = (item 1 of yyt)) and ¬ |λ|(item 2 of xxt, item 2 of yyt) end if end |λ| end script go's |λ|(xs, ys) end isPrefixOf     -- length :: [a] -> Int on |length|(xs) set c to class of xs if list is c or string is c then length of xs else (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite) end if end |length|     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- uncons :: [a] -> Maybe (a, [a]) on uncons(xs) set lng to |length|(xs) if 0 = lng then missing value else if (2 ^ 29 - 1) as integer > lng then if class of xs is string then set cs to text items of xs {item 1 of cs, rest of cs} else {item 1 of xs, rest of xs} end if else set nxt to take(1, xs) if {} is nxt then missing value else {item 1 of nxt, xs} end if end if end if end uncons
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
#Common_Lisp
Common Lisp
(defun find-roots (function start end &optional (step 0.0001)) (let* ((roots '()) (value (funcall function start)) (plusp (plusp value))) (when (zerop value) (format t "~&Root found at ~W." start)) (do ((x (+ start step) (+ x step))) ((> x end) (nreverse roots)) (setf value (funcall function x)) (cond ((zerop value) (format t "~&Root found at ~w." x) (push x roots)) ((not (eql plusp (plusp value))) (format t "~&Root found near ~w." x) (push (cons (- x step) x) roots))) (setf plusp (plusp value)))))
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.
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   set choice1=rock set choice2=paper set choice3=scissors set freq1=0 set freq2=0 set freq3=0 set games=0 set won=0 set lost=0 set tie=0   :start cls echo Games - %games% : Won - %won% : Lost - %lost% : Ties - %tie% choice /c RPS /n /m "[R]ock, [P]aper or [S]cissors? "   set choice=%errorlevel% rem used [1,1000] as interval for random if %games% equ 0 ( rem at the beginning, there's no bias for each choice set /a "rocklimit=1000 / 3" set /a "scissorslimit=1000 * 2 / 3" ) else ( set /a "rocklimit=1000 * %freq3% / %games%" set /a "scissorslimit=1000 * (%freq1% + %freq3%) / %games%" ) set /a "randchoice=%random% %% 1000 + 1" set compchoice=2 if %randchoice% geq %scissorslimit% set compchoice=3 if %randchoice% leq %rocklimit% set compchoice=1   cls echo Player: !choice%choice%! ^|vs^| Computer: !choice%compchoice%! goto %compchoice%   :1 if %choice%==1 goto tie if %choice%==2 goto win if %choice%==3 goto loss   :2 if %choice%==1 goto loss if %choice%==2 goto tie if %choice%==3 goto win   :3 if %choice%==1 goto win if %choice%==2 goto loss if %choice%==3 goto tie   :win set /a "won+=1" echo Player wins^! goto end   :loss set /a "lost+=1" echo Computer Wins^! goto end   :tie set /a "tie+=1" echo Tie^! goto end   :end set /a "games+=1" set /a "freq%choice%+=1" pause goto start
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.
#E
E
def rle(string) { var seen := null var count := 0 var result := [] def put() { if (seen != null) { result with= [count, seen] } } for ch in string { if (ch != seen) { put() seen := ch count := 0 } count += 1 } put() return result }   def unrle(coded) { var result := "" for [count, ch] in coded { result += E.toString(ch) * count } return result }
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.
#JavaScript
JavaScript
function Root(angle) { with (Math) { this.r = cos(angle); this.i = sin(angle) } }   Root.prototype.toFixed = function(p) { return this.r.toFixed(p) + (this.i >= 0 ? '+' : '') + this.i.toFixed(p) + 'i' }   function roots(n) { var rs = [], teta = 2*Math.PI/n for (var angle=0, i=0; i<n; angle+=teta, i+=1) rs.push( new Root(angle) ) return rs }   for (var n=2; n<8; n+=1) { document.write(n, ': ') var rs=roots(n); for (var i=0; i<rs.length; i+=1) document.write( i ? ', ' : '', rs[i].toFixed(5) ) document.write('<br>') }  
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#REXX
REXX
/*REXX pgm finds and displays bare language (<lang>) tags without a language specified. */ parse arg iFID . /*obtain optional argument from the CL.*/ if iFID=='' | iFID="," then iFID= 'BARELANG.HTM' /*Not specified? Then assume default*/ call lineout iFID /*close the file, just in case its open*/ call linein ifid,1,0 /*point to the first record. */ noLa= 0; bare= 0; header=; heads= /*initialize various REXX variables. */ !.= 0 /*sparse array to hold language headers*/ do recs=0 while lines(iFID)\==0 /*read all lines in the input file. */ $= linein(iFID) /*read a line (record) from the input. */ $= space($) /*elide superfluous blanks from record.*/ if $=='' then iterate /*if a blank line, then skip any tests.*/ call testHead /*process possible ==((header|ααα}}== */ call testLang /* " " <lang ααα> or <lang>*/ end /*recs*/   call lineout iFID /*close the file, just in case its open*/ say recs ' records read from file: ' iFID; say /*show number of records read from file*/ if bare==0 then bare= 'no'; say right(bare, 9) " bare language tags."; say   do #=1 for words(head); _= word(head, #) /*maybe show <lang> for language ααα */ if !._\==0 then say right(!._, 9) ' in' _ /*show the count for a particular lang.*/ end /*#*/   if noLa==0 then noLa= 'no'; say right(noLa, 9) " in no specified language." exit 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ testHead: @head= '=={{header|'; @foot= "}}==" /*define two literals. */ hh= pos(@head, $ ); if hh==0 then return /*get start of literal.*/ or= hh + length(@head) - 1 /*get position of | */ hb= pos(@foot, $, or); if hb==0 then return /*get position of foot.*/ head= substr($, or+1, hb-or-1) /*get the language name*/ if head\=='' then header= head /*Header? Then use it.*/ if wordpos(head, heads)==0 then heads= heads head /*Is lang? Add──► list*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ testLang: @lang= '<lang'; @back= ">" /*define two literals. */ s1= pos(@lang, $ ); if s1==0 then return /*get start of literal.*/ gt= pos(@back, $, s1+1) /*get position of < */ lang= strip( substr($, gt-2, gt-length(@lang) -1 ) ) /*get the language name*/ if lang=='' then bare= bare + 1 /*No lang? Bump bares.*/ else @lang= lang /*Is lang? Set lang. */ if @lang\=='' & header=='' then noLa= noLa + 1 /*bump noLang counter.*/ if @lang\=='' & header\=='' then !.head= !.head + 1 /*bump a lang " */ return
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.
#jq
jq
# If there are infinitely many solutions, emit true; # if none, emit empty; # otherwise always emit two. # For numerical accuracy, Middlebrook's approach is adopted: def quadratic_roots(a; b; c): if a == 0 and b == 0 then if c == 0 then true # infinitely many else empty # none end elif a == 0 then [-c/b, 0] elif b == 0 then (complex_sqrt(1/a) | (., negate(.))) else divide( plus(1.0; complex_sqrt( minus(1.0; (4 * a * c / (b*b))))); 2) as $f | negate(divide(multiply(b; $f); a)), negate(divide(c; multiply(b; $f))) 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
#CLU
CLU
rot13 = proc (c: char) returns (char) base: int letter: bool := false if c>='A' & c<='Z' then base := char$c2i('A') letter := true elseif c>='a' & c<='z' then base := char$c2i('a') letter := true end if ~letter then return(c) end return(char$i2c((char$c2i(c)-base+13)//26+base)) end rot13   start_up = proc () po: stream := stream$primary_output() pi: stream := stream$primary_input() while true do stream$putc(po,rot13(stream$getc(pi))) except when end_of_file: break end end end start_up
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#PARI.2FGP
PARI/GP
rk4(f,dx,x,y)={ my(k1=dx*f(x,y), k2=dx*f(x+dx/2,y+k1/2), k3=dx*f(x+dx/2,y+k2/2), k4=dx*f(x+dx,y+k3)); y + (k1 + 2*k2 + 2*k3 + k4) / 6 }; rate(x,y)=x*sqrt(y); go()={ my(x0=0,x1=10,dx=.1,n=1+(x1-x0)\dx,y=vector(n)); y[1]=1; for(i=2,n,y[i]=rk4(rate, dx, x0 + dx * (i - 1), y[i-1])); print("x\ty\trel. err.\n------------"); forstep(i=1,n,10, my(x=x0+dx*i,y2=(x^2/4+1)^2); print(x "\t" y[i] "\t" y[i]/y2 - 1) ) }; go()
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Scala
Scala
libraryDependencies ++= Seq( "org.json4s"%%"json4s-native"%"3.6.0", "com.softwaremill.sttp"%%"core"%"1.5.11", "com.softwaremill.sttp"%%"json4s"%"1.5.11")
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Tcl
Tcl
package require Tcl 8.5 package require http package require json package require struct::set   fconfigure stdout -buffering none   # Initialize a cache of lookups array set cache {} proc log msg { #puts -nonewline $msg }   proc get_tasks {category} { global cache if {[info exists cache($category)]} { return $cache($category) } set base_url http://www.rosettacode.org/mw/api.php set query { action query list categorymembers cmtitle Category:%s format json cmlimit 500 } set query [list {*}$query]; # remove excess whitespace set this_query [dict create {*}[split [format $query $category]]] set tasks [list]   while {1} { set url [join [list $base_url [http::formatQuery {*}$this_query]] ?] while 1 { set response [http::geturl $url] # Process redirects if {[http::ncode $response] == 301} { set newurl [dict get [http::meta $response] Location] if {[string match http://* $newurl]} { set url $newurl } else { set url [regexp -inline {http://[^/]+} $url] append url $newurl } continue } # Check for oopsies! if { [set s [http::status $response]] ne "ok" || [http::ncode $response] != 200 } then { error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" } break }   # Get the data out of the message set data [json::json2dict [http::data $response]] http::cleanup $response   # add tasks to list foreach task [dict get $data query categorymembers] { lappend tasks [dict get [dict create {*}$task] title] }   if {[catch { dict get $data query-continue categorymembers cmcontinue } continue_task]} then { # no more continuations, we're done break } dict set this_query cmcontinue $continue_task } return [set cache($category) $tasks] }   proc get_unimplemented {lang} { set tasks [get_tasks Programming_Tasks] set collected [get_tasks Collection_Members] set doneTasks [get_tasks $lang] set omittedTasks [get_tasks $lang/Omit]   # Map generic collection task categories to specific ones set tasks [regsub -all {Category:(\S+)} $tasks "\\1/$lang"]   set collectOfLang [struct::set intersect $collected $doneTasks] set ignorable [struct::set union $doneTasks $omittedTasks $collectOfLang] set unimplemented [struct::set difference $tasks $ignorable]   puts "\n$lang has [llength $unimplemented] unimplemented programming tasks:" if {[llength $unimplemented]} { puts " [join [lsort $unimplemented] "\n "]" } }   catch {console show} catch {wm withdraw .} foreach lang {Perl Python Ruby Tcl} { get_unimplemented $lang }
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#Potion
Potion
isdigit = (c): 47 < c ord and c ord < 58. iswhitespace = (c): c ord == 10 or c ord == 13 or c == " ".   # str: a string of the form "...<nondigit>[{<symb>}]..." # i: index to start at (must be the index of <nondigit>) # => returns (<the symbol as a string>, <index after the last char>) parsesymbol = (str, i) : datum = () while (str(i) != "(" and str(i) != ")" and not iswhitespace(str(i)) and str(i) != "\"") : datum append(str(i++)) . (datum join, i) .   # str: a string of the form "...[<minus>]{<digit>}[<dot>{<digit>}]..." # i: index to start at (must be the index of the first token) # => returns (<float or int>, <index after the last digit>) parsenumber = (str, i) : datum = () dot = false while (str(i) != "(" and str(i) != ")" and not iswhitespace(str(i)) and str(i) != "\"") : if (str(i) == "."): dot = true. datum append(str(i++)) . if (dot): (datum join number, i). else: (datum join number integer, i). .   # str: a string of the form "...\"....\"..." # i: index to start at (must be the index of the first quote) # => returns (<the string>, <index after the last quote>) parsestring = (str, i) : datum = ("\"") while (str(++i) != "\"") : datum append(str(i)) . datum append("\"") (datum join, ++i) .   # str: a string of the form "...(...)..." # i: index to start at # => returns (<tuple/list>, <index after the last paren>) parselist = (str, i) : lst = () data = () while (str(i) != "("): i++. i++ while (str(i) != ")") : if (not iswhitespace(str(i))) : if (isdigit(str(i)) or (str(i) == "-" and isdigit(str(i + 1)))): data = parsenumber(str, i). elsif (str(i) == "\""): data = parsestring(str, i). elsif (str(i) == "("): data = parselist(str, i). else: data = parsesymbol(str, i). lst append(data(0)) i = data(1) . else : ++i . . (lst, ++i) .   parsesexpr = (str) : parselist(str, 0)(0) .   parsesexpr("(define (factorial x) \"compute factorial\" (version 2.0) (apply * (range 1 x)))") string print "\n" print parsesexpr("((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))") string print "\n" print
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#Plain_English
Plain English
To add an attribute to some stats: Allocate memory for an entry. Put the attribute into the entry's attribute. Append the entry to the stats.   An attribute is a number.   An entry is a thing with an attribute.   To find a count of attributes greater than fourteen in some stats: Put 0 into the count. Get an entry from the stats. Loop. If the entry is nil, exit. If the entry's attribute is greater than 14, bump the count. Put the entry's next into the entry. Repeat.   To find a sum of some stats: Put 0 into the sum. Get an entry from the stats. Loop. If the entry is nil, exit. Add the entry's attribute to the sum. Put the entry's next into the entry. Repeat.   To generate an attribute: Put 0 into the attribute. Put 6 into a minimum number. Loop. If a counter is past 4, break. Pick a number between 1 and 6. Add the number to the attribute. If the number is less than the minimum, put the number into the minimum. Repeat. Subtract the minimum from the attribute.   To generate some stats (raw): If a counter is past 6, exit. Generate an attribute. Add the attribute to the stats. Repeat.   To generate some stats (valid): Generate some raw stats (raw). Find a sum of the raw stats. If the sum is less than 75, destroy the raw stats; repeat. Find a count of attributes greater than fourteen in the raw stats. If the count is less than 2, destroy the raw stats; repeat. Put the raw stats into the stats.   To run: Start up. Show some RPG attributes. Wait for the escape key. Shut down.   To show some RPG attributes: Generate some stats (valid). Find a sum of the stats. Find a count of attributes greater than fourteen in the stats. Write the stats on the console. Destroy the stats. Write "Total: " then the sum on the console. Write "Number of stats greater than fourteen: " then the count on the console.   Some stats are some entries.   A sum is a number.   To write some stats on the console: Get an entry from the stats. Loop. If the entry is nil, write "" on the console; exit. Convert the entry's attribute to a string. Write the string on the console without advancing. If the entry's next is not nil, write ", " on the console without advancing. Put the entry's next into the entry. Repeat.
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
#Smalltalk
Smalltalk
| potentialPrimes limit | limit := 100. potentialPrimes := Array new: limit. potentialPrimes atAllPut: true. 2 to: limit sqrt do: [:testNumber | (potentialPrimes at: testNumber) ifTrue: [ (testNumber * 2) to: limit by: testNumber do: [:nonPrime | potentialPrimes at: nonPrime put: false ] ] ]. 2 to: limit do: [:testNumber | (potentialPrimes at: testNumber) ifTrue: [ Transcript show: testNumber asString; cr ] ]
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Perl
Perl
use HTTP::Tiny;   my $site = "http://rosettacode.org"; my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";   my $response = HTTP::Tiny->new->get("$site$list_url"); for ($response->{content} =~ /cm.*?title="(.*?)"/g) { (my $slug = $_) =~ tr/ /_/; my $response = HTTP::Tiny->new->get("$site/wiki/$slug"); my $count = () = $response->{content} =~ /toclevel-1/g; print "$_: $count examples\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
#Logo
Logo
to indexof :item :list if empty? :list [(throw "NOTFOUND 0)] if equal? :item first :list [output 1] output 1 + indexof :item butfirst :list end   to showindex :item :list make "i catch "NOTFOUND [indexof :item :list] ifelse :i = 0 [(print :item [ not found in ] :list)] [(print :item [ found at position ] :i [ in ] :list)] end   showindex "dog [My dog has fleas]  ; dog found at position 2 in My dog has fleas showindex "cat [My dog has fleas]  ; cat not found in My dog has fleas
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
#Lua
Lua
list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} --contents of my desk   item = io.read()   for i,v in ipairs(list) if v == item then print(i) end end
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.
#Objeck
Objeck
use HTTP; use RegEx; use XML; use Collection;   class RosettaRank { function : Main(args : String[]) ~ Nil { langs_xml := ""; client := HttpClient->New(); in := client->Get("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=5000&format=xml"); each(i : in) { langs_xml += in->Get(i)->As(String); };   langs := StringSet->New(); parser := XmlParser->New(langs_xml); if(parser->Parse()) { # get first item results := parser->FindElements("/api/query/categorymembers/cm"); each(i : results) { element := results->Get(i)->As(XmlElement); name := element->GetAttribute("title")->GetValue(); offset := name->Find(':'); if(offset > -1) { lang := name->SubString(offset + 1, name->Size() - offset - 1); langs->Insert(lang->ReplaceAll("&#x20;", " ")); }; }; };   langs_counts := IntMap->New(); client := HttpClient->New(); html := client->Get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); each(i : html) { lines := html->Get(i)->As(String); html_elements := lines->Split("\n"); each(j : html_elements) { element := html_elements[j]; name : String; count : String; regex := RegEx->New("<li><a href=\"(\\w|\\s|/|\\?|\\&|;|:|#)+\"\\stitle=\"Category:(\\w|\\s|#)+\">"); found := regex->FindFirst(element); if(found <> Nil) { group1 := found->Size(); regex := RegEx->New("(\\w|\\s)+"); found := regex->Match(element, group1); if(found <> Nil & found->Size() > 0) { name := found; # skip over some junk characters group2 := group1 + found->Size() + 10; regex := RegEx->New("\\s\\("); found := regex->Match(element, group2); if(found <> Nil) { group3 := group2 + found->Size(); regex := RegEx->New("\\d+"); found := regex->Match(element, group3); if(found <> Nil & found->Size() > 0) { count := found; }; }; }; };   if(name <> Nil & count <> Nil) { if(langs->Has(name)) { langs_counts->Insert(count->ToInt(), name); }; name := Nil; count := Nil; }; }; };   keys := langs_counts->GetKeys(); count := 1; for(i := keys->Size() - 1; i >= 0; i -=1;) { key := keys->Get(i); IO.Console->Print(count)->Print(". ")->Print(key)->Print(" - ")->PrintLine(langs_counts->Find(key)->As(String)); count += 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
#APL
APL
toRoman←{ ⍝ Digits and corresponding values ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I' vs←1000, ,100 10 1∘.×9 5 4 1 ⍝ Input ≤ 0 is invalid ⍵≤0:⎕SIGNAL 11 { 0=d←⊃⍸vs≤⍵:⍬ ⍝ Find highest digit in number (d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number }⍵ }
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.
#Applesoft_BASIC
Applesoft BASIC
10 LET R$ = "MCMXCIX" 20 GOSUB 100 PRINT "ROMAN NUMERALS DECODED" 30 LET R$ = "MMXII" 40 GOSUB 100 50 LET R$ = "MDCLXVI" 60 GOSUB 100 70 LET R$ = "MMMDCCCLXXXVIII" 80 GOSUB 100 90 END 100 PRINT M$R$, 110 LET M$ = CHR$ (13) 120 GOSUB 150"ROMAN NUMERALS DECODE given R$" 130 PRINT N; 140 RETURN 150 IF NOT C THEN GOSUB 250INITIALIZE 160 LET J = 0 170 LET N = 0 180 FOR I = LEN (R$) TO 1 STEP - 1 190 LET P = J 200 FOR J = 1 TO C 210 IF MID$ (C$,J,1) < > MID$ (R$,I,1) THEN NEXT J 220 IF J < = C THEN N = N + R(J) * ((J > = P) * 2 - 1) 230 NEXT I 240 RETURN 250 READ C$ 260 LET C = LEN (C$) 270 DIM R(C) 280 FOR I = 0 TO C 290 READ R(I) 300 NEXT I 310 RETURN 320 DATA "IVXLCDM",0,1,5,10,50,100,500,1000
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
#D
D
import std.stdio, std.math, std.algorithm;   bool nearZero(T)(in T a, in T b = T.epsilon * 4) pure nothrow { return abs(a) <= b; }   T[] findRoot(T)(immutable T function(in T) pure nothrow fi, in T start, in T end, in T step=T(0.001L), T tolerance = T(1e-4L)) { if (step.nearZero) writefln("WARNING: step size may be too small.");   /// Search root by simple bisection. T searchRoot(T a, T b) pure nothrow { T root; int limit = 49; T gap = b - a;   while (!nearZero(gap) && limit--) { if (fi(a).nearZero) return a; if (fi(b).nearZero) return b; root = (b + a) / 2.0L; if (fi(root).nearZero) return root; ((fi(a) * fi(root) < 0) ? b : a) = root; gap = b - a; }   return root; }   immutable dir = T(end > start ? 1.0 : -1.0); immutable step2 = (end > start) ? abs(step) : -abs(step); T[T] result; for (T x = start; (x * dir) <= (end * dir); x += step2) if (fi(x) * fi(x + step2) <= 0) { immutable T r = searchRoot(x, x + step2); result[r] = fi(r); }   return result.keys.sort().release; }   void report(T)(in T[] r, immutable T function(in T) pure f, in T tolerance = T(1e-4L)) { if (r.length) { writefln("Root found (tolerance = %1.4g):", tolerance);   foreach (const x; r) { immutable T y = f(x);   if (nearZero(y)) writefln("... EXACTLY at %+1.20f, f(x) = %+1.4g",x,y); else if (nearZero(y, tolerance)) writefln(".... MAY-BE at %+1.20f, f(x) = %+1.4g",x,y); else writefln("Verify needed, f(%1.4g) = " ~ "%1.4g > tolerance in magnitude", x, y); } } else writefln("No root found."); }   void main() { static real f(in real x) pure nothrow { return x ^^ 3 - (3 * x ^^ 2) + 2 * x; }   findRoot(&f, -1.0L, 3.0L, 0.001L).report(&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.
#BBC_BASIC
BBC BASIC
PRINT"Welcome to the game of rock-paper-scissors" PRINT "Each player guesses one of these three, and reveals it at the same time." PRINT "Rock blunts scissors, which cut paper, which wraps stone." PRINT "If both players choose the same, it is a draw!" PRINT "When you've had enough, choose Q." DIM rps%(2),g$(3) g$()="rock","paper","scissors" total%=0 draw%=0 pwin%=0 cwin%=0 c%=RND(3) PRINT"What is your move (press R, P, or S)?" REPEAT REPEAT q$=GET$ UNTIL INSTR("RPSrpsQq",q$)>0 g%=(INSTR("RrPpSsQq",q$)-1) DIV 2 IF g%>2 THEN PROCsummarise:END total%+=1 rps%(g%)+=1 PRINT"You chose ";g$(g%);" and I chose ";g$(c%); CASE g%-c% OF WHEN 0: PRINT ". It's a draw" draw%+=1 WHEN 1,-2: PRINT ". You win!" pwin%+=1 WHEN -1,2: PRINT ". I win!" cwin%+=1 ENDCASE c%=FNmove(rps%(),total%) UNTIL FALSE END : DEFPROCsummarise PRINT "You won ";pwin%;", and I won ";cwin%;". There were ";draw%;" draws" PRINT "Thanks for playing!" ENDPROC : DEFFNmove(p%(),t%) LOCAL r% r%=RND(total%) IF r%<=p%(0) THEN =1 IF r%<=p%(0)+p%(1) THEN =2 =0
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.
#Elena
Elena
import system'text; import system'routines; import extensions; import extensions'text;   singleton compressor { string compress(string s) { auto tb := new TextBuilder(); int count := 0; char current := s[0]; s.forEach:(ch) { if (ch == current) { count += 1 } else { tb.writeFormatted("{0}{1}",count,current); count := 1; current := ch } };   tb.writeFormatted("{0}{1}",count,current);   ^ tb }   string decompress(string s) { auto tb := new TextBuilder(); char current := $0; var a := new StringWriter(); s.forEach:(ch) { current := ch; if (current.isDigit()) { a.append(ch) } else { int count := a.toInt(); a.clear();   tb.fill(current,count) } };   ^ tb } }   public program() { var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";   s := compressor.compress(s); console.printLine(s);   s := compressor.decompress(s); console.printLine(s) }
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.
#jq
jq
def nthroots(n): (8 * (1|atan)) as $twopi | range(0;n) | (($twopi * .) / n) as $angle | [ ($angle | cos), ($angle | sin) ];   nthroots(10)
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.
#Julia
Julia
nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ]
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Ruby
Ruby
require "open-uri" require "cgi"   tasks = ["Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"] part_uri = "http://rosettacode.org/wiki?action=raw&title=" Report = Struct.new(:count, :tasks) result = Hash.new{|h,k| h[k] = Report.new(0, [])}   tasks.each do |task| puts "processing #{task}" current_lang = "no language" open(part_uri + CGI.escape(task)).each_line do |line| current_lang = Regexp.last_match["lang"] if /==\{\{header\|(?<lang>.+)\}\}==/ =~ line num_no_langs = line.scan(/<lang\s*>/).size if num_no_langs > 0 then result[current_lang].count += num_no_langs result[current_lang].tasks << task end end end   puts "\n#{result.values.map(&:count).inject(&:+)} bare language tags.\n\n" result.each{|k,v| puts "#{v.count} in #{k} (#{v.tasks})"}
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.
#Julia
Julia
using Printf   function quadroots(x::Real, y::Real, z::Real) a, b, c = promote(float(x), y, z) if a ≈ 0.0 return [-c / b] end Δ = b ^ 2 - 4a * c if Δ ≈ 0.0 return [-sqrt(c / a)] end if Δ < 0.0 Δ = complex(Δ) end d = sqrt(Δ) if b < 0.0 d -= b return [d / 2a, 2c / d] else d = -d - b return [2c / d, d / 2a] end end   a = [1, 1, 1.0, 10] b = [10, 2, -10.0 ^ 9, 1] c = [1, 1, 1, 1]   for (x, y, z) in zip(a, b, c) @printf "The roots of %.2fx² + %.2fx + %.2f\n\tx₀ = (%s)\n" x y z join(round.(quadroots(x, y, z), 2), ", ") end
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.
#Kotlin
Kotlin
import java.lang.Math.*   data class Equation(val a: Double, val b: Double, val c: Double) { data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> "${i}i" else -> "$r + ${i}i" } }   data class Solution(val x1: Any, val x2: Any) { override fun toString() = when(x1) { x2 -> "X1,2 = $x1" else -> "X1 = $x1, X2 = $x2" } }   val quadraticRoots by lazy { val _2a = a + a val d = b * b - 4.0 * a * c // discriminant if (d < 0.0) { val r = -b / _2a val i = sqrt(-d) / _2a Solution(Complex(r, i), Complex(r, -i)) } else { // avoid calculating -b +/- sqrt(d), to avoid any // subtractive cancellation when it is near zero. val r = if (b < 0.0) (-b + sqrt(d)) / _2a else (-b - sqrt(d)) / _2a Solution(r, c / (a * r)) } } }   fun main(args: Array<String>) { val equations = listOf(Equation(1.0, 22.0, -1323.0), // two distinct real roots Equation(6.0, -23.0, 20.0), // with a != 1.0 Equation(1.0, -1.0e9, 1.0), // with one root near zero Equation(1.0, 2.0, 1.0), // one real root (double root) Equation(1.0, 0.0, 1.0), // two imaginary roots Equation(1.0, 1.0, 1.0)) // two complex roots   equations.forEach { println("$it\n" + it.quadraticRoots) } }
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. rot-13.   DATA DIVISION. LOCAL-STORAGE SECTION. 78 STR-LENGTH VALUE 100.   78 normal-lower VALUE "abcdefghijklmnopqrstuvwxyz". 78 rot13-lower VALUE "nopqrstuvwxyzabcdefghijklm".   78 normal-upper VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". 78 rot13-upper VALUE "NOPQRSTUVWXYZABCDEFGHIJKLM".   LINKAGE SECTION. 01 in-str PIC X(STR-LENGTH). 01 out-str PIC X(STR-LENGTH).   PROCEDURE DIVISION USING VALUE in-str, REFERENCE out-str. MOVE in-str TO out-str   INSPECT out-str CONVERTING normal-lower TO rot13-lower INSPECT out-str CONVERTING normal-upper TO rot13-upper   GOBACK .
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#Pascal
Pascal
program RungeKuttaExample;   uses sysutils;   type TDerivative = function (t, y : Real) : Real;   procedure RungeKutta(yDer : TDerivative; var t, y : array of Real; dt : Real); var dy1, dy2, dy3, dy4 : Real; idx : Cardinal;   begin for idx := Low(t) to High(t) - 1 do begin dy1 := dt * yDer(t[idx], y[idx]); dy2 := dt * yDer(t[idx] + dt / 2.0, y[idx] + dy1 / 2.0); dy3 := dt * yDer(t[idx] + dt / 2.0, y[idx] + dy2 / 2.0); dy4 := dt * yDer(t[idx] + dt, y[idx] + dy3);   t[idx + 1] := t[idx] + dt; y[idx + 1] := y[idx] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; end; end;   function CalcError(t, y : Real) : Real; var trueVal : Real;   begin trueVal := sqr(sqr(t) + 4.0) / 16.0; CalcError := abs(trueVal - y); end;   procedure Print(t, y : array of Real; modnum : Integer); var idx : Cardinal;   begin for idx := Low(t) to High(t) do begin if idx mod modnum = 0 then begin WriteLn(Format('y(%4.1f) = %12.8f Error: %12.6e', [t[idx], y[idx], CalcError(t[idx], y[idx])])); end; end; end;   function YPrime(t, y : Real) : Real; begin YPrime := t * sqrt(y); end;   const dt = 0.10; N = 100;   var tArr, yArr : array [0..N] of Real;   begin tArr[0] := 0.0; yArr[0] := 1.0;   RungeKutta(@YPrime, tArr, yArr, dt); Print(tArr, yArr, 10); end.
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Wren
Wren
/* rc_find_unimplemented_tasks.wren */   import "./pattern" for Pattern   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 p1 = Pattern.new("title/=\"[+1^\"]\"") var p2 = Pattern.new("cmcontinue/=\"[+1^\"]\"")   var findTasks = Fn.new { |category| var url = "https://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:%(category)&cmlimit=500&format=xml" var cmcontinue = "" var tasks = [] while (true) { var content = getContent.call(url + cmcontinue) var matches1 = p1.findAll(content) for (m in matches1) { var title = m.capsText[0].replace("&#039;", "'").replace("&quot;", "\"") tasks.add(title) } var m2 = p2.find(content) if (m2) cmcontinue = "&cmcontinue=%(m2.capsText[0])" else break } return tasks }   var tasks1 = findTasks.call("Programming_Tasks") // 'full' tasks only var tasks2 = findTasks.call("Draft_Programming_Tasks") var lang = "Wren" var langTasks = findTasks.call(lang) // includes draft tasks curl.easyCleanup() System.print("Unimplemented 'full' tasks in %(lang):") for (task in tasks1) { if (!langTasks.contains(task)) System.print(" " + task) } System.print("\nUnimplemented 'draft' tasks in %(lang):") for (task in tasks2) { if (!langTasks.contains(task)) System.print(" " + task) }
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#Python
Python
import re   dbg = False   term_regex = r'''(?mx) \s*(?: (?P<brackl>\()| (?P<brackr>\))| (?P<num>\-?\d+\.\d+|\-?\d+)| (?P<sq>"[^"]*")| (?P<s>[^(^)\s]+) )'''   def parse_sexp(sexp): stack = [] out = [] if dbg: print("%-6s %-14s %-44s %-s" % tuple("term value out stack".split())) for termtypes in re.finditer(term_regex, sexp): term, value = [(t,v) for t,v in termtypes.groupdict().items() if v][0] if dbg: print("%-7s %-14s %-44r %-r" % (term, value, out, stack)) if term == 'brackl': stack.append(out) out = [] elif term == 'brackr': assert stack, "Trouble with nesting of brackets" tmpout, out = out, stack.pop(-1) out.append(tmpout) elif term == 'num': v = float(value) if v.is_integer(): v = int(v) out.append(v) elif term == 'sq': out.append(value[1:-1]) elif term == 's': out.append(value) else: raise NotImplementedError("Error: %r" % (term, value)) assert not stack, "Trouble with nesting of brackets" return out[0]   def print_sexp(exp): out = '' if type(exp) == type([]): out += '(' + ' '.join(print_sexp(x) for x in exp) + ')' elif type(exp) == type('') and re.search(r'[\s()]', exp): out += '"%s"' % repr(exp)[1:-1].replace('"', '\"') else: out += '%s' % exp return out     if __name__ == '__main__': sexp = ''' ( ( data "quoted data" 123 4.5) (data (123 (4.5) "(more" "data)")))'''   print('Input S-expression: %r' % (sexp, )) parsed = parse_sexp(sexp) print("\nParsed to Python:", parsed)   print("\nThen back to: '%s'" % print_sexp(parsed))
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#PureBasic
PureBasic
#heroicAttributeMinimum = 15 #heroicAttributeCountMinimum = 2 #attributeSumMinimum = 75 #attributeCount = 6   Procedure roll_attribute() Protected i, sum Dim rolls(3)   For i = 0 To 3 rolls(i) = Random(6, 1) Next i   ;sum the highest three rolls SortArray(rolls(), #PB_Sort_Descending) For i = 0 To 2 sum + rolls(i) Next ProcedureReturn sum EndProcedure   Procedure displayAttributes(List attributes(), sum, heroicCount) Protected output$   output$ = "Attributes generated: [" ForEach attributes() output$ + attributes() If ListIndex(attributes()) <> #attributeCount - 1: output$ + ", ": EndIf Next output$ + "]" PrintN(output$) PrintN("Total: " + sum + ", Values " + #heroicAttributeMinimum + " or above: " + heroicCount) EndProcedure   Procedure Gen_attributes() Protected i, attributesSum, heroicAttributesCount   NewList attributes() Repeat ClearList(attributes()) attributesSum = 0: heroicAttributesCount = 0 For i = 1 To #attributeCount AddElement(attributes()) attributes() = roll_attribute() attributesSum + attributes() heroicAttributesCount + Bool(attributes() >= #heroicAttributeMinimum) Next Until attributesSum >= #attributeSumMinimum And heroicAttributesCount >= #heroicAttributeCountMinimum   displayAttributes(attributes(), attributesSum, heroicAttributesCount) EndProcedure   If OpenConsole("RPG Attributes Generator") Gen_attributes() Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#SNOBOL4
SNOBOL4
define('sieve(n)i,j,k,p,str,res') :(sieve_end) sieve i = lt(i,n - 1) i + 1 :f(sv1) str = str (i + 1) ' ' :(sieve) sv1 str break(' ') . j span(' ') = :f(return) sieve = sieve j ' ' sieve = gt(j ^ 2,n) sieve str :s(return) ;* Opt1 res = '' str (arb ' ') @p ((j ^ 2) ' ') ;* Opt2 str len(p) . res = ;* Opt2 sv2 str break(' ') . k span(' ') = :f(sv3) res = ne(remdr(k,j),0) res k ' ' :(sv2) sv3 str = res :(sv1) sieve_end   * # Test and display output = sieve(100) end
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#Phix
Phix
-- -- demo\rosetta\rosettacode_cache.e -- ================================ -- -- Common routines for handling rc_cache etc. -- without js -- (libcurl, file i/o, peek, progress..) include builtins\timedate.e constant day = timedelta(days:=1) integer refresh_cache = 21*day -- 0 for always [NB refresh_cache += timedelta(days:=1) below] function days(atom delta) integer d = ceil(delta/day) return sprintf("%d day%s",{d,iff(d=1?"":"s")}) end function constant {hex,ascii} = columnize({{"%22",`"`}, {"%27","'"}, {"%2A","*"}, {"%2B","+"}, {"%3A",":"}, {"%5E",`^`}, {"%E2%80%93","-"}, {"%E2%80%99","'"}, {"%C3%A8","e"}, {"%C3%A9","e"}, {"%C3%B6","o"}, {"%C5%91","o"}, {""",`"`}, {"'","'"}, {"_"," "}}) global function html_clean(string s) return substitute_all(s,hex,ascii) end function include builtins\libcurl.e atom curl = NULL, pErrorBuffer function write_callback(atom pData, integer size, nmemb, fn) integer bytes_written = size * nmemb puts(fn,peek({pData,bytes_written})) return bytes_written end function constant write_cb = call_back({'+', write_callback}) global string wastitle = "" -- don't clobber "NEED EDITING"/Downloading messages global integer show_title = progress global function open_download(string filename, url, integer i=0, n=0) object text bool refetch = false string why = "not found" filename = join_path({"rc_cache",filename}) if file_exists(filename) then -- use existing file if <= refresh_cache days old sequence last_mod = get_file_date(filename) atom delta = timedate_diff(last_mod,date()) refetch = true if delta>refresh_cache and not match(".hist",filename) then why = days(delta) & " > " & days(refresh_cache) elsif get_file_size(filename)=0 then why = "filesize of 0" else text = trim(get_text(filename)) if not sequence(text) then why = "no text" elsif length(text)<10 then why = "<10 bytes" else refetch = false end if end if else refetch = true string directory = get_file_path(filename) if get_file_type(directory)!=FILETYPE_DIRECTORY then if not create_directory(directory,make_parent:=true) then crash("cannot create %s directory",{directory}) end if end if end if if refetch then wastitle = "x" -- don't clobber string nofn = iff(n?sprintf("(%d/%d, %.1f%%) ",{i,n,i/n*100}):""), title = sprintf("Downloading %s%s (%s)...",{nofn,html_clean(filename),why}) show_title(title) if curl=NULL then curl_global_init() curl = curl_easy_init() pErrorBuffer = allocate(CURL_ERROR_SIZE) curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pErrorBuffer) curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb) end if url = substitute(url,"%3A",":") url = substitute(url,"%2A","*") curl_easy_setopt(curl, CURLOPT_URL, url) integer fn = open(filename,"wb") assert(fn!=-1,"cannot open "&filename) curl_easy_setopt(curl, CURLOPT_WRITEDATA, fn) while true do CURLcode res = curl_easy_perform(curl) if res=CURLE_OK then exit end if string error = sprintf("%d",res) if res=CURLE_COULDNT_RESOLVE_HOST then error &= " [CURLE_COULDNT_RESOLVE_HOST]" end if progress("Error %s downloading file, retry?(Y/N):",{error}) if lower(wait_key())!='y' then abort(0) end if printf(1,"Y\n") end while close(fn) refresh_cache += timedelta(days:=1) -- did I mention it is slow? text = get_text(filename) end if return text end function global function open_category(string filename, integer i=0, n=0) return open_download(filename&".htm","http://rosettacode.org/wiki/Category:"&filename,i,n) end function global function dewiki(string s, sequence exclude={}) -- extract tasks from eg `<li><a href="/wiki/100_doors"` sequence tasks = {} integer start = 1, finish = match(`<div class="printfooter">`,s) s = s[1..finish-1] while true do start = match(`<li><a href="/wiki/`,s,start) if start=0 then exit end if start += length(`<li><a href="/wiki/`) finish = find('"',s,start) string task = s[start..finish-1] task = substitute_all(task,{"*",":"},{"%2A","%3A"}) tasks = append(tasks,task) start = finish+1 end while return tasks end function global procedure curl_cleanup() if curl!=NULL then curl_easy_cleanup(curl) free(pErrorBuffer) curl = NULL pErrorBuffer = NULL end if end procedure
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Flush ' empty stack Inventory Queue Haystack= "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt" Append Haystack, "foo", "bar", "bletch", "foo", "bar", "fum", "fred", "jim", "sheila", "barney", "flarp", "zxc" Append Haystack, "spqr", "wombat", "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", "bar" Append Haystack, "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", "pluto", "paperino", "aap" Append Haystack, "noot", "mies", "oogle", "foogle", "boogle", "zork", "gork", "bork" \\ Inventories are objects and we have access to properties using COM model With HayStack, "index" as index Inventory Queue HayStackRev N=Each(HayStack, -1, 1) While N { Append HayStackRev, Eval$(N, N^) } With HayStackRev, "index" as indexRev Print Len(HayStack) Print Len(HayStackRev) local needle$ \\ Print all elements using columns Print haystack Repeat { Input "Word to search for? (Leave blank to exit) ", needle$ If needle$ <> "" Then { If Exist(haystackrev,lcase$(needle$) ) Then { Print "Found "; CHR$(34); needle$; CHR$(34); " at index "; STR$(len(haystackrev)-indexrev,"")   If Exist(haystack,lcase$(needle$) ) Then { if len(haystackrev)-1<>indexrev+index then { Print "Found "; CHR$(34); needle$; CHR$(34); " at index "; STR$(Len(haystack)-index,"") } } } Else Print CHR$(34); needle$; CHR$(34); " not found" } Else Exit } Always } CheckIt  
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.
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * Create a list of Rosetta Code languages showing the number of tasks * This program's logic is basically that of the REXX program * rearranged to my taste and utilizing the array class of ooRexx * which offers a neat way of sorting as desired, see :CLASS mycmp below * For the input to this program open these links: * http://rosettacode.org/wiki/Category:Programming_Languages * http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000 * and save the pages as LAN.txt and CAT.txt, respectively * Output: RC_POP.txt list of languages sorted by popularity * If test=1, additionally: * RC_LNG.txt list of languages alphabetically sorted * RC_TRN.txt list language name translations (debug) *--------------------------------------------------------------------*/ test=1 name.='??' l.=0 safe='' x00='00'x linfid='RC_LAN.txt' linfid='LAN.txt' /* language file */ cinfid='CAT.txt' /* category file */ oid='RC_POP.txt'; 'erase' oid If test Then Do tid='RC.TRN.txt'; 'erase' tid tia='RC_LNG.txt'; 'erase' tia End Call init   call read_lang /* process language file */   Call read_cat /* process category file */   Call ot words(lang_list) 'possible languages' Call ot words(lang_listr) 'relevant languages' llrn=words(lang_listr)   If test Then Call no_member   a=.array~new /* create array object */ cnt.=0 Do i=1 By 1 While lang_listr<>'' Parse Var lang_listr ddu0 lang_listr ddu=translate(ddu0,' ',x00) a[i]=right(mem.ddu,3) name.ddu /* fill array element */ z=mem.ddu /* number of members */ cnt.z=cnt.z+1 /* number of such languages */ End n=i-1 /* number of output lines */   a~sortWith(.mycmp~new) /* sort the array elements */ /* see :CLASS mycmp below */ /*--------------------------------------------------------------------- * and now create the output *--------------------------------------------------------------------*/ Call o ' ' Call o center('timestamp: ' date() time('Civil'),79,'-') Call o ' ' Call o right(lrecs,9) 'records read from file: ' linfid Call o right(crecs,9) 'records read from file: ' cinfid Call o right(llrn,9) 'relevant languages' Call o ' '   rank=0 rank.=0 Do i=1 To n rank=rank+1 Parse Value a[i] With o . 6 lang ol=' rank: 'right(rank,3)' '||, '('right(o,3) 'entries) 'lang If cnt.o>1 Then Do If rank.o=0 Then rank.o=rank ol=overlay(right(rank.o,3),ol,17) ol=overlay('[tied]',ol,22) End Call o ol End   Call o ' ' Call o center('+ end of list +',72) Say 'Output in' oid   If test Then Do b=.array~new /* create array object */ cnt.=0 Do i=1 By 1 While lang_list<>'' Parse Var lang_list ddu0 lang_list ddu=translate(ddu0,' ',x00) b[i]=right(mem.ddu,3) name.ddu /* fill array element */ End n=i-1 /* number of output lines */   b~sortWith(.alpha~new) /* sort the array elements */ Call oa n 'languages' Do i=1 To n Call oa b[i] End Say 'Sorted list of languages in' tia End Exit   o: Return lineout(oid,arg(1)) ot: If test Then Call lineout tid,arg(1) Return oa: If test Then Call lineout tia,arg(1) Return   read_lang: /*--------------------------------------------------------------------- * Read the language page to determine the list of possible languages * Output: l.lang>0 for all languages found * name.lang original name of uppercased language name * lang_list list of uppercased language names * lrecs number of records read from language file *--------------------------------------------------------------------*/ l.=0 name.='??' lang_list='' Do lrecs=0 While lines(linfid)\==0 l=linein(linfid) /* read from language file */ l=translate(l,' ','9'x) /* turn tabs to blanks */ dd=space(l) /* remove extra blanks */ ddu=translate(dd) If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then /* ignore this */ Iterate If pos('RETRIEVED FROM',ddu)\==0 Then /* this indicates the end */ Leave If dd=='' Then /* ignore all blank lines. */ Iterate If left(dd,1)\=='*' Then /* ignore lines w/o * */ Iterate ddo=fix_lang(dd) /* replace odd language names */ If ddo<>dd Then Do /* show those that we found */ Call ot ' ' dd Call ot '>' ddo dd=ddo End Parse Var dd '*' dd "<" /* extract the language name */ ddu=strip(translate(dd)) /* translate to uppercase */ If name.ddu='??' Then name.ddu=dd /* remember 1st original name */ l.ddu=l.ddu+1 ddu_=translate(ddu,x00,' ') If wordpos(ddu_,lang_list)=0 Then lang_list=lang_list ddu_ End Return   read_cat: /*--------------------------------------------------------------------- * Read the category page to get language names and number of members * Output: mem.ddu number of members for (uppercase) Language ddu * lang_listr the list of relevant languages *--------------------------------------------------------------------*/ mem.=0 lang_listr='' Do crecs=0 While lines(cinfid)\==0 l=get_cat(cinfid) /* read from category file */ l=translate(l,' ','9'x) /* turn tabs to blanks */ dd=space(l) /* remove extra blanks */ If dd=='' Then /* ignore all blank lines. */ Iterate ddu=translate(dd) ddo=fix_lang(dd) /* replace odd language names */ If ddo<>dd Then Do /* show those that we found */ Call ot ' ' dd Call ot '>' ddo dd=ddo End du=translate(dd) /* get an uppercase version. */ If pos('RETRIEVED FROM',du)\==0 Then /* this indicates the end */ Leave Parse Var dd dd '<' "(" mems . /* extract the language name */ /* and the number of members */ dd=space(substr(dd,3)) _=translate(dd) If \l._ Then /* not a known language */ Iterate /* ignore */ if pos(',', mems)\==0 then mems=changestr(",", mems, '') /* remove commas. */ If\datatype(mems,'W') Then /* not a number of members */ Iterate /* ignore */ ddu=space(translate(dd)) mem.ddu=mem.ddu+mems /* set o add number of members*/ Call memory ddu /* list of relevant languages */ End Return   get_cat: /*--------------------------------------------------------------------- * get a (logical) line from the category file * These two lines * * Lotus 123 Macro Scripting * </wiki/Category:Lotus_123_Macro_Scripting>â€�‎ (3 members) * are returned as one line: *-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members) * we need language name and number of members in one line *--------------------------------------------------------------------*/ Parse Arg fid If safe<>'' Then ol=safe Else Do If lines(fid)=0 Then Return '' ol=linein(fid) safe='' End If left(ol,3)=' *' Then Do Do Until left(r,3)==' *' | lines(fid)=0 r=linein(fid) If left(r,3)==' *' Then Do safe=r Return ol End Else ol=ol r End End Return ol   memory: ddu0=translate(ddu,x00,' ') If wordpos(ddu0,lang_listr)=0 Then lang_listr=lang_listr ddu0 Return   fix_lang: Procedure Expose old. new. Parse Arg s Do k=1 While old.k\=='' /* translate Unicode variations. */ If pos(old.k,s)\==0 Then s=changestr(old.k,s,new.k) End Return s   init: old.='' old.1='UC++' /* '55432B2B'X */ new.1="µC++" /* old UC++ --?ASCII-8: µC++ */ old.2='МК-61/52' /* 'D09CD09A2D36312F3532'X */ new.2='MK-61/52' /* somewhere a mistranslated: MK- */ old.3='Déjà Vu' /* '44C3A96AC3A0205675'X */ new.3='Déjà Vu' /* Unicode +¬j+á --?ASCII-8: Déjá */ old.4='Caché' /* '43616368C3A9'X */ new.4='Caché' /* Unicode ach+¬ --?ASCII-8: Caché */ old.5='ΜC++' /* 'CE9C432B2B'X */ new.5="MC++" /* Unicode +£C++ --?ASCII-8: µC++ */ /*-----------------------------------------------------------------*/ Call ot 'Language replacements:' Do ii=1 To 5 Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii End Call ot ' ' Return   no_member: Procedure Expose lang_list lang_listr tid x00 test /*--------------------------------------------------------------------- * show languages found in language file that are not referred to * in the category file *--------------------------------------------------------------------*/ ll =wordsort(lang_list ) /* languages in language file */ llr=wordsort(lang_listr) /* languages in category file */ Parse Var ll l1 ll Parse Var llr l2 llr nn.=0 Do Forever Select When l1=l2 Then Do If l1='' Then /* both lists empty */ Leave Parse Var ll l1 ll /* get the next language */ Parse Var llr l2 llr /* -"- */ End When l1<l2 Then Do /* in language file */ /* and not in category file */ z=nn.0+1 nn.z=' 'translate(l1,' ',x00) /* show in test output */ nn.0=z Parse Var ll l1 ll /* next from language file */ End Otherwise Do Call ot '?? 'translate(l2,' ',x00) /* show in test output */ Say 'In category file but not in language file:' Say '?? 'translate(l2,' ',x00) Say 'Hit enter to proceed' Pull . Parse Var llr l2 llr /* next from category file */ End End End Call ot nn.0 'Languages without members:' /* heading */ Do ii=1 To nn.0 Call ot nn.ii End Return   ::CLASS mycmp MIXINCLASS Comparator ::METHOD compare /********************************************************************** * smaller number is considered higher * numbers equal: higher language considered higher * otherwise return lower **********************************************************************/ Parse Upper Arg a,b Parse Var a na +4 ta Parse Var b nb +4 tb Select When na<<nb THEN res=1 When na==nb Then Do If ta<<tb Then res=-1 Else res=1 End Otherwise res=-1 End Return res     ::CLASS alpha MIXINCLASS Comparator ::METHOD compare /********************************************************************** * higher language considered higher * otherwise return lower **********************************************************************/ Parse Upper Arg a,b Parse Var a na +4 ta Parse Var b nb +4 tb If ta<<tb Then res=-1 Else res=1 Return res
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
#AppleScript
AppleScript
------------------ ROMAN INTEGER STRINGS -----------------   -- roman :: Int -> String on roman(n) set kvs to {["M", 1000], ["CM", 900], ["D", 500], ¬ ["CD", 400], ["C", 100], ["XC", 90], ["L", 50], ¬ ["XL", 40], ["X", 10], ["IX", 9], ["V", 5], ¬ ["IV", 4], ["I", 1]}   script stringAddedValueDeducted on |λ|(balance, kv) set {k, v} to kv set {q, r} to quotRem(balance, v) if q > 0 then {r, concat(replicate(q, k))} else {r, ""} end if end |λ| end script   concat(snd(mapAccumL(stringAddedValueDeducted, n, kvs))) end roman     --------------------------- TEST ------------------------- on run   map(roman, [2016, 1990, 2008, 2000, 1666])   --> {"MMXVI", "MCMXC", "MMVIII", "MM", "MDCLXVI"} end run     ---------------- GENERIC LIBRARY FUNCTIONS ---------------   -- concat :: [[a]] -> [a] | [String] -> String on concat(xs) script append on |λ|(a, b) a & b end |λ| end script   if length of xs > 0 and ¬ class of (item 1 of xs) is string then set unit to "" else set unit to {} end if foldl(append, unit, xs) end concat   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- 'The mapAccumL function behaves like a combination of map and foldl; -- it applies a function to each element of a list, passing an -- accumulating parameter from left to right, and returning a final -- value of this accumulator together with the new list.' (see Hoogle)   -- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) on mapAccumL(f, acc, xs) script on |λ|(a, x) tell mReturn(f) to set pair to |λ|(item 1 of a, x) [item 1 of pair, (item 2 of a) & {item 2 of pair}] end |λ| end script   foldl(result, [acc, {}], xs) end mapAccumL   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- quotRem :: Integral a => a -> a -> (a, a) on quotRem(m, n) {m div n, m mod n} end quotRem   -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length   -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if n < 1 then return out set dbl to {a}   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- snd :: (a, b) -> b on snd(xs) if class of xs is list and length of xs = 2 then item 2 of xs else missing value end if end snd
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.
#Arturo
Arturo
syms: #[ M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 ]   fromRoman: function [roman][ ret: 0 loop 0..(size roman)-2 'ch [ fst: roman\[ch] snd: roman\[ch+1] valueA: syms\[fst] valueB: syms\[snd]   if? valueA < valueB -> ret: ret - valueA else -> ret: ret + valueA ] return ret + syms\[last roman] ]   loop ["MCMXC" "MMVIII" "MDCLXVI"] 'r -> print [r "->" fromRoman r]
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
#Dart
Dart
double fn(double x) => x * x * x - 3 * x * x + 2 * x;   findRoots(Function(double) f, double start, double stop, double step, double epsilon) sync* { for (double x = start; x < stop; x = x + step) { if (fn(x).abs() < epsilon) yield x; } }   main() { // Vector(-9.381755897326649E-14, 0.9999999999998124, 1.9999999999997022) print(findRoots(fn, -1.0, 3.0, 0.0001, 0.000000001)); }
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.
#C
C
  #include <stdio.h> #include <stdlib.h> #define LEN 3   /* pick a random index from 0 to n-1, according to probablities listed in p[] which is assumed to have a sum of 1. The values in the probablity list matters up to the point where the sum goes over 1 */ int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; }   int main() { int user_action, my_action; int user_rec[] = {0, 0, 0}; const char *names[] = { "Rock", "Paper", "Scissors" }; char str[2]; const char *winner[] = { "We tied.", "Meself winned.", "You win." }; double p[LEN] = { 1./3, 1./3, 1./3 };   while (1) { my_action = rand_idx(p,LEN);   printf("\nYour choice [1-3]:\n" " 1. Rock\n 2. Paper\n 3. Scissors\n> ");   /* scanf is a terrible way to do input. should use stty and keystrokes */ if (!scanf("%d", &user_action)) { scanf("%1s", str); if (*str == 'q') { printf("Your choices [rock : %d , paper :  %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); return 0; } continue; } user_action --; if (user_action > 2 || user_action < 0) { printf("invalid choice; again\n"); continue; } printf("You chose %s; I chose %s. %s\n", names[user_action], names[my_action], winner[(my_action - user_action + 3) % 3]);   user_rec[user_action]++; } }  
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.
#Elixir
Elixir
defmodule Run_length do def encode(str) when is_bitstring(str) do to_char_list(str) |> encode |> to_string end def encode(list) when is_list(list) do Enum.chunk_by(list, &(&1)) |> Enum.flat_map(fn chars -> to_char_list(length(chars)) ++ [hd(chars)] end) end   def decode(str) when is_bitstring(str) do Regex.scan(~r/(\d+)(.)/, str) |> Enum.map_join(fn [_,n,c] -> String.duplicate(c, String.to_integer(n)) end) end def decode(list) when is_list(list) do to_string(list) |> decode |> to_char_list end end   text = [ string: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", char_list: 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' ]   Enum.each(text, fn {type, txt} -> IO.puts type txt |> IO.inspect |> Run_length.encode |> IO.inspect |> Run_length.decode |> IO.inspect 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.
#Kotlin
Kotlin
import java.lang.Math.*   data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> i.toString() + 'i' else -> "$r + ${i}i" } }   fun unity_roots(n: Number) = (1..n.toInt() - 1).map { val a = it * 2 * PI / n.toDouble() var r = cos(a); if (abs(r) < 1e-6) r = 0.0 var i = sin(a); if (abs(i) < 1e-6) i = 0.0 Complex(r, i) }   fun main(args: Array<String>) { (1..4).forEach { println(listOf(1) + unity_roots(it)) } println(listOf(1) + unity_roots(5.0)) }
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Rust
Rust
  extern crate regex;   use std::io; use std::io::prelude::*;   use regex::Regex;   fn find_bare_lang_tags(input: &str) -> Vec<(Option<String>, i32)> { let mut language_pairs = vec![]; let mut language = None; let mut counter = 0_i32;   let header_re = Regex::new(r"==\{\{header\|(?P<lang>[[:alpha:]]+)\}\}==").unwrap();   for line in input.lines() { if let Some(captures) = header_re.captures(line) { if let Some(header_lang) = captures.name("lang") { language_pairs.push((language, counter)); language = Some(header_lang.as_str().to_owned()); counter = 0; } }   if line.contains("<lang>") { counter += 1; } }   language_pairs.push((language, counter)); language_pairs }   fn main() { let stdin = io::stdin(); let mut buf = String::new(); stdin.lock().read_to_string(&mut buf).unwrap(); let results = find_bare_lang_tags(&buf); let total_bare = results.iter().map(|r| r.1).sum::<i32>();   println!("{} bare language tags.\n", total_bare); for result in &results { let num_bare = result.1;   if num_bare > 0 { println!( "{} in {}", result.1, result .0 .to_owned() .unwrap_or_else(|| String::from("no language")) ); } } }  
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare language tags. 1 in perl 1 in no language Extra credit Allow multiple files to be read.   Summarize all results by language: 5 bare language tags. 2 in c ([[Foo]], [[Bar]]) 1 in perl ([[Foo]]) 2 in no language ([[Baz]]) Extra extra credit Use the   Media Wiki API   to test actual RC tasks.
#Scala
Scala
// Map lines to a list of Option(heading -> task) for each bare lang tag found. val headerFormat = "==[{]+header[|]([^}]*)[}]+==".r val langFormat = "<lang([^>]*)>".r def mapped(lines: Seq[String], taskName: String = "") = { var heading = "" for (line <- lines; head = headerFormat.findFirstMatchIn(line).map(_ group 1); lang = langFormat.findFirstMatchIn(line).map(_ group 1)) yield { if (head.isDefined) heading = head.get lang.map(_.trim).filter(_ == "").map(_ => heading -> taskName) } } // Group results as a Map(heading -> task1, task2, ...) def reduced(results: Seq[Option[(String,String)]]) = results.flatten.groupBy(_._1).mapValues(_.unzip._2)   // Format each heading as "tasklist.size in heading (tasklist)" def format(results: Map[String,Seq[String]]) = results.map{case (heading, tasks) => val h = if (heading.length > 0) heading else "no langauge" val hmsg = s"${tasks.size} in $h" val t = tasks.filterNot(_ == "") val tmsg = if (t.isEmpty) "" else t.distinct.mkString(" (", ",", ")") hmsg + tmsg } def count(results: Map[String,Seq[String]]) = results.values.map(_.size).sum   // Single and multi-source support case class BareLangFinder(source: scala.io.Source, taskName: String = "") { def map = mapped(source.getLines.toSeq, taskName) def mapReduce = reduced(map) def summary = format(mapReduce) mkString "\n" } def mapReduce(inputs: Seq[BareLangFinder]) = reduced(inputs.flatMap(_.map))
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.
#lambdatalk
lambdatalk
  1) using lambdas:   {def equation {lambda {:a :b :c} {b equation :a*x{sup 2}+:b*x+:c=0} {{lambda {:a' :b' :d} {if {> :d 0} then {{lambda {:b' :d'} {equation.disp {+ :b' :d'} {- :b' :d'} 2 real roots} } :b' {/ {sqrt :d} :a'}} else {if {< :d 0} then {{lambda {:b' :d'} {equation.disp [:b',:d'] [:b',-:d'] 2 complex roots} } :b' {/ {sqrt {- :d}} :a'} } else {equation.disp :b'  :b' one real double root} }} } {* 2 :a} {/ {- :b} {* 2 :a}} {- {* :b :b} {* 4 :a :c}} } }}   2) using let:   {def equation {lambda {:a :b :c} {b equation :a*x{sup 2}+:b*x+:c=0} {let { {:a' {* 2 :a}} {:b' {/ {- :b} {* 2 :a}}} {:d {- {* :b :b} {* 4 :a :c}}} } {if {> :d 0} then {let { {:b' :b'} {:d' {/ {sqrt :d} :a'}} } {equation.disp {+ :b' :d'} {- :b' :d'} 2 real roots} } else {if {< :d 0} then {let { {:b' :b'} {:d' {/ {sqrt {- :d}} :a'}} } {equation.disp [:b',:d'] [:b',-:d'] 2 complex roots} } else {equation.disp :b' :b' one real double root} }} }}}   3) a function to display results in an HTML table format   {def equation.disp {lambda {:x1 :x2 :txt} {table {@ style="background:#ffa"} {tr {td :txt: }} {tr {td x1 = :x1 }} {tr {td x2 = :x2 }} } }}   4) testing:   equation 1*x2+1*x+-1=0 2 real roots: x1 = 0.6180339887498949 x2 = -1.618033988749895   equation 1*x2+1*x+1=0 2 complex roots: x1 = [-0.5,0.8660254037844386] x2 = [-0.5,-0.8660254037844386]   equation 1*x2+-2*x+1=0 one real double root: x1 = 1 x2 = 1  
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
#Commodore_BASIC
Commodore BASIC
1 rem rot-13 cipher 2 rem rosetta code 10 print chr$(147);chr$(14); 25 gosub 1000 30 print chr$(147);"Enter a message to translate." 35 print:print "Press CTRL-Z when finished.":print 40 mg$="":gosub 2000 45 print chr$(147);"Processing...":gosub 3000 50 print chr$(147);"The translated message is:" 55 print:print cm$ 100 print:print "Do another one? "; 110 get k$:if k$<>"y" and k$<>"n" then 110 120 print k$:if k$="y" then goto 10 130 end   1000 rem generate encoding table 1010 ec$="mnopqrstuvwxyzabcdefghijklMNOPQRSTUVWXYZABCDEFGHIJKL" 1099 return   2000 rem get user input routine 2005 print chr$(18);" ";chr$(146);chr$(157); 2010 get k$:if k$="" then 2010 2012 if k$=chr$(13) then print " ";chr$(157); 2015 print k$; 2020 if k$=chr$(20) then mg$=left$(mg$,len(mg$)-1):goto 2040 2025 if len(mg$)=255 or k$=chr$(26) then return 2030 mg$=mg$+k$ 2040 goto 2005   3000 rem translate message 3005 cm$="" 3010 for i=1 to len(mg$) 3015 c=asc(mid$(mg$,i,1)) 3020 if c<65 or (c>90 and c<193) or c>218 then cm$=cm$+chr$(c):goto 3030 3025 if c>=65 and c<=90 then c=c-64 3030 if c>=193 and c<=218 then c=(c-192)+26 3035 cm$=cm$+mid$(ec$,c,1) 3040 next i 3050 return
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#Perl
Perl
sub runge_kutta { my ($yp, $dt) = @_; sub { my ($t, $y) = @_; my @dy = $dt * $yp->( $t , $y ); push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[0]/2 ); push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[1]/2 ); push @dy, $dt * $yp->( $t + $dt , $y + $dy[2] ); return $t + $dt, $y + ($dy[0] + 2*$dy[1] + 2*$dy[2] + $dy[3]) / 6; } }   my $RK = runge_kutta sub { $_[0] * sqrt $_[1] }, .1;   for( my ($t, $y) = (0, 1); sprintf("%.0f", $t) <= 10; ($t, $y) = $RK->($t, $y) ) { printf "y(%2.0f) = %12f ± %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16) if sprintf("%.4f", $t) =~ /0000$/; }
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#zkl
zkl
var [const] YAJL=Import("zklYAJL")[0], CURL=Import("zklCurl");   fcn getTasks(language){ continueValue,tasks:="",Data(0,String); // "nm\0nm\0...." do{ page:=CURL().get(("http://rosettacode.org/mw/api.php?" "action=query&cmlimit=500" "&format=json" "&list=categorymembers" "&cmtitle=Category:%s" "&cmcontinue=%s").fmt(language,continueValue)); page=page[0].del(0,page[1]); // get rid of HTML header json:=YAJL().write(page).close(); json["query"]["categorymembers"].pump(tasks,T("get","title")); continueValue=json.find("continue") //continue:-||,cmcontinue:page|954|19) .toList().apply("concat","=").concat("&"); }while(continueValue); tasks }   allTasks:=getTasks.future("Programming_Tasks"); // thread
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#Racket
Racket
  #lang racket (define input #<<--- ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) --- )   (read (open-input-string input))  
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#Python
Python
import random random.seed() attributes_total = 0 count = 0   while attributes_total < 75 or count < 2: attributes = []   for attribute in range(0, 6): rolls = []   for roll in range(0, 4): result = random.randint(1, 6) rolls.append(result)   sorted_rolls = sorted(rolls) largest_3 = sorted_rolls[1:] rolls_total = sum(largest_3)   if rolls_total >= 15: count += 1   attributes.append(rolls_total)   attributes_total = sum(attributes)   print(attributes_total, attributes)
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
#Standard_ML
Standard ML
  val segmentedSieve = fn N => (* output : list of {segment=bit segment, start=number at startposition segment} *)   let   val NSegmt= 120000000; (* segment size *)     val inf2i = IntInf.toInt ; val i2inf = IntInf.fromInt ; val isInt = fn m => m <= IntInf.fromInt (valOf Int.maxInt);   val sweep = fn (bits, step, k, up) => (* strike off bits up to limit *) (while (  !k < up andalso 0 <= !k ) do ( BitArray.clrBit( bits, !k ) ; k:= !k + step ; ()) ) handle Overflow => ()   val rec nextPrimebit = (* find next 1-bit within segment *) fn Bits => fn pos => if pos+1 >= BitArray.length Bits then NONE else ( if BitArray.sub ( Bits,pos) then SOME (i2inf pos) else nextPrimebit Bits (pos+1) );     val sieveEratosthenes = fn n: int => (* Eratosthenes sieve , up to+incl n *)   let val nums= BitArray.bits(n,[] ); val i=ref 2; val k=ref (!i * (!i) -1);   in   ( BitArray.complement nums; BitArray.clrBit( nums, 0 ); while ( !k <n ) do ( if ( BitArray.sub (nums, !i - 1) ) then sweep (nums, !i, k, n) else (); i:= !i+1; k:= !i * (!i) - 1 ); [ { start= i2inf 1, segment=nums } ] )   end;       val sieveThroughSegment =   fn ( primes : { segment:BitArray.array, start:IntInf.int } list, low : IntInf.int, up ) => (* second segment and on *) let val n = inf2i (up-low+1) val nums = BitArray.bits(n,[] ); val itdone = low div i2inf NSegmt   val rec oldprimes = fn c => fn (* use segment B to sweep current one *) [] => () | ctlist as {start=st,segment=B}::t => let   val nxt = nextPrimebit B c ; val p = st + Option.getOpt( nxt,~10) val modp = ( i2inf NSegmt * itdone ) mod p val i = inf2i ( if( isInt( p - modp ) ) then p - modp else 0 ) (* i = 0 breaks off *) val k = ref ( if Option.isSome nxt then (i - 1) else ~2 ) val step = if (isInt(p)) then inf2i(p) else valOf Int.maxInt (* !k+maxInt > n *)   in   ( sweep (nums, step, k, n) ; if ( p*p <= up andalso Option.isSome nxt ) then oldprimes ( inf2i (p-st+1) ) ctlist else oldprimes 0 t (* next segment B *) )   end   in ( BitArray.complement nums; oldprimes 0 primes; rev ( {start = low, segment = nums } :: rev (primes) ) ) end;       val rec workSegmentsDown = fn firstFn => fn nextFns => fn sizeSeg : int => fn upLimit : IntInf.int => let val residual = upLimit mod i2inf sizeSeg in   if ( upLimit <= i2inf sizeSeg ) then firstFn ( inf2i upLimit ) else if ( residual > 0 ) then nextFns ( workSegmentsDown firstFn nextFns sizeSeg (upLimit - residual ), upLimit - residual + 1, upLimit ) else nextFns ( workSegmentsDown firstFn nextFns sizeSeg (upLimit - i2inf sizeSeg), upLimit - i2inf sizeSeg + 1, upLimit ) end;   in   workSegmentsDown sieveEratosthenes sieveThroughSegment NSegmt N   end;    
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#PicoLisp
PicoLisp
(load "@lib/http.l")   (client "rosettacode.org" 80 "mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" (while (from " title=\"") (let Task (till "\"") (client "rosettacode.org" 80 (pack "wiki/" (replace Task " " "_")) (let Cnt 0 (while (from "<span class=\"tocnumber\">") (unless (sub? "." (till "<" T)) (inc 'Cnt) ) ) (out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) )
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
#PureBasic
PureBasic
Procedure handleError(value, msg.s) If value = 0 MessageRequester("Error", msg) End EndIf EndProcedure   handleError(InitNetwork(), "Unable to initialize network functions.") If OpenConsole() Define url$, x1$, y1$, title$, unescapedTitle$, encodedURL$ Define x2, i, j, totalExamples, totalTasks url$ = "http://www.rosettacode.org/mw/api.php?action=query" + "&list=categorymembers&cmtitle=Category:Programming_Tasks" + "&cmlimit=500&format=xml"   Repeat handleError(ReceiveHTTPFile(url$, "tasks.xml"), "Unable to access tasks URL.")   handleError(ReadFile(0, "tasks.xml"), "Unable to read 'task.xml' file.") x1$ = ReadString(0) CloseFile(0)   Repeat x2 = FindString(x1$, "title=", x2 + 1) If x2 title$ = Mid(x1$, x2 + 7, 99) title$ = Left(title$, FindString(title$, ">", 1) - 4) unescapedTitle$ = UnescapeString(ReplaceString(title$, "&#039;", "&apos;"), #PB_String_EscapeXML) encodedURL$ = URLEncoder("http://www.rosettacode.org/mw/index.php?title=" + unescapedTitle$ + "&action=raw") If ReceiveHTTPFile(encodedURL$, "task.xml") ReadFile(0, "task.xml") While Not Eof(0) y1$ = ReadString(0) If FindString(y1$, "=={{header|", 1, #PB_String_NoCase) totalExamples + 1 EndIf Wend CloseFile(0)   PrintN(unescapedTitle$ +": " + Str(totalExamples) + " examples")   totalTasks + totalExamples totalExamples = 0 EndIf EndIf Until x2 = 0   ;check for additional pages of tasks x2 = FindString(x1$, "cmcontinue=") If x2 i = FindString(x1$, #DQUOTE$, x2 + 1) j = FindString(x1$, #DQUOTE$, i + 1) url$ = URLEncoder("http://www.rosettacode.org/mw/api.php?action=query" + "&list=categorymembers&cmtitle=Category:Programming_Tasks" + "&cmlimit=500&format=xml&cmcontinue=" + Mid(x1$, i + 1, j - i)) Else Break ;all done EndIf ForEver   PrintN("Total: " + Str(totalTasks) + " examples") Input() CloseConsole() EndIf
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
#Maple
Maple
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]: occurences := ListTools:-SearchAll(needle,haystack): try #first occurence printf("The first occurence is at index %d\n", occurences[1]); #last occurence, note that StringTools:-SearchAll()retuns a list of all occurences positions printf("The last occurence is at index %d\n", occurences[-1]); catch : print("Erros: Needle not found in the haystack"): end try:
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.
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   fun {GetPage RawUrl} Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} Url = {VirtualString.toString RawUrl} OutParams HttpResponseParams in {Client getService(Url ?OutParams ?HttpResponseParams)} {Client closeAll(true)} OutParams.sOut end   fun {GetCategories Doc} {Map {Regex.allMatches "<li><a[^>]+>([^<]+)</a> \\(([0-9]+) member" Doc} fun {$ Match} Category = {Regex.group 1 Match Doc} Count = {String.toInt {ByteString.toString {Regex.group 2 Match Doc}}} in Category#Count end } end   Url = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"   {System.showInfo "Retrieving..."} Doc = {GetPage Url}   {System.showInfo "Parsing..."} Cs = {GetCategories Doc} in for Cat#Count in {Sort Cs fun {$ _#C1 _#C2} C1 > C2 end} I in 1..20 do {System.showInfo I#". "#Count#" - "#Cat} end
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#Arturo
Arturo
nums: [[1000 "M"] [900 "CM"] [500 "D"] [400 "CD"] [100 "C"] [90 "XC"] [50 "L"] [40 "XL"] [10 "X"] [9 "IX"] [5 "V"] [4 "IV"] [1 "I"])   toRoman: function [x][ ret: "" idx: 0 initial: x loop nums 'num [ d: num\0 l: num\1   i: 0 while [i<initial/d] [ ret: ret ++ l i: i+1 ]   initial: mod initial d ] return ret ]   loop [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 25 30 40 50 60 69 70 80 90 99 100 200 300 400 500 600 666 700 800 900 1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500 3000 3999] 'n -> print [n "->" toRoman n]