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/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.
#Nim
Nim
import complex, math, sequtils, strformat, strutils   proc roots(n: Positive): seq[Complex64] = for k in 0..<n: result.add rect(1.0, 2 * k.float * Pi / n.float)   proc toString(z: Complex64): string = &"{z.re:.3f} + {z.im:.3f}i"   for nr in 2..10: let result = roots(nr).map(toString).join(", ") echo &"{nr:2}: {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.
#OCaml
OCaml
open Complex   let pi = 4. *. atan 1.   let () = for n = 1 to 10 do Printf.printf "%2d " n; for k = 1 to n do let ret = polar 1. (2. *. pi *. float_of_int k /. float_of_int n) in Printf.printf "(%f + %f i)" ret.re ret.im done; print_newline () done
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.
#Nim
Nim
import math, complex, strformat   const Epsilon = 1e-15   type   SolKind = enum solDouble, solFloat, solComplex   Roots = object case kind: SolKind of solDouble: fvalue: float of solFloat: fvalues: (float, float) of solComplex: cvalues: (Complex64, Complex64)     func quadRoots(a, b, c: float): Roots = if a == 0: raise newException(ValueError, "first coefficient cannot be null.") let den = a * 2 let Δ = b * b - a * c * 4 if abs(Δ) < Epsilon: result = Roots(kind: solDouble, fvalue: -b / den) elif Δ < 0: let r = -b / den let i = sqrt(-Δ) / den result = Roots(kind: solComplex, cvalues: (complex64(r, i), complex64(r, -i))) else: let r = (if b < 0: -b + sqrt(Δ) else: -b - sqrt(Δ)) / den result = Roots(kind: solFloat, fvalues: (r, c / (a * r)))     func `$`(r: Roots): string = case r.kind of solDouble: result = $r.fvalue of solFloat: result = &"{r.fvalues[0]}, {r.fvalues[1]}" of solComplex: result = &"{r.cvalues[0].re} + {r.cvalues[0].im}i, {r.cvalues[1].re} + {r.cvalues[1].im}i"     when isMainModule:   const Equations = [(1.0, -2.0, 1.0), (10.0, 1.0, 1.0), (1.0, -10.0, 1.0), (1.0, -1000.0, 1.0), (1.0, -1e9, 1.0)]   for (a, b, c) in Equations: echo &"Equation: {a=}, {b=}, {c=}" let roots = quadRoots(a, b, c) let plural = if roots.kind == solDouble: "" else: "s" echo &" root{plural}: {roots}"
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.
#OCaml
OCaml
type quadroots = | RealRoots of float * float | ComplexRoots of Complex.t * Complex.t ;;   let quadsolve a b c = let d = (b *. b) -. (4.0 *. a *. c) in if d < 0.0 then let r = -. b /. (2.0 *. a) and i = sqrt(-. d) /. (2.0 *. a) in ComplexRoots ({ Complex.re = r; Complex.im = i }, { Complex.re = r; Complex.im = (-.i) }) else let r = if b < 0.0 then ((sqrt d) -. b) /. (2.0 *. a) else ((sqrt d) +. b) /. (-2.0 *. a) in RealRoots (r, c /. (r *. a)) ;;
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
rot-13: ) for ch in chars swap: ord ch if <= 65 dup: if >= 90 dup: + 13 - swap 65 + 65 % swap 26 if <= 97 dup: if >= 122 dup: + 13 - swap 97 + 97 % swap 26 chr concat(   !print rot-13 "Snape kills Frodo with Rosebud."
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 }
#Raku
Raku
sub runge-kutta(&yp) { return -> \t, \y, \δt { my $a = δt * yp( t, y ); my $b = δt * yp( t + δt/2, y + $a/2 ); my $c = δt * yp( t + δt/2, y + $b/2 ); my $d = δt * yp( t + δt, y + $c ); ($a + 2*($b + $c) + $d) / 6; } }   constant δt = .1; my &δy = runge-kutta { $^t * sqrt($^y) };   loop ( my ($t, $y) = (0, 1); $t <= 10; ($t, $y) »+=« (δt, δy($t, $y, δt)) ) { printf "y(%2d) = %12f ± %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16) if $t %% 1; }
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.
#Sidef
Sidef
func sexpr(txt) { txt.trim!   if (txt.match(/^\((.*)\)$/s)) {|m| txt = m[0] } else { die "Invalid: <<#{txt}>>" }   var w var ret = []   while (!txt.is_empty) { given (txt.first) { when('(') { (w, txt) = txt.extract_bracketed('()'); w = sexpr(w) } when ('"') { (w, txt) = txt.extract_delimited('"') w.sub!(/^"(.*)"/, {|s1| s1 }) } else { txt.sub!(/^(\S+)/, {|s1| w = s1; '' }) } } ret << w txt.trim_beg! } return ret }   func sexpr2txt(String e) { e ~~ /[\s"\(\)]/ ? do { e.gsub!('"', '\\"'); %Q("#{e}") } : e }   func sexpr2txt(expr) { '(' + expr.map {|e| sexpr2txt(e) }.join(' ') + ')' }   var s = sexpr(%q{   ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))   })   say s # dump structure say sexpr2txt(s) # convert back
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.
#Ring
Ring
  # Project  : RPG Attributes Generator   load "stdlib.ring" attributestotal = 0 count = 0 while attributestotal < 75 or count < 2 attributes = [] for attribute = 0 to 6 rolls = [] largest3 = [] for roll = 0 to 4 result = random(5)+1 add(rolls,result) next sortedrolls = sort(rolls) sortedrolls = reverse(sortedrolls) for n = 1 to 3 add(largest3,sortedrolls[n]) next rollstotal = sum(largest3) if rollstotal >= 15 count = count + 1 ok add(attributes,rollstotal) next attributestotal = sum(attributes) end showline()   func sum(aList) num = 0 for n = 1 to len(aList) num = num + aList[n] next return num   func showline() line = "(" + attributestotal + ", [" for n = 1 to len(attributes) line = line + attributes[n] + ", " next line = left(line,len(line)-2) line = line + "])" see line + nl  
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.
#Ruby
Ruby
res = [] until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do res = Array.new(6) do a = Array.new(4){rand(1..6)} a.sum - a.min end end   p res puts "sum: #{res.sum}"  
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
#UNIX_Shell
UNIX Shell
function primes { typeset -a a typeset i j a[1]="" for (( i = 2; i <= $1; i++ )); do a[$i]=$i done for (( i = 2; i * i <= $1; i++ )); do if [[ ! -z ${a[$i]} ]]; then for (( j = i * i; j <= $1; j += i )); do a[$j]="" done fi done printf '%s' "${a[2]}" printf ' %s' ${a[*]:3} printf '\n' }   primes 1000
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
#Sidef
Sidef
var lwp = require('LWP::UserAgent').new(agent => 'Mozilla/5.0');   var site = 'http://rosettacode.org'; var list_url = '/mw/api.php?action=query&list=categorymembers&'+ 'cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml';   var content = lwp.get(site + list_url).decoded_content;   while (var m = content.match(/cm.*?title="(.*?)"/g)) { (var slug = m[0]).gsub!(' ', '_'); var count = lwp.get("#{site}/wiki/#{slug}").decoded_content.count(/toclevel-1/g); say "#{m[0]}: #{count} examples"; }
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
#Tcl
Tcl
package require Tcl 8.5 package require http package require json   fconfigure stdout -buffering none   proc get_tasks {category} { set start [clock milliseconds] puts -nonewline "getting $category members..." set base_url http://www.rosettacode.org/w/api.php set query {action query list categorymembers cmtitle Category:%s format json cmlimit 500} set this_query [dict create {*}[split [format $query $category]]] set tasks [list]   while {1} { set url [join [list $base_url [http::formatQuery {*}$this_query]] ?] set response [http::geturl $url] if {[set s [http::status $response]] ne "ok" || [http::ncode $response] != 200} { error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" } 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] != 0} { # no more continuations, we're done break } dict set this_query cmcontinue $continue_task } puts " found [llength $tasks] tasks in [expr {[clock milliseconds] - $start}] milliseconds" return $tasks }   # This proc can be replaced by a single regexp command: # set count [regexp -all "***=$needle" $haystack] # However this proc is more efficient -- we're dealing with plain strings only. proc count_substrings {needle haystack} { set count 0 set idx 0 while {[set idx [string first $needle $haystack $idx]] != -1} { incr count incr idx } return $count }   set total 0 foreach task [get_tasks Programming_Tasks] { set url [format "http://www.rosettacode.org/w/index.php?title=%s&action=raw" [string map {{ } _} $task]] set response [http::geturl $url] if {[set s [http::status $response]] ne "ok" || [http::ncode $response] != 200} { error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" } set count [count_substrings "\{\{header|" [http::data $response]] puts [format "%3d examples in %s" $count $task] http::cleanup $response incr total $count }   puts "\nTotal: $total examples"
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
#Objeck
Objeck
use Collection;   class Test { function : Main(args : String[]) ~ Nil { haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]; values := CompareVector->New(); each(i : haystack) { values->AddBack(haystack[i]->As(Compare)); };   needles := ["Washington", "Bush"]; each(i : needles) { values->Has(needles[i]->As(Compare))->PrintLine(); }; } }
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.
#Python
Python
import requests import re   response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text languages = re.findall('title="Category:(.*?)">',response)[:-3] # strip last 3   response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response) # strip ',' from popular languages above 999 members members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response) # find language and members   for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): # show only top 15 languages if language in languages: print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))    
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
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   set cnt=0&for %%A in (1000,900,500,400,100,90,50,40,10,9,5,4,1) do (set arab!cnt!=%%A&set /a cnt+=1) set cnt=0&for %%R in (M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I) do (set rom!cnt!=%%R&set /a cnt+=1) ::Testing call :toRoman 2009 echo 2009 = !result! call :toRoman 1666 echo 1666 = !result! call :toRoman 3888 echo 3888 = !result! pause>nul exit/b 0 ::The "function"... :toRoman set value=%1 set result=   for /l %%i in (0,1,12) do ( set a=%%i call :add_val ) goto :EOF   :add_val if !value! lss !arab%a%! goto :EOF set result=!result!!rom%a%! set /a value-=!arab%a%! goto add_val
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.
#BQN
BQN
⟨ToArabic⇐A⟩ ← { c ← "IVXLCDM" # Characters v ← ⥊ (10⋆↕4) ×⌜ 1‿5 # Their values A ⇐ +´∘(⊢ׯ1⋆<⟜«) v ⊏˜ c ⊐ ⊢ }
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
#FreeBASIC
FreeBASIC
#Include "crt.bi" const iterations=20000000   sub bisect( f1 as function(as double) as double,min as double,max as double,byref O as double,a() as double) dim as double last,st=(max-min)/iterations,v for n as double=min to max step st v=f1(n) if sgn(v)<>sgn(last) then redim preserve a(1 to ubound(a)+1) a(ubound(a))=n O=n+st:exit sub end if last=v next end sub   function roots(f1 as function(as double) as double,min as double,max as double, a() as double) as long redim a(0) dim as double last,O,st=(max-min)/iterations,v for n as double=min to max step st v=f1(n) if sgn(v)<>sgn(last) and n>min then bisect(f1,n-st,n,O,a()):n=O last=v next return ubound(a) end function   Function CRound(Byval x As Double,Byval precision As Integer=30) As String If precision>30 Then precision=30 Dim As zstring * 40 z:Var s="%." &str(Abs(precision)) &"f" sprintf(z,s,x) If Val(z) Then Return Rtrim(Rtrim(z,"0"),".")Else Return "0" End Function   function defn(x as double) as double return x^3-3*x^2+2*x end function   redim as double r()   print if roots(@defn,-20,20,r()) then print "in range -20 to 20" print "All roots approximate" print "number","root to 6 dec places","function value at root" for n as long=1 to ubound(r) print n,CRound(r(n),6),,defn(r(n)) next n end if sleep
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.
#Erlang
Erlang
  -module(rps). -compile(export_all).   play() -> loop([1,1,1]).   loop([R,P,S]=Odds) -> case io:fread("What is your move? (R,P,S,Q) ","~c") of {ok,["Q"]} -> io:fwrite("Good bye!~n"); {ok,[[Human]]} when Human == $R; Human == $P; Human == $S -> io:fwrite("Your move is ~s.~n", [play_to_string(Human)]), Computer = select_play(Odds), io:fwrite("My move is ~s~n", [play_to_string(Computer)]), case {beats(Human,Computer),beats(Computer,Human)} of {true,_} -> io:fwrite("You win!~n"); {_,true} -> io:fwrite("I win!~n"); _ -> io:fwrite("Draw~n") end, case Human of $R -> loop([R+1,P,S]); $P -> loop([R,P+1,S]); $S -> loop([R,P,S+1]) end; _ -> io:fwrite("Invalid play~n"), loop(Odds) end.   beats($R,$S) -> true; beats($P,$R) -> true; beats($S,$P) -> true; beats(_,_) -> false.   play_to_string($R) -> "Rock"; play_to_string($P) -> "Paper"; play_to_string($S) -> "Scissors".   select_play([R,P,S]) -> N = random:uniform(R+P+S), if N =< R -> $P; N =< R+P -> $S; true -> $R end.  
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#Fan
Fan
** ** Generates a run-length encoding for a string ** class RLE { Run[] encode(Str s) { runs := Run[,]   s.size.times |i| { ch := s[i] if (runs.size==0 || runs.last.char != ch) runs.add(Run(ch)) runs.last.inc } return runs }   Str decode(Run[] runs) { buf := StrBuf() runs.each |run| { run.count.times { buf.add(run.char.toChar) } } return buf.toStr }   Void main() { echo(decode(encode( "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" ))) }   }   internal class Run { Int char Int count := 0 new make(Int ch) { char = ch } Void inc() { ++count }   override Str toStr() { return "${count}${char.toChar}" } }
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.
#Octave
Octave
for j = 2 : 10 printf("*** %d\n", j); for n = 1 : j disp(exp(2i*pi*n/j)); endfor disp(""); endfor
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.
#OoRexx
OoRexx
/*REXX program computes the K roots of unity (which include complex roots).*/ parse Version v Say v parse arg n frac . /*get optional arguments from the C.L. */ if n=='' then n=1 /*Not specified? Then use the default.*/ if frac='' then frac=5 /* " " " " " " */ start=abs(n) /*assume only one K is wanted. */ if n<0 then start=1 /*Negative? Then use a range of K's. */ /*display unity roots for a range, or */ do k=start to abs(n) /* just for one K. */ say right(k 'roots of unity',40,"-") /*display a pretty separator with title*/ do angle=0 by 360/k for k /*compute the angle for each root. */ rp=adjust(rxCalcCos(angle,,'D')) /*compute real part via COS function.*/ if left(rp,1)\=='-' then rp=" "rp /*not negative? Then pad with a blank.*/ ip=adjust(rxCalcSin(angle,,'D')) /*compute imaginary part via SIN funct.*/ if left(ip,1)\=='-' then ip="+"ip /*Not negative? Then pad with + char.*/ if ip=0 then say rp /*Only real part? Ignore imaginary part*/ else say left(rp,frac+4)ip'i' /*show the real & imaginary part*/ end /*angle*/ end /*k*/ exit /*stick a fork in it, we're all done. */ /*----------------------------------------------------------------------------*/ adjust: parse arg x; near0='1e-' || (digits()-digits()%10) /*compute small #*/ if abs(x)<near0 then x=0 /*if near zero, then assume zero.*/ return format(x,,frac)/1 /*fraction digits past dec point.*/ ::requires rxMath library
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.
#Octave
Octave
roots(a,b,c)=polrootsreal(Pol([a,b,c]))
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.
#PARI.2FGP
PARI/GP
roots(a,b,c)=polrootsreal(Pol([a,b,c]))
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
#E
E
pragma.enable("accumulator")   var rot13Map := [].asMap() for a in ['a', 'A'] { for i in 0..!26 { rot13Map with= (a + i, E.toString(a + (i + 13) % 26)) } }   def rot13(s :String) { return accum "" for c in s { _ + rot13Map.fetch(c, fn{ c }) } }
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 }
#REXX
REXX
The Runge─Kutta method is used to solve the following differential equation:   y'(t) = t2 √ y(t)   The exact solution: y(t) = (t2+4)2 ÷ 16
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 }
#Ring
Ring
  decimals(8) y = 1.0 for i = 0 to 100 t = i / 10 if t = floor(t) actual = (pow((pow(t,2) + 4),2)) / 16 see "y(" + t + ") = " + y + " error = " + (actual - y) + nl ok k1 = t * sqrt(y) k2 = (t + 0.05) * sqrt(y + 0.05 * k1) k3 = (t + 0.05) * sqrt(y + 0.05 * k2) k4 = (t + 0.10) * sqrt(y + 0.10 * k3) y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6 next  
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.
#Tcl
Tcl
package require Tcl 8.5   proc fromSexp {str} { set tokenizer {[()]|"(?:[^\\""]|\\.)*"|(?:[^()""\s\\]|\\.)+|[""]} set stack {} set accum {} foreach token [regexp -inline -all $tokenizer $str] { if {$token eq "("} { lappend stack $accum set accum {} } elseif {$token eq ")"} { if {![llength $stack]} {error "unbalanced"} set accum [list {*}[lindex $stack end] [list list {*}$accum]] set stack [lrange $stack 0 end-1] } elseif {$token eq "\""} { error "bad quote" } elseif {[string match {"*"} $token]} { set token [string range $token 1 end-1] lappend accum [list string [regsub -all {\\(.)} $token {\1}]] } else { if {[string is integer -strict $token]} { set type int } elseif {[string is double -strict $token]} { set type real } else { set type atom } lappend accum [list $type [regsub -all {\\(.)} $token {\1}]] } } if {[llength $stack]} {error "unbalanced"} return [lindex $accum 0] } proc toSexp {tokList} { set content [lassign $tokList type] if {$type eq "list"} { set s "(" set sep "" foreach bit $content { append s $sep [toSexp $bit] set sep " " } return [append s ")"] } elseif {$type eq "string"} { return "\"[regsub -all {[\\""]} [lindex $content 0] {\\\0}]\"" } else { return [lindex $content 0] } }
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.
#Run_BASIC
Run BASIC
dim statnames$(6) data "STR", "CON", "DEX", "INT", "WIS", "CHA" for i = 1 to 6 read statnames$(i) next i dim stat(6) acceptable = false   while 1 sum = 0 : n15 = 0 for i = 1 to 6 stat(i) = rollstat() sum = sum + stat(i) if stat(i) >= 15 then n15 = n15 + 1 next i if sum >= 75 and n15 >= 2 then exit while wend   for i = 1 to 6 print statnames$(i); ": "; stat(i) next i print "-------" print "TOT: "; sum end   function d6() d6 = 1 + int(rnd(1) * 6) end function   function rollstat() a = d6() : b = d6() : c = d6() : d = d6() rollstat = a + b + c + d - min(min(a, b), min(c, d)) end function
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.
#Rust
Rust
  use rand::distributions::Uniform; use rand::prelude::{thread_rng, ThreadRng}; use rand::Rng;   fn main() { for _ in 0..=10 { attributes_engine(); } }   #[derive(Copy, Clone, Debug)] pub struct Dice { amount: i32, range: Uniform<i32>, rng: ThreadRng, }   impl Dice { // Modeled after d20 polyhederal dice use and notation. // roll_pool() - returns Vec<i32> with length of vector determined by dice amount. // attribute_out() - returns i32, by sorting a dice pool of 4d6, dropping the lowest integer, and summing all elements. pub fn new(amount: i32, size: i32) -> Self { Self { amount, range: Uniform::new(1, size + 1), rng: thread_rng(), } }   fn roll_pool(mut self) -> Vec<i32> { (0..self.amount) .map(|_| self.rng.sample(self.range)) .collect() }   fn attribute_out(&self) -> i32 { // Sort dice pool lowest to high and drain all results to exclude the lowest before summing. let mut attribute_array: Vec<i32> = self.roll_pool(); attribute_array.sort(); attribute_array.drain(1..=3).sum() } }   fn attributes_finalizer() -> (Vec<i32>, i32, bool) { let die: Dice = Dice::new(4, 6); let mut attributes: Vec<i32> = Vec::new();   for _ in 0..6 { attributes.push(die.attribute_out()) }   let attributes_total: i32 = attributes.iter().sum();   let numerical_condition: bool = attributes .iter() .filter(|attribute| **attribute >= 15) .count() >= 2;   (attributes, attributes_total, numerical_condition) }   fn attributes_engine() { loop { let (attributes, attributes_total, numerical_condition) = attributes_finalizer(); if (attributes_total >= 75) && (numerical_condition) { println!( "{:?} | sum: {:?}", attributes, attributes_total ); break; } else { continue; } } }  
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
#Ursala
Ursala
#import nat   sieve = ~<{0,1}&& iota; @NttPX ~&r->lx ^/~&rhPlC remainder@rlX~|@r
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
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" data=REQUEST (url)   BUILD S_TABLE beg=* DATA :title=": BUILD S_TABLE end=* DATA :":   titles=EXTRACT (data,beg|,end,1,0,"~~") titles=SPLIT (titles,":~~:") sz_titles=SIZE (titles)   BUILD R_TABLE header=":==\{\{header|:" all=*   ERROR/STOP CREATE ("tasks",seq-e,-std-)   COMPILE LOOP title=titles ask=* ask =SET_VALUE(ask,"title",title) ask =SET_VALUE(ask,"action","raw") ask =ENCODE (ask,cgi) http ="http://www.rosettacode.org/mw/index.php" url =CONCAT (http,"?",ask) data =REQUEST (url) header =FILTER_INDEX (data,header,-) sz_header=SIZE(header) line =CONCAT (title,"=",sz_header," members") FILE "tasks" = line all =APPEND(all,sz_header) ENDLOOP   ENDCOMPILE all =JOIN(all),sum=SUM(all),time=time() line=CONCAT (time,": ", sz_titles, " Programing Tasks: ", sum, " solutions")   FILE "tasks" = line  
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
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash SITE=https://www.rosettacode.org API=$SITE/mw/api.php PAGES=$SITE/mw/index.php query="$API?action=query" query+=$(printf '&%s' \ list=categorymembers \ cmtitle=Category:Programming_Tasks \ cmlimit=500) total=0 while read title; do t=${title// /_} tasks=$(curl -s "$PAGES?title=$t&action=raw" \ | grep -c '{{header|') printf '%s: %d examples.\n' "$title" "$tasks" let total+=tasks done < <(curl -s "$query&format=json" \ | jq -r '.query.categorymembers[].title')   printf '\nTotal: %d examples.\n' "$total"
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
#Objective-C
Objective-C
NSArray *haystack = @[@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo"]; for (id needle in @[@"Washington",@"Bush"]) { int index = [haystack indexOfObject:needle]; if (index == NSNotFound) NSLog(@"%@ is not in haystack", needle); else NSLog(@"%i %@", index, needle); }
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.
#R
R
  library(rvest) library(plyr) library(dplyr) options(stringsAsFactors=FALSE)   langUrl <- "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&prop=categoryinfo&gcmlimit=5000" langs <- html(langUrl) %>% html_nodes('page')   ff <- function(xml_node) { language <- xml_node %>% html_attr("title") language <- sub("^Category:", "", language) npages <- xml_node %>% html_nodes('categoryinfo') %>% html_attr("pages") c(language, npages) } tbl <- ldply(sapply(langs, ff), rbind) names(tbl) <- c("language", "n") tbl %>% mutate(n=as.integer(n)) %>% arrange(desc(n)) %>% head  
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
#BBC_BASIC
BBC BASIC
PRINT ;1999, FNroman(1999) PRINT ;2012, FNroman(2012) PRINT ;1666, FNroman(1666) PRINT ;3888, FNroman(3888) END   DEF FNroman(n%) LOCAL i%, r$, arabic%(), roman$() DIM arabic%(12), roman$(12) arabic%() = 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,1000 roman$() = "I","IV", "V","IX", "X","XL", "L","XC", "C","CD", "D","CM", "M" FOR i% = 12 TO 0 STEP -1 WHILE n% >= arabic%(i%) r$ += roman$(i%) n% -= arabic%(i%) ENDWHILE NEXT = r$
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#Bracmat
Bracmat
( unroman = nbr,lastVal,val . 0:?nbr:?lastVal & @( low$!arg  :  ?  %@?L ( ? & (m.1000) (d.500) (c.100) (l.50) (x.10) (v.5) (i.1)  : ? (!L.?val) ? & (!val:~>!lastVal|!val+-2*!lastVal) + !nbr  : ?nbr & !val:?lastVal & ~ ) ) | !nbr ) & (M.1000) (MCXI.1111) (CMXI.911) (MCM.1900) (MCMXC.1990) (MMVIII.2008) (MMIX.2009) (MCDXLIV.1444) (MDCLXVI.1666) (MMXII.2012)  : ?years & (test=.out$(!arg unroman$!arg)) & (  !years  : ? (?L.?D) (?&test$!L&~) | done );
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
#Go
Go
package main   import ( "fmt" "math" )   func main() { example := func(x float64) float64 { return x*x*x - 3*x*x + 2*x } findroots(example, -.5, 2.6, 1) }   func findroots(f func(float64) float64, lower, upper, step float64) { for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step { x1 = math.Min(x1, upper) r, status := secant(f, x0, x1) if status != "" && r >= x0 && r < x1 { fmt.Printf("  %6.3f %s\n", r, status) } } }   func secant(f func(float64) float64, x0, x1 float64) (float64, string) { var f0 float64 f1 := f(x0) for i := 0; i < 100; i++ { f0, f1 = f1, f(x1) switch { case f1 == 0: return x1, "exact" case math.Abs(x1-x0) < 1e-6: return x1, "approximate" } x0, x1 = x1, x1-f1*(x1-x0)/(f1-f0) } return 0, "" }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Euphoria
Euphoria
function weighted_rand(sequence table) integer sum,r sum = 0 for i = 1 to length(table) do sum += table[i] end for   r = rand(sum) for i = 1 to length(table)-1 do r -= table[i] if r <= 0 then return i end if end for return length(table) end function   constant names = { "Rock", "Paper", "Scissors" } constant winner = { "We tied.", "Meself winned.", "You win." } integer user_action, my_action, key, win sequence user_rec, score user_rec = {1,1,1} score = {0,0}   while 1 do my_action = remainder(weighted_rand(user_rec)+1,3)+1 puts(1,"Your choice [1-3]:\n") puts(1," 1. Rock\n 2. Paper\n 3. Scissors\n> ") key = -1 while (key < '1' or key > '3') and key != 'q' do key = get_key() end while puts(1,key) puts(1,'\n') if key = 'q' then exit end if user_action = key-'0' win = remainder(my_action-user_action+3,3) printf(1,"You chose %s; I chose %s. %s\n", { names[user_action], names[my_action], winner[win+1] })   if win then score[win] += 1 end if printf(1,"\nScore %d:%d\n",score) user_rec[user_action] += 1 end while
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.
#Forth
Forth
variable a : n>a (.) tuck a @ swap move a +! ; : >a a @ c! 1 a +! ; : encode ( c-addr +n a -- a n' ) dup a ! -rot over c@ 1 2swap 1 /string bounds ?do over i c@ = if 1+ else n>a >a i c@ 1 then loop n>a >a a @ over - ;   : digit? [char] 0 [ char 9 1+ literal ] within ; : decode ( c-addr +n a -- a n' ) dup a ! 0 2swap bounds ?do i c@ digit? if 10 * i c@ [char] 0 - + else a @ over i c@ fill a +! 0 then loop drop a @ over - ;
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.
#PARI.2FGP
PARI/GP
vector(n,k,exp(2*Pi*I*k/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.
#Pascal
Pascal
Program Roots;   var root: record // poor man's complex type. r: real; i: real; end; i, n: integer; angle: real;   begin for n := 2 to 7 do begin angle := 0.0; write(n, ': '); for i := 1 to n do begin root.r := cos(angle); root.i := sin(angle); write(root.r:8:5, root.i:8:5, 'i '); angle := angle + (2.0 * pi / n); end; writeln; end; 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.
#Pascal
Pascal
Program QuadraticRoots;   var a, b, c, q, f: double;   begin a := 1; b := -10e9; c := 1; q := sqrt(a * c) / b; f := (1 + sqrt(1 - 4 * q * q)) / 2;   writeln ('Version 1:'); writeln ('x1: ', (-b * f / a):16, ', x2: ', (-c / (b * f)):16);   writeln ('Version 2:'); q := sqrt(b * b - 4 * a * c); if b < 0 then begin f := (-b + q) / 2 * a; writeln ('x1: ', f:16, ', x2: ', (c / (a * f)):16); end else begin f := (-b - q) / 2 * a; writeln ('x1: ', (c / (a * f)):16, ', x2: ', f:16); end; 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
#Elena
Elena
import system'routines; import extensions; import extensions'text;   singleton rotConvertor { char convert(char ch) { if (($97 <= ch && ch <= $109) || ($65 <= ch && ch <= $77)) { ^ (ch.toInt() + 13).toChar() }; if (($110 <= ch && ch <= $122) || ($78 <= ch && ch <= $90)) { ^ (ch.toInt() - 13).toChar() };   ^ ch }   string convert(string s) = s.selectBy:(ch => rotConvertor.convert(ch)).summarize(new StringWriter()); }   public program() { if (program_arguments.Length > 1) { console.printLine(rotConvertor.convert(program_arguments[1])) } }
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 }
#Ruby
Ruby
def calc_rk4(f) return ->(t,y,dt){ ->(dy1 ){ ->(dy2 ){ ->(dy3 ){ ->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call( dt * f.call( t + dt , y + dy3 ))}.call( dt * f.call( t + dt/2, y + dy2/2 ))}.call( dt * f.call( t + dt/2, y + dy1/2 ))}.call( dt * f.call( t , y ))} end   TIME_MAXIMUM, WHOLE_TOLERANCE = 10.0, 1.0e-5 T_START, Y_START, DT = 0.0, 1.0, 0.10   def my_diff_eqn(t,y) ; t * Math.sqrt(y)  ; end def my_solution(t ) ; (t**2 + 4)**2 / 16  ; end def find_error(t,y) ; (y - my_solution(t)).abs  ; end def is_whole?(t ) ; (t.round - t).abs < WHOLE_TOLERANCE ; end   dy = calc_rk4( ->(t,y){my_diff_eqn(t,y)} )   t, y = T_START, Y_START while t <= TIME_MAXIMUM printf("y(%4.1f)\t= %12.6f \t error: %12.6e\n",t,y,find_error(t,y)) if is_whole?(t) t, y = t + DT, y + dy.call(t,y,DT) 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.
#TXR
TXR
$ txr -p '(read)' ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) [Ctrl-D][Enter] ((data "quoted data" 123 4.5) (data (! (sys:var #(4.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.
#Scala
Scala
  import scala.util.Random Random.setSeed(1)   def rollDice():Int = { val v4 = Stream.continually(Random.nextInt(6)+1).take(4) v4.sum - v4.min }   def getAttributes():Seq[Int] = Stream.continually(rollDice()).take(6)   def getCharacter():Seq[Int] = { val attrs = getAttributes() println("generated => " + attrs.mkString("[",",", "]")) (attrs.sum, attrs.filter(_>15).size) match { case (a, b) if (a < 75 || b < 2) => getCharacter case _ => attrs } }   println("picked => " + getCharacter.mkString("[", ",", "]"))  
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
#Vala
Vala
using Gee;   ArrayList<int> primes(int limit){ var sieve = new ArrayList<bool>(); var prime_list = new ArrayList<int>();   for(int i = 0; i <= limit; i++){ sieve.add(true); }   sieve[0] = false; sieve[1] = false;   for (int i = 2; i <= limit/2; i++){ if (sieve[i] != false){ for (int j = 2; i*j <= limit; j++){ sieve[i*j] = false; } } }   for (int i = 0; i < sieve.size; i++){ if (sieve[i] != false){ prime_list.add(i); } }   return prime_list; } // end primes   public static void main(){ var prime_list = primes(50);   foreach(var prime in prime_list) stdout.printf("%s ", prime.to_string());   stdout.printf("\n"); }
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
#Wren
Wren
/* rc_count_examples.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 url = "https://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" var content = getContent.call(url) var p = Pattern.new("title/=\"[+1^\"]\"") var matches = p.findAll(content) for (m in matches) { var title = m.capsText[0].replace("&#039;", "'").replace("&quot;", "\"") var title2 = title.replace(" ", "_").replace("+", "\%2B") var taskUrl = "https://www.rosettacode.org/mw/index.php?title=%(title2)&action=raw" var taskContent = getContent.call(taskUrl) var lines = taskContent.split("\n") var count = lines.count { |line| line.trim().startsWith("=={{header|") } System.print("%(title) : %(count) examples") }   curl.easyCleanup()
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
#OCaml
OCaml
# let find_index pred lst = let rec loop n = function [] -> raise Not_found | x::xs -> if pred x then n else loop (n+1) xs in loop 0 lst;; val find_index : ('a -> bool) -> 'a list -> int = <fun>   # let haystack = ["Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo"];; val haystack : string list = ["Zig"; "Zag"; "Wally"; "Ronald"; "Bush"; "Krusty"; "Charlie"; "Bush"; "Bozo"] # List.iter (fun needle -> try Printf.printf "%i %s\n" (find_index ((=) needle) haystack) needle with Not_found -> Printf.printf "%s is not in haystack\n" needle) ["Washington"; "Bush"];; Washington is not in haystack 4 Bush - : unit = ()
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.
#Racket
Racket
#lang racket   (require racket/hash net/url json)   (define limit 15) (define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1")) (define category "Category:Programming Languages") (define entries "entries")   (define api-url (string->url "http://rosettacode.org/mw/api.php")) (define (make-complete-url gcmcontinue) (struct-copy url api-url [query `([format . "json"] [action . "query"] [generator . "categorymembers"] [gcmtitle . ,category] [gcmlimit . "200"] [gcmcontinue . ,gcmcontinue] [continue . ""] [prop . "categoryinfo"])]))   (define @ hash-ref)   (define table (make-hash))   (let loop ([gcmcontinue ""]) (define resp (read-json (get-pure-port (make-complete-url gcmcontinue)))) (hash-union! table (for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))]) (values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0)))) (cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))   (for/fold ([prev #f] [rank #f] #:result (void)) ([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)]) (match-define (cons cat size) item) (define this-rank (if (equal? prev size) rank (add1 i))) (printf "Rank: ~a ~a ~a\n" (~a this-rank #:align 'right #:min-width 2) (~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14) (replacer cat)) (values size this-rank))
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
#BCPL
BCPL
get "libhdr"   let toroman(n, v) = valof $( let extract(n, val, rmn, v) = valof $( while n >= val $( n := n - val; for i=1 to rmn%0 do v%(v%0+i) := rmn%i v%0 := v%0 + rmn%0 $) resultis n $)   v%0 := 0 n := extract(n, 1000, "M", v) n := extract(n, 900, "CM", v) n := extract(n, 500, "D", v) n := extract(n, 400, "CD", v) n := extract(n, 100, "C", v) n := extract(n, 90, "XC", v) n := extract(n, 50, "L", v) n := extract(n, 40, "XL", v) n := extract(n, 10, "X", v) n := extract(n, 9, "IX", v) n := extract(n, 5, "V", v) n := extract(n, 4, "IV", v) n := extract(n, 1, "I", v) resultis v $)   let show(n) be $( let v = vec 50 writef("%I4 = %S*N", n, toroman(n, v)) $)   let start() be $( show(1666) show(2008) show(1001) show(1999) show(3888) show(2021) $)
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.
#C
C
#include <stdio.h>   int digits[26] = { 0, 0, 100, 500, 0, 0, 0, 0, 1, 1, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 10, 0, 0 };   /* assuming ASCII, do upper case and get index in alphabet. could also be inline int VALUE(char x) { return digits [ (~0x20 & x) - 'A' ]; } if you think macros are evil */ #define VALUE(x) digits[(~0x20 & (x)) - 'A']   int decode(const char * roman) { const char *bigger; int current; int arabic = 0; while (*roman != '\0') { current = VALUE(*roman); /* if (!current) return -1; note: -1 can be used as error code; Romans didn't even have zero */ bigger = roman;   /* look for a larger digit, like IV or XM */ while (VALUE(*bigger) <= current && *++bigger != '\0');   if (*bigger == '\0') arabic += current; else { arabic += VALUE(*bigger); while (roman < bigger) arabic -= VALUE(* (roman++) ); }   roman ++; } return arabic; }   int main() { const char * romans[] = { "MCmxC", "MMVIII", "MDClXVI", "MCXLUJ" }; int i;   for (i = 0; i < 4; i++) printf("%s\t%d\n", romans[i], decode(romans[i]));   return 0; }
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
#Haskell
Haskell
f x = x^3-3*x^2+2*x   findRoots start stop step eps = [x | x <- [start, start+step .. stop], abs (f x) < eps]
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.
#F.23
F#
open System   let random = Random () let rand = random.NextDouble () //Gets a random number in the range (0.0, 1.0)   /// Union of possible choices for a round of rock-paper-scissors type Choice = | Rock | Paper | Scissors   /// Gets the string representation of a Choice let getString = function | Rock -> "Rock" | Paper -> "Paper" | Scissors -> "Scissors"   /// Defines rules for winning and losing let beats (a : Choice, b : Choice) = match a, b with | Rock, Scissors -> true // Rock beats Scissors | Paper, Rock -> true // Paper beats Rock | Scissors, Paper -> true // Scissors beat Paper | _, _ -> false   /// Generates the next move for the computer based on probability derived from previous player moves. let genMove r p s = let tot = r + p + s let n = rand if n <= s / tot then Rock elif n <= (s + r) / tot then Paper else Scissors   /// Gets the move chosen by the player let rec getMove () = printf "[R]ock, [P]aper, or [S]cissors?: " let choice = Console.ReadLine () match choice with | "r" | "R" -> Rock | "p" | "P" -> Paper | "s" | "S" -> Scissors | _ -> printf "Invalid choice.\n\n" getMove ()   /// Place where all the game logic takes place. let rec game (r : float, p : float, s : float) = let comp = genMove r p s let player = getMove () Console.WriteLine ("Player: {0} vs Computer: {1}", getString player, getString comp) Console.WriteLine ( if beats(player, comp) then "Player Wins!\n" elif beats(comp, player) then "Computer Wins!\n" else "Draw!\n" ) let nextR = if player = Rock then r + 1.0 else r let nextP = if player = Paper then p + 1.0 else p let nextS = if player = Scissors then s + 1.0 else s game (nextR, nextP, nextS)   game(1.0, 1.0, 1.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.
#Fortran
Fortran
program RLE implicit none   integer, parameter :: bufsize = 100 ! Sets maximum size of coded and decoded strings, adjust as necessary character(bufsize) :: teststr = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" character(bufsize) :: codedstr = "", decodedstr = ""   call Encode(teststr, codedstr) write(*,"(a)") trim(codedstr) call Decode(codedstr, decodedstr) write(*,"(a)") trim(decodedstr)   contains   subroutine Encode(instr, outstr) character(*), intent(in) :: instr character(*), intent(out) :: outstr character(8) :: tempstr = "" character(26) :: validchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" integer :: a, b, c, i   if(verify(trim(instr), validchars) /= 0) then outstr = "Invalid input" return end if outstr = "" c = 1 a = iachar(instr(1:1)) do i = 2, len(trim(instr)) b = iachar(instr(i:i)) if(a == b) then c = c + 1 else write(tempstr, "(i0)") c outstr = trim(outstr) // trim(tempstr) // achar(a) a = b c = 1 end if end do write(tempstr, "(i0)") c outstr = trim(outstr) // trim(tempstr) // achar(b) end subroutine   subroutine Decode(instr, outstr) character(*), intent(in) :: instr character(*), intent(out) :: outstr character(26) :: validchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" integer :: startn, endn, n   outstr = "" startn = 1 do while(startn < len(trim(instr))) endn = scan(instr(startn:), validchars) + startn - 1 read(instr(startn:endn-1), "(i8)") n outstr = trim(outstr) // repeat(instr(endn:endn), n) startn = endn + 1 end do end subroutine end program
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.
#Perl
Perl
use Math::Complex;   foreach my $n (2 .. 10) { printf "%2d", $n; my @roots = root(1,$n); foreach my $root (@roots) { $root->display_format(style => 'cartesian', format => '%.3f'); print " $root"; } print "\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.
#Phix
Phix
with javascript_semantics for n=2 to 10 do printf(1,"%2d:",n) for root=0 to n-1 do atom real = cos(2*PI*root/n) atom imag = sin(2*PI*root/n) printf(1,"%s %6.3f %6.3fi",{iff(root?",":""),real,imag}) end for printf(1,"\n") end for
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.
#Perl
Perl
use Math::Complex;   ($x1,$x2) = solveQuad(1,2,3);   print "x1 = $x1, x2 = $x2\n";   sub solveQuad { my ($a,$b,$c) = @_; my $root = sqrt($b**2 - 4*$a*$c); return ( -$b + $root )/(2*$a), ( -$b - $root )/(2*$a); }
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.
#Phix
Phix
procedure solve_quadratic(sequence t3) atom {a,b,c} = t3, d = b*b-4*a*c, f string s = sprintf("for a=%g,b=%g,c=%g",t3), t sequence u if abs(d)<1e-6 then d=0 end if switch sign(d) do case 0: t = "single root is %g" u = {-b/2/a} case 1: t = "real roots are %g and %g" f = (1+sqrt(1-4*a*c/(b*b)))/2 u = {-f*b/a,-c/b/f} case-1: t = "complex roots are %g +/- %g*i" u = {-b/2/a,sqrt(-d)/2/a} end switch printf(1,"%-25s the %s\n",{s,sprintf(t,u)}) end procedure constant tests = {{1,-1E9,1}, {1,0,1}, {2,-1,-6}, {1,2,-2}, {0.5,1.4142135,1}, {1,3,2}, {3,4,5}} papply(tests,solve_quadratic)
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
#Elixir
Elixir
defmodule RC do def rot13(clist) do f = fn(c) when (?A <= c and c <= ?M) or (?a <= c and c <= ?m) -> c + 13 (c) when (?N <= c and c <= ?Z) or (?n <= c and c <= ?z) -> c - 13 (c) -> c end Enum.map(clist, f) end end   IO.inspect encode = RC.rot13('Rosetta Code') IO.inspect RC.rot13(encode)
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 }
#Run_BASIC
Run BASIC
y = 1 while t <= 10 k1 = t * sqr(y) k2 = (t + .05) * sqr(y + .05 * k1) k3 = (t + .05) * sqr(y + .05 * k2) k4 = (t + .1) * sqr(y + .1 * k3)   if right$(using("##.#",t),1) = "0" then print "y(";using("##",t);") ="; using("####.#######", y);chr$(9);"Error ="; (((t^2 + 4)^2) /16) -y y = y + .1 *(k1 + 2 * (k2 + k3) + k4) / 6 t = t + .1 wend end
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 }
#Rust
Rust
fn runge_kutta4(fx: &dyn Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 { let k1 = dx * fx(x, y); let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0); let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0); let k4 = dx * fx(x + dx, y + k3);   y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0 }   fn f(x: f64, y: f64) -> f64 { x * y.sqrt() }   fn actual(x: f64) -> f64 { (1.0 / 16.0) * (x * x + 4.0).powi(2) }   fn main() { let mut y = 1.0; let mut x = 0.0; let step = 0.1; let max_steps = 101; let sample_every_n = 10;   for steps in 0..max_steps { if steps % sample_every_n == 0 { println!("y({}):\t{:.10}\t\t {:E}", x, y, actual(x) - y) }   y = runge_kutta4(&f, x, y, step);   x = ((x * 10.0) + (step * 10.0)) / 10.0; } }
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.
#Wren
Wren
import "/pattern" for Pattern import "/fmt" for Fmt   var INDENT = 2   var parseSExpr = Fn.new { |str| var ipat = " \t\n\f\v\r()\"" var p = Pattern.new("""+0/s["+0^""|(|)|"|+1/I]""", Pattern.within, ipat) var t = p.findAll(str).map { |m| m.text }.toList if (t.count == 0) return null var o = false var c = 0 for (i in t.count-1..0) { var ti = t[i].trim() var nd = Num.fromString(ti) if (ti == "\"") return null if (ti == "(") { t[i] = "[" c = c + 1 } else if (ti == ")") { t[i] = "]" c = c - 1 } else if (nd) { var ni = Num.fromString(ti) t[i] = ni ? ni.toString : nd.toString } else if (ti.startsWith("\"")) { // escape embedded double quotes var temp = ti[1...-1] t[i] = "\"" + temp.replace("\"", "\\\"") + "\"" } if (i > 0 && t[i] != "]" && t[i - 1].trim() != "(") t.insert(i, ", ") if (c == 0) { if (!o) o = true else return null } } return (c != 0) ? null : t }   var toSExpr = Fn.new { |tokens| for (i in 0...tokens.count) { if (tokens[i] == "[") { tokens[i] = "(" } else if (tokens[i] == "]") { tokens[i] = ")" } else if (tokens[i] == ", ") { tokens[i] = " " } else if (tokens[i].startsWith("\"")) { // unescape embedded quotes var temp = tokens[i][1...-1] tokens[i] = "\"" + temp.replace("\\\"", "\"") + "\"" } } return tokens.join() }   var prettyPrint = Fn.new { |tokens| var level = 0 for (t in tokens) { var n if (t == ", " || t == " ") { continue } else if (t == "[" || t == "(") { n = level * INDENT + 1 level = level + 1 } else if (t == "]" || t == ")") { level = level - 1 n = level * INDENT + 1 } else { n = level * INDENT + t.count } Fmt.print("$*s", n, t) } }   var str = """((data "quoted data" 123 4.5)""" + "\n" + """ (data (!@# (4.5) "(more" "data)")))""" var tokens = parseSExpr.call(str) if (!tokens) { System.print("Invalid s-expr!") } else { System.print("Native data structure:") System.print(tokens.join()) System.print("\nNative data structure (pretty print):") prettyPrint.call(tokens)   System.print("\nRecovered S-Expression:") System.print(toSExpr.call(tokens)) System.print("\nRecovered S-Expression (pretty print):") prettyPrint.call(tokens) }
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: count is 0; var integer: total is 0; var integer: attribIdx is 0; var integer: diceroll is 0; var integer: sumOfRolls is 0; var array integer: attribute is 6 times 0; var array integer: dice is 4 times 0; begin repeat count := 0; total := 0; for key attribIdx range attribute do for key diceroll range dice do dice[diceroll] := rand(1, 6); end for; dice := sort(dice); sumOfRolls := 0; for diceroll range 2 to maxIdx(dice) do # Discard the lowest roll sumOfRolls +:= dice[diceroll]; end for; attribute[attribIdx] := sumOfRolls; total +:= sumOfRolls; if sumOfRolls >= 15 then incr(count); end if; end for; until total >= 75 and count >= 2; writeln("Attributes:"); for key attribIdx range attribute do writeln(attribIdx <& " ..... " <& attribute[attribIdx] lpad 2); end for; writeln(" ----"); writeln("Total " <& total lpad 3); end func;
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.
#True_BASIC
True BASIC
FUNCTION min(a, b) IF a < b THEN LET min = a ELSE LET min = b END FUNCTION   FUNCTION d6 LET d6 = 1 + INT(RND * 6) END FUNCTION   FUNCTION rollstat LET a = d6 LET b = d6 LET c = d6 LET d = d6 LET rollstat = a + b + c + d - min(min(a, b), min(c, d)) END FUNCTION   DIM statnames$(6) DATA "STR", "CON", "DEX", "INT", "WIS", "CHA" FOR i = 1 TO 6 READ statnames$(i) NEXT i DIM stat(6) LET acceptable = 0   RANDOMIZE  ! RANDOMIZE TIMER en QBasic DO LET sum = 0 LET n15 = 0 FOR i = 1 TO 6 LET stat(i) = rollstat LET sum = sum + stat(i) IF stat(i) >= 15 THEN LET n15 = n15 + 1 NEXT i IF sum >= 75 AND n15 >= 2 THEN LET acceptable = 1 LOOP UNTIL acceptable = 1   FOR i = 1 TO 6 PRINT statnames$(i); ": "; stat(i) NEXT i PRINT "--------" PRINT "TOT: "; sum END
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
#VAX_Assembly
VAX Assembly
000F4240 0000 1 n=1000*1000 0000 0000 2 .entry main,0 7E 7CFD 0002 3 clro -(sp) ;result buffer 5E DD 0005 4 pushl sp ;pointer to buffer 10 DD 0007 5 pushl #16 ;descriptor -> len of buffer 0009 6 02 DD 0009 7 pushl #2 ;1st candidate 000B 8 test: 09 46'AF 6E E1 000B 9 bbc (sp), b^bits, found ;bc - bit clear 0010 10 next: F3 6E 000F4240 8F F2 0010 11 aoblss #n, (sp), test ;+1: limit,index 04 0018 12 ret 0019 13 found: 04 AE 7F 0019 14 pushaq 4(sp) ;-> descriptor by ref 04 AE DF 001C 15 pushal 4(sp) ;-> prime on stack by ref 00000000'GF 02 FB 001F 16 calls #2, g^ots$cvt_l_ti ;convert integer to string 04 AE 7F 0026 17 pushaq 4(sp) ; 00000000'GF 01 FB 0029 18 calls #1, g^lib$put_output ;show result 0030 19 53 6E D0 0030 20 movl (sp), r3 0033 21 mult: 0002 53 6E 000F4240 8F F1 0033 22 acbl #n, (sp), r3, set_mult ;limit,add,index D1 11 003D 23 brb next 003F 24 set_mult: ;set bits for multiples EF 46'AF 53 E2 003F 25 bbss r3, b^bits, mult ;branch on bit set & set ED 11 0044 26 brb mult 0046 27 0001E892 0046 28 bits: .blkl <n+2+31>/32 E892 29 .end main
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
#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 } re:=RegExp(0'!\s+==\s*{{\s*header\s*\|!); // == {{ header | zkl foreach task in (getTasks("Programming_Tasks")){ page:=CURL().get( "http://www.rosettacode.org/mw/index.php?title=%s&action=raw" .fmt(CURL.urlEncode(task))); page=page[0].del(0,page[1]); // get rid of HTML header cnt,n:=0,0; while(re.search(page,True,n)){ cnt+=1; n=re.matched[0].sum(0); } "%4d: %s".fmt(cnt,task).println(); }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Oforth
Oforth
: needleIndex(needle, haystack) haystack indexOf(needle) dup ifNull: [ drop ExRuntime throw("Not found", needle) ] ;   [ "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz" ] const: Haystack   needleIndex("Bush", Haystack) println Haystack lastIndexOf("Bush") println needleIndex("Washington", Haystack) println
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.
#Raku
Raku
use HTTP::UserAgent; use URI::Escape; use JSON::Fast; use Sort::Naturally;   my $client = HTTP::UserAgent.new;   my $url = 'http://rosettacode.org/mw';   my $tablefile = './RC_Popularity.txt';   my %cat = ( 'Programming_Tasks' => 'Task', 'Draft_Programming_Tasks' => 'Draft' ); my %tasks;   for %cat.keys.sort -> $cat { mediawiki-query( $url, 'pages', :generator<categorymembers>, :gcmtitle("Category:$cat"), :gcmlimit<350>, :rawcontinue(), :prop<title> ).map({ %tasks{%cat{$cat}}++ }); }   my %counts = mediawiki-query( $url, 'pages', :generator<categorymembers>, :gcmtitle<Category:Programming Languages>, :gcmlimit<350>, :rawcontinue(), :prop<categoryinfo> ) .map({ my $title = .<title>.subst(/^'Category:'/, ''); my $tasks = (.<categoryinfo><pages> || 0); my $categories = (.<categoryinfo><subcats> || 0); my $total = (.<categoryinfo><size> || 0); $title => [$tasks ,$categories, $total] });   my $out = open($tablefile, :w) or die "$!\n";   # Add table boilerplate and header $out.say: "\{|class=\"wikitable sortable\"\n", "|+ As of { Date.today } :: {+%counts} Languages\n", '!Rank!!Language!!Task<br>Entries!!Tasks<br>done %!!Non-task<br>Subcate-<br>gories!!Total<br>Categories' ;   my @bg = <#fff; #ccc;>; my $ff = 0; my $rank = 1; my $ties = 0;   # Get sorted unique task counts for %counts.values»[0].unique.sort: -* -> $count { $ff++; # Get list of tasks with this count my @these = %counts.grep( *.value[0] == $count )».keys.sort: *.&naturally;   for @these { $ties++; $out.say: "|- style=\"background-color: { @bg[$ff % 2] }\"\n"~ "|$rank\n"~ "|[[:Category:$_|]]\n"~ "|$count\n"~ "|{(100 * $count/%tasks<Draft Task>.sum).round(.01)} %\n"~ "|{%counts{$_}[1]}\n"~ "|{%counts{$_}[2]}" } $rank += $ties; $ties = 0; } $out.say( "|}" ); $out.say('=' x 5, " query, download & processing: {(now - INIT now).round(.01)} seconds ", '=' x 5); $out.close;   sub mediawiki-query ($site, $type, *%query) { my $url = "$site/api.php?" ~ uri-query-string( :action<query>, :format<json>, :formatversion<2>, |%query); my $continue = '';   gather loop { my $response = $client.get("$url&$continue"); my $data = from-json($response.content); take $_ for $data.<query>.{$type}.values; $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last); } }   sub uri-query-string (*%fields) { join '&', %fields.map: { "{.key}={uri-escape .value}" } }
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
#Befunge
Befunge
&>0\0>00p:#v_$ >:#,_ $ @ 4-v >5+#:/#<\55+%:5/\5%: vv_$9+00g+5g\00g8+>5g\00 g>\20p>:10p00g \#v _20gv > 2+ v^-1g01\g5+8<^ +9 _ IVXLCDM
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.
#C.23
C#
using System; using System.Collections.Generic;   namespace Roman { internal class Program { private static void Main(string[] args) { // Decode and print the numerals. Console.WriteLine("{0}: {1}", "MCMXC", Decode("MCMXC")); Console.WriteLine("{0}: {1}", "MMVIII", Decode("MMVIII")); Console.WriteLine("{0}: {1}", "MDCLXVI", Decode("MDCLXVI")); }   // Dictionary to hold our numerals and their values. private static readonly Dictionary<char, int> RomanDictionary = new Dictionary<char, int> { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} };   private static int Decode(string roman) { /* Make the input string upper-case, * because the dictionary doesn't support lower-case characters. */ roman = roman.ToUpper();   /* total = the current total value that will be returned. * minus = value to subtract from next numeral. */ int total = 0, minus = 0;   for (int i = 0; i < roman.Length; i++) // Iterate through characters. { // Get the value for the current numeral. Takes subtraction into account. int thisNumeral = RomanDictionary[roman[i]] - minus;   /* Checks if this is the last character in the string, or if the current numeral * is greater than or equal to the next numeral. If so, we will reset our minus * variable and add the current numeral to the total value. Otherwise, we will * subtract the current numeral from the next numeral, and continue. */ if (i >= roman.Length - 1 || thisNumeral + minus >= RomanDictionary[roman[i + 1]]) { total += thisNumeral; minus = 0; } else { minus = thisNumeral; } }   return total; // Return the total. } } }
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
#HicEst
HicEst
OPEN(FIle='test.txt')   1 DLG(NameEdit=x0, DNum=3)   x = x0 chi2 = SOLVE(NUL=x^3 - 3*x^2 + 2*x, Unknown=x, I=iterations, NumDiff=1E-15) EDIT(Text='approximate exact ', Word=(chi2 == 0), Parse=solution)   WRITE(FIle='test.txt', LENgth=6, Name) x0, x, solution, chi2, iterations GOTO 1
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.
#Factor
Factor
USING: combinators formatting io kernel math math.ranges qw random sequences ; IN: rosetta-code.rock-paper-scissors   CONSTANT: thing qw{ rock paper scissors } CONSTANT: msg { "I win." "Tie!" "You win." }   : ai-choice ( r p s -- n ) 3dup + + nip [1,b] random { { [ 3dup nip >= ] [ 3drop 1 ] } { [ 3dup [ + ] dip >= ] [ 3drop 2 ] } [ 3drop 0 ] } cond ;   : player-choice ( -- n ) "r/p/s/q? " write readln qw{ r p s q } index dup [ drop player-choice ] unless ;   ! return: ! -1 for n1 loses to n2. ! 0 for n1 ties n2. ! 1 for n1 beats n2. : outcome ( n1 n2 -- n3 ) - dup abs 1 > [ neg ] when sgn ;   : status. ( seq -- ) "My wins: %d Ties: %d Your wins: %d\n" vprintf ;   : choices. ( n1 n2 -- ) [ thing nth ] bi@ "You chose: %s\nI chose: %s\n" printf ;   : tally ( seq n -- seq' ) over [ 1 + ] change-nth ;   : game ( seq -- seq' ) dup status. player-choice dup 3 = [ drop ] [ [ 3 + tally ] keep over 3 tail* first3 ai-choice 2dup choices. outcome 1 + dup [ tally ] dip msg nth print nl game ] if ;   ! The game state is a sequence where the members are: ! losses, ties, wins, #rock, #paper, #scissors : main ( -- ) { 0 0 0 1 1 1 } clone game drop ;   MAIN: main
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#FreeBASIC
FreeBASIC
  Dim As String initial, encoded, decoded   Function RLDecode(i As String) As String Dim As Long Loop0 dim as string rCount, outP, m   For Loop0 = 1 To Len(i) m = Mid(i, Loop0, 1) Select Case m Case "0" To "9" rCount += m Case Else If Len(rCount) Then outP += String(Val(rCount), m) rCount = "" Else outP += m End If End Select Next RLDecode = outP End Function   Function RLEncode(i As String) As String Dim As String tmp1, tmp2, outP Dim As Long Loop0, rCount   tmp1 = Mid(i, 1, 1) tmp2 = tmp1 rCount = 1   For Loop0 = 2 To Len(i) tmp1 = Mid(i, Loop0, 1) If tmp1 <> tmp2 Then outP += Ltrim(Rtrim(Str(rCount))) + tmp2 tmp2 = tmp1 rCount = 1 Else rCount += 1 End If Next   outP += Ltrim(Rtrim(Str(rCount))) outP += tmp2 RLEncode = outP End Function   Input "Type something: ", initial encoded = RLEncode(initial) decoded = RLDecode(encoded) Print initial Print encoded Print decoded End  
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (for N (range 2 10) (let Angle 0.0 (prin N ": ") (for I N (let Ipart (sin Angle) (prin (round (cos Angle) 4) (if (lt0 Ipart) "-" "+") "j" (round (abs Ipart) 4) " " ) ) (inc 'Angle (*/ 2 pi N)) ) (prinl) ) )
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.
#PL.2FI
PL/I
complex_roots: procedure (N); declare N fixed binary nonassignable; declare x float, c fixed decimal (10,8) complex; declare twopi float initial ((4*asin(1.0)));   do x = 0 to twopi by twopi/N; c = complex(cos(x), sin(x)); put skip list (c); end; end complex_roots;   1.00000000+0.00000000I 0.80901700+0.58778524I 0.30901697+0.95105654I -0.30901703+0.95105648I -0.80901706+0.58778518I -1.00000000-0.00000008I -0.80901694-0.58778536I -0.30901709-0.95105648I 0.30901712-0.95105648I 0.80901724-0.58778494I
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.
#Prolog
Prolog
  roots(N, Rs) :- succ(Pn, N), numlist(0, Pn, Ks), maplist(root(N), Ks, Rs).   root(N, M, R2) :- R0 is (2*M) rdiv N, % multiple of PI (R0 > 1 -> R1 is R0 - 2; R1 = R0), % adjust for principal values cis(R1, R2).   cis(0, 1) :- !. cis(1, -1) :- !. cis(1 rdiv 2, i) :- !. cis(-1 rdiv 2, -i) :- !. cis(-1 rdiv Q, exp(-i*pi/Q)) :- !. cis(1 rdiv Q, exp(i*pi/Q)) :- !. cis(P rdiv Q, exp(P*i*pi/Q)).  
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.
#PicoLisp
PicoLisp
(scl 40)   (de solveQuad (A B C) (let SD (sqrt (- (* B B) (* 4 A C))) (if (lt0 B) (list (*/ (- SD B) A 2.0) (*/ C 2.0 (*/ A A (- SD B) `(* 1.0 1.0))) ) (list (*/ C 2.0 (*/ A A (- 0 B SD) `(* 1.0 1.0))) (*/ (- 0 B SD) A 2.0) ) ) ) )   (mapcar round (solveQuad 1.0 -1000000.0 1.0) (6 .) )
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.
#PL.2FI
PL/I
  declare (c1, c2) float complex, (a, b, c, x1, x2) float;   get list (a, b, c); if b**2 < 4*a*c then do; c1 = (-b + sqrt(b**2 - 4+0i*a*c)) / (2*a); c2 = (-b - sqrt(b**2 - 4+0i*a*c)) / (2*a); put data (c1, c2); end; else do; x1 = (-b + sqrt(b**2 - 4*a*c)) / (2*a); x2 = (-b - sqrt(b**2 - 4*a*c)) / (2*a); put data (x1, x2); 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
#Emacs_Lisp
Emacs Lisp
(rot13-string "abc") ;=> "nop" (with-temp-buffer (insert "abc") (rot13-region (point-min) (point-max)) (buffer-string)) ;=> "nop"
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 }
#Scala
Scala
object Main extends App { val f = (t: Double, y: Double) => t * Math.sqrt(y) // Runge-Kutta solution val g = (t: Double) => Math.pow(t * t + 4, 2) / 16 // Exact solution new Calculator(f, Some(g)).compute(100, 0, .1, 1) }   class Calculator(f: (Double, Double) => Double, g: Option[Double => Double] = None) { def compute(counter: Int, tn: Double, dt: Double, yn: Double): Unit = { if (counter % 10 == 0) { val c = (x: Double => Double) => (t: Double) => { val err = Math.abs(x(t) - yn) f" Error: $err%7.5e" } val s = g.map(c(_)).getOrElse((x: Double) => "") // If we don't have exact solution, just print nothing println(f"y($tn%4.1f) = $yn%12.8f${s(tn)}") // Else, print Error estimation here } if (counter > 0) { val dy1 = dt * f(tn, yn) val dy2 = dt * f(tn + dt / 2, yn + dy1 / 2) val dy3 = dt * f(tn + dt / 2, yn + dy2 / 2) val dy4 = dt * f(tn + dt, yn + dy3) val y = yn + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6 val t = tn + dt compute(counter - 1, t, dt, y) } } }
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.
#UNIX_Shell
UNIX Shell
function main { typeset attrs=(str dex con int wis cha) typeset -A values typeset attr typeset -i value total fifteens while true; do fifteens=0 total=0 for attr in "${attrs[@]}"; do # "random" values repeat in zsh if run in a subshell r4d6drop >/tmp/$$ read value </tmp/$$ values[$attr]=$value (( total += value )) if (( value >= 15 )); then (( fifteens += 1 )) fi done if (( total >= 75 && fifteens >= 2 )); then break fi done rm -f /tmp/$$ for attr in "${attrs[@]}"; do printf '%s: %d\n' "$attr" "${values[$attr]}" done }   function r4d6drop { typeset -i d1=RANDOM%6+1 d2=RANDOM%6+1 d3=RANDOM%6+1 d4=RANDOM%6+1 typeset e=$(printf '%s\n' $d1 $d2 $d3 $d4 | sort -n | tail -n +2 | tr $'\n' +) printf '%d\n' $(( ${e%+} )) }   main "$@"  
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.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Dim r As New Random   Function getThree(n As Integer) As List(Of Integer) getThree = New List(Of Integer) For i As Integer = 1 To 4 : getThree.Add(r.Next(n) + 1) : Next getThree.Sort() : getThree.RemoveAt(0) End Function   Function getSix() As List(Of Integer) getSix = New List(Of Integer) For i As Integer = 1 To 6 : getSix.Add(getThree(6).Sum) : Next End Function   Sub Main(args As String()) Dim good As Boolean = False : Do Dim gs As List(Of Integer) = getSix(), gss As Integer = gs.Sum, hvc As Integer = gs.FindAll(Function(x) x > 14).Count Console.Write("attribs: {0}, sum={1}, ({2} sum, high vals={3})", String.Join(", ", gs), gss, If(gss >= 75, "good", "low"), hvc) good = gs.Sum >= 75 AndAlso hvc > 1 Console.WriteLine(" - {0}", If(good, "success", "failure")) Loop Until good End Sub End Module
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
#VBA
VBA
Sub primes() 'BRRJPA 'Prime calculation for VBA_Excel 'p is the superior limit of the range calculation 'This example calculates from 2 to 100000 and print it 'at the collum A   p = 100000   Dim nprimes(1 To 100000) As Integer b = Sqr(p)   For n = 2 To b   For k = n * n To p Step n nprimes(k) = 1   Next k Next n     For a = 2 To p If nprimes(a) = 0 Then c = c + 1 Range("A" & c).Value = a   End If Next a   End Sub
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
#ooRexx
ooRexx
-- ordered collections always return the first hit a = .array~of(1,2,3,4,4,5) say a~index(4) a2 = .array~new(5,5) -- multidimensional a2[3,3] = 4 -- the returned index is an array of values say a2~index(4)~makestring('line', ',') -- Note, list indexes are assigned when an item is added and -- are not tied to relative position l = .list~of(1,2,3,4,4,5) say l~index(4) q = .queue~of(1,2,3,4,4,5) say q~index(4) -- directories are unordered, so it is -- undertermined which one is returned d = .directory~new d["foo"] = 4 d["bar"] = 4 say d~index(4)
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.
#Red
Red
Red []   data: read http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000 lb: make block! 500 ;;data: read %data.html ;; for testing save html and use flat file arr: split data newline   k: "Category:" ;; exclude list: exrule: [thru ["programming" | "users" | "Implementations" | "Solutions by " | "Members" | "WikipediaSourced" | "Typing/Strong" | "Impl needed" ] to end ]   foreach line arr [ unless find line k [continue] parse line [ thru k thru ">" copy lang to "<" to end ] ;; extract/parse language if 20 < length? lang [continue] if parse lang [exrule] [continue] ;; exclude invalid cnt: 0  ;; parse number of entries parse line [thru "</a>" thru "(" copy cnt to " member" (cnt: to-integer cnt ) to end] if cnt > 25 [ append lb reduce [to-string lang cnt] ] ;; only process lang with > 25 entries ]   lb: sort/skip/compare lb 2 2  ;; sort series by entries   print reduce [ "Rank Entries Language" ]  ;; header   last: 0 rank: 0   lb: tail lb  ;; process the series backwards   until [ lb: skip lb -2 cnt: second lb if cnt <> last [ rank: rank + 1 ] print rejoin [ pad/left rank 4 "." pad/left cnt 5 " - " first lb ] last: cnt head? lb  ;; until head reached ]  
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
#BQN
BQN
⟨ToRoman⇐R⟩ ← { ds ← 1↓¨(¯1+`⊏⊸=)⊸⊔" I IV V IX X XL L XC C CD D CM M" vs ← 1e3∾˜ ⥊1‿4‿5‿9×⌜˜10⋆↕3 R ⇐ { 𝕨𝕊0: ""; (⊑⟜ds∾·𝕊𝕩-⊑⟜vs) 1-˜⊑vs⍋𝕩 } }
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.
#C.2B.2B
C++
  #include <exception> #include <string> #include <iostream> using namespace std;   namespace Roman { int ToInt(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } throw exception("Invalid character"); }   int ToInt(const string& s) { int retval = 0, pvs = 0; for (auto pc = s.rbegin(); pc != s.rend(); ++pc) { const int inc = ToInt(*pc); retval += inc < pvs ? -inc : inc; pvs = inc; } return retval; } }   int main(int argc, char* argv[]) { try { cout << "MCMXC = " << Roman::ToInt("MCMXC") << "\n"; cout << "MMVIII = " << Roman::ToInt("MMVIII") << "\n"; cout << "MDCLXVI = " << Roman::ToInt("MDCLXVI") << "\n"; } catch (exception& e) { cerr << e.what(); return -1; } return 0; }  
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
#Icon_and_Unicon
Icon and Unicon
procedure main() showRoots(f, -1.0, 4, 0.002) end   procedure f(x) return x^3 - 3*x^2 + 2*x end   procedure showRoots(f, lb, ub, step) ox := x := lb oy := f(x) os := sign(oy) while x <= ub do { if (s := sign(y := f(x))) = 0 then write(x) else if s ~= os then { dx := x-ox dy := y-oy cx := x-dx*(y/dy) write("~",cx) } (ox := x, oy := y, os := s) x +:= step } end   procedure sign(x) return (x<0, -1) | (x>0, 1) | 0 end
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:   Rock beats scissors   Scissors beat paper   Paper beats rock If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent. Extra credit Support additional choices   additional weapons.
#Forth
Forth
  include random.fs   0 value aiwins 0 value plwins   10 constant inlim 0 constant rock 1 constant paper 2 constant scissors   create rpshistory 0 , 0 , 0 , create inversemove 1 , 2 , 0 , 3 constant historylen   : @a ( n array -- ) swap cells + @ ;   : sum-history ( -- n ) 0 historylen 0 ?do i rpshistory @a 1+ + loop ;   : probable-choice ( -- n ) \ Simple linear search sum-history random historylen 0 ?do i rpshistory @a - dup 0< if drop i leave then loop inversemove @a ;   : rps-print ( addr u -- ) cr type ;   : rpslog. ( -- ) s" ROCK PAPER SCISSORS AI/W PL/W" rps-print cr 3 0 do i cells rpshistory + @ 9 u.r loop aiwins 7 u.r plwins 6 u.r cr ;   create rpswords ' rock , ' paper , ' scissors , ' quit ,   : update-history! ( n -- ) cells rpshistory + 1 swap +! ;   : thrown. ( n -- addr u ) cells rpswords + @ name>string ;   : throws. ( n n -- ) thrown. s" AI threw: " 2swap s+ rps-print thrown. s" You threw: " 2swap s+ rps-print ;   : print-throws ( n n -- ) rpslog. throws. ;   : tie. ( n n -- ) s" Tie. " rps-print ;   : plwin ( n n -- ) 1 +to plwins s" You win. " rps-print ;   : aiwin ( n n -- ) 1 +to aiwins s" AI wins. " rps-print ;   create rpsstates ' tie. , ' plwin , ' aiwin ,   : determine-winner ( n n -- ) >r abs r> abs - 3 + 3 mod cells rpsstates + @ execute ;   : rps-validate ( name -- ) ( Rude way of checking for only valid commands ) 4 0 do i cells rpswords + @ over = swap loop drop or or or ;   : rps-prompt. ( -- ) s" Enter choice (rock, paper, scissors or quit): " rps-print ;   : player-choice ( -- n ) recursive pad inlim accept pad swap find-name dup rps-validate if execute else drop rps-prompt. player-choice then ;   : update-log ( n n -- ) update-history! update-history! ;   : rps ( -- ) recursive rps-prompt. player-choice probable-choice 2dup update-log 2dup print-throws determine-winner rps ;  
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.
#Gambas
Gambas
Public Sub Main() Dim sString As String = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" Dim siCount As Short = 1 Dim siStart As Short = 1 Dim sHold As New String[] Dim sTemp As String   sString &= " "   Repeat sTemp = Mid(sString, siCount, 1) Do Inc siCount If Mid(sString, siCount, 1) <> sTemp Then Break If siCount = Len(sString) Then Break Loop sHold.add(Str(siCount - siStart) & sTemp) siStart = siCount Until siCount = Len(sString)   Print sString & gb.NewLine & sHold.Join(", ")   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.
#PureBasic
PureBasic
OpenConsole() For n = 2 To 10 angle = 0 PrintN(Str(n)) For i = 1 To n x.f = Cos(Radian(angle)) y.f = Sin(Radian(angle)) PrintN( Str(i) + ": " + StrF(x, 6) + " / " + StrF(y, 6)) angle = angle + (360 / n) Next Next Input()
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.
#Python
Python
import cmath     class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0.0' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip   def pureImag(self): return abs(self.real) < 0.000005   def pureReal(self): return abs(self.imag) < 0.000005     def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) # in pre-Python 2.6: # return (Complex(cmath.exp(2j*k*cmath.pi/n)) for k in range(n))     for nr in range(2, 11): print(nr, list(croots(nr)))
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.
#Python
Python
#!/usr/bin/env python3   import math import cmath import numpy   def quad_discriminating_roots(a,b,c, entier = 1e-5): """For reference, the naive algorithm which shows complete loss of precision on the quadratic in question. (This function also returns a characterization of the roots.)""" discriminant = b*b - 4*a*c a,b,c,d =complex(a), complex(b), complex(c), complex(discriminant) root1 = (-b + cmath.sqrt(d))/2./a root2 = (-b - cmath.sqrt(d))/2./a if abs(discriminant) < entier: return "real and equal", abs(root1), abs(root1) if discriminant > 0: return "real", root1.real, root2.real return "complex", root1, root2   def middlebrook(a, b, c): try: q = math.sqrt(a*c)/b f = .5+ math.sqrt(1-4*q*q)/2 except ValueError: q = cmath.sqrt(a*c)/b f = .5+ cmath.sqrt(1-4*q*q)/2 return (-b/a)*f, -c/(b*f)   def whatevery(a, b, c): try: d = math.sqrt(b*b-4*a*c) except ValueError: d = cmath.sqrt(b*b-4*a*c) if b > 0: return div(2*c, (-b-d)), div((-b-d), 2*a) else: return div((-b+d), 2*a), div(2*c, (-b+d))   def div(n, d): """Divide, with a useful interpretation of division by zero.""" try: return n/d except ZeroDivisionError: if n: return n*float('inf') return float('nan')   testcases = [ (3, 4, 4/3), # real, equal (3, 2, -1), # real, unequal (3, 2, 1), # complex (1, -1e9, 1), # ill-conditioned "quadratic in question" required by task. (1, -1e100, 1), (1, -1e200, 1), (1, -1e300, 1), ]   print('Naive:') for c in testcases: print("{} {:.5} {:.5}".format(*quad_discriminating_roots(*c)))   print('\nMiddlebrook:') for c in testcases: print(("{:.5} "*2).format(*middlebrook(*c)))   print('\nWhat Every...') for c in testcases: print(("{:.5} "*2).format(*whatevery(*c)))   print('\nNumpy:') for c in testcases: print(("{:.5} "*2).format(*numpy.roots(c)))
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
#Erlang
Erlang
rot13(Str) -> F = fun(C) when (C >= $A andalso C =< $M); (C >= $a andalso C =< $m) -> C + 13; (C) when (C >= $N andalso C =< $Z); (C >= $n andalso C =< $z) -> C - 13; (C) -> C end, lists:map(F, Str).
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 }
#Sidef
Sidef
func runge_kutta(yp) { func (t, y, δt) { var a = (δt * yp(t, y)); var b = (δt * yp(t + δt/2, y + a/2)); var c = (δt * yp(t + δt/2, y + b/2)); var d = (δt * yp(t + δt, y + c)); (a + 2*(b + c) + d) / 6; } }   define δt = 0.1; var δy = runge_kutta(func(t, y) { t * y.sqrt });   var(t, y) = (0, 1); loop { t.is_int && printf("y(%2d) = %12f ± %e\n", t, y, abs(y - ((t**2 + 4)**2 / 16))); t <= 10 || break; y += δy(t, y, δt); t += δt; }
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.
#Wren
Wren
import "random" for Random import "/sort" for Sort   var rand = Random.new() var vals = List.filled(6, 0) while (true) { for (i in 0..5) { var rns = List.filled(4, 0) for (j in 0..3) rns[j] = rand.int(1, 7) var sum = rns.reduce { |acc, n| acc + n } Sort.insertion(rns) vals[i] = sum - rns[0] } var total = vals.reduce { |acc, n| acc + n } if (total >= 75) { var fifteens = vals.count { |n| n >= 15 } if (fifteens >= 2) { System.print("The six values are: %(vals)") System.print("Their total is: %(total)") break } } }
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
#VBScript
VBScript
  Dim sieve() If WScript.Arguments.Count>=1 Then n = WScript.Arguments(0) Else n = 99 End If ReDim sieve(n) For i = 1 To n sieve(i) = True Next For i = 2 To n If sieve(i) Then For j = i * 2 To n Step i sieve(j) = False Next End If Next For i = 2 To n If sieve(i) Then WScript.Echo i Next  
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
#Oz
Oz
declare %% Lazy list of indices of Y in Xs. fun {Indices Y Xs} for X in Xs I in 1;I+1 yield:Yield do if Y == X then {Yield I} end end end   fun {Index Y Xs} case {Indices Y Xs} of X|_ then X else raise index(elementNotFound Y) end end end   Haystack = ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"] in {Show {Index "Bush" Haystack}} {Show {List.last {Indices "Bush" Haystack}}}   {Show {Index "Washington" Haystack}} %% throws
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.
#REXX
REXX
/*REXX program reads two files and displays a ranked list of Rosetta Code languages.*/ parse arg catFID lanFID outFID . /*obtain optional arguments from the CL*/ call init /*initialize some REXX variables. */ call get /*obtain data from two separate files. */ call eSort #,0 /*sort languages along with members. */ call tSort /* " " that are tied in rank.*/ call eSort #,1 /* " " along with members. */ call out /*create the RC_POP.OUT (output) file.*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do jc=length(_)-3 to 1 by -3; _= insert(",",_,jc); end; return _ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ eSort: procedure expose #. @. !tr.; arg N,p2; h= N /*sort: number of members*/ do while h>1; h= h % 2 /*halve number of records*/ do i=1 for N-h; j= i; k= h + i /*sort this part of list.*/ if p2 then do while !tR.k==!tR.j & @.k>@.j /*this uses a hard swap ↓*/ @= @.j; #= !tR.j; @.j= @.k;  !tR.j= !tR.k; @.k= @;  !tR.k= # if h>=j then leave; j= j - h; k= k - h end /*while !tR.k==···*/ else do while #.k<#.j /*this uses a hard swap ↓*/ @= @.j; #= #.j; @.j= @.k; #.j= #.k; @.k= @; #.k= # if h>=j then leave; j= j - h; k= k - h end /*while #.k<···*/ end /*i*/ /*hard swaps needed for embedded blanks.*/ end /*while h>1*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ get: langs= 0; call rdr 'languages' /*assign languages ───► L.ααα */ call rdr 'categories' /*append categories ───► catHeap */ #= 0 do j=1 until catHeap=='' /*process the heap of categories. */ parse var catHeap cat.j (sep) catHeap /*get a category from the catHeap. */ parse var cat.j cat.j '<' "(" mems . /*untangle the strange─looking string. */ cat.j= space(cat.j); ?=cat.j; upper ? /*remove any superfluous blanks. */ if ?=='' | \L.? then iterate /*it's blank or it's not a language. */ if pos(',', mems)\==0 then mems= space(translate(mems,,","), 0) /*¬commas.*/ if \datatype(mems, 'W') then iterate /*is the "members" number not numeric? */ #.0= #.0 + mems /*bump the number of members found. */ if u.?\==0 then do; do f=1 for # until [email protected] end /*f*/ #.f= #.f + mems; iterate j /*languages in different cases.*/ end /* [↑] handle any possible duplicates.*/ u.?= u.? + 1; #= # + 1 /*bump a couple of counters. */ #.#= #.# + mems; @.#= cat.j; @u.#=? /*bump the counter; assign it (upper).*/ end /*j*/    !.=; @tno= '(total) number of' /*array holds indication of TIED langs.*/ call tell right(commas(#), 9) @tno 'languages detected in the category file' call tell right(commas(langs),9) ' " " " " " " " language " call tell right(commas(#.0), 9) @tno 'entries (solutions) detected', , 1; term= 0 return /*don't show any more msgs──►term. [↑] */ /*──────────────────────────────────────────────────────────────────────────────────────*/ init: sep= '█'; L.=0; #.=0; u.=#.; catHeap=; term=1; old.= /*assign some REXX vars*/ if catFID=='' then catFID= "RC_POP.CAT" /*Not specified? Then use the default.*/ if lanFID=='' then lanFID= "RC_POP.LAN" /* " " " " " " */ if outFID=='' then outFID= "RC_POP.OUT" /* " " " " " " */ call tell center('timestamp: ' date() time("Civil"),79,'═'), 2, 1; return /*──────────────────────────────────────────────────────────────────────────────────────*/ out: w= length( commas(#) ); rank= 0 /* [↓] show by ascending rank of lang.*/ do t=# by -1 for #; rank= rank + 1 /*bump rank of a programming language. */ call tell right('rank:' right(commas(!tR.t), w), 20-1) right(!.t, 7), right('('commas(#.t) left("entr"s(#.t, 'ies', "y")')', 9), 20) @.t end /*#*/ /* [↑] S(···) pluralizes a word. */ call tell left('', 27) "☼ end─of─list. ☼", 1, 2; return /*bottom title.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ rdr: arg which 2; igAst= 1 /*ARG uppers WHICH, obtain the 1st char*/ if which=='L' then inFID= lanFID /*use this fileID for the languages. */ if which=='C' then inFID= catFID /* " " " " " categories. */ Uyir= 'α«ëα«»α«┐α«░α»ì/Uyir' /*Unicode (in text) name for Uyir */ old.0= '╬£C++'  ; new.0= "µC++" /*Unicode ╬£C++ ───► ASCII─8: µC++ */ old.1= 'UC++'  ; new.1= "µC++" /*old UC++ ───► ASCII─8: µC++ */ old.2= '╨£╨Ü-'  ; new.2= "MK-" /*Unicode ╨£╨Ü─ ───► ASCII-8: MK- */ old.3= 'D├⌐j├á'  ; new.3= "Déjà" /*Unicode ├⌐j├á ───► ASCII─8: Déjà */ old.4= 'Cach├⌐'  ; new.4= "Caché" /*Unicode Cach├⌐ ───► ASCII─8: Caché */ old.5= '??-61/52'  ; new.5= "MK-61/52" /*somewhere past, a mis─translated: MK-*/ old.6= 'F┼ìrmul├ª' ; new.6= 'Fôrmulæ' /*Unicode ───► ASCII─8: Fôrmulæ */ old.7= '╨£iniZinc' ; new.7= 'MiniZinc' /*Unicode ───► ASCII─8: MiniZinc*/ old.8= Uyir  ; new.8= 'Uyir' /*Unicode ───► ASCII─8: Uyir */ old.9= 'Perl 6'  ; new.9= 'Raku' /* (old name) ───► (new name) */   do recs=0 while lines(inFID) \== 0 /*read a file, a single line at a time.*/ $= translate( linein(inFID), , '9'x) /*handle any stray TAB ('09'x) chars.*/ $$= space($); if $$=='' then iterate /*ignore all blank lines in the file(s)*/ do v=0 while old.v \== '' /*translate Unicode variations of langs*/ if pos(old.v, $$) \==0 then $$= changestr(old.v, $$, new.v) end /*v*/ /* [↑] handle different lang spellings*/ if igAst then do; igAst= pos(' * ', $)==0; if igAst then iterate; end if pos('RETRIEVED FROM', translate($$))\==0 then leave /*pseudo End─Of─Data?.*/ if which=='L' then do; if left($$, 1)\=="*" then iterate /*lang ¬legitimate?*/ parse upper var $$ '*' $$ "<"; $$= space($$) if $$=='' then iterate; L.$$= 1 langs= langs + 1 /*bump number of languages found. */ iterate end /* [↓] extract computer language name.*/ if left($$, 1)=='*' then $$= sep || space( substr($$, 2) ) catHeap= catHeap $$ /*append to the catHeap (CATegory) heap*/ end /*recs*/ call tell right( commas(recs), 9) 'records read from file: ' inFID return /*──────────────────────────────────────────────────────────────────────────────────────*/ tell: do '0'arg(2); call lineout outFID," "  ; if term then say ; end call lineout outFID,arg(1)  ; if term then say arg(1) do '0'arg(3); call lineout outFID," "  ; if term then say ; end return /*show BEFORE blank lines (if any), message, show AFTER blank lines.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ tSort: tied=; r= 0 /*add true rank (tR) ───► the entries. */ do j=# by -1 for #; r= r+1; tR= r;  !tR.j= r; jp= j+1; jm= j-1 if tied=='' then pR= r; tied= /*handle when language rank is untied. */ if #.j==#.jp | #.j==#.jm then do;  !.j= '[tied]'; tied= !.j; end if #.j==#.jp then do; tR= pR;  !tR.j= pR; end else pR= r end /*j*/; return