task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Roman_numerals/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 decima...
#AutoHotkey
AutoHotkey
Roman_Decode(str){ res := 0 Loop Parse, str { n := {M: 1000, D:500, C:100, L:50, X:10, V:5, I:1}[A_LoopField] If ( n > OldN ) && OldN res -= 2*OldN res += n, oldN := n } return res }   test = MCMXC|MMVIII|MDCLXVI Loop Parse, test, | res .= A_LoopField "`t= " Roman_Decode(A_LoopField) "`r`n" clipboard :...
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
#Delphi
Delphi
type TFunc = function (x : Float) : Float;   function f(x : Float) : Float; begin Result := x*x*x-3.0*x*x +2.0*x; end;   const e = 1.0e-12;   function Secant(xA, xB : Float; f : TFunc) : Float; const limit = 50; var fA, fB : Float; d : Float; i : Integer; begin fA := f(xA); for i := 0 to limit do b...
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: ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace RockPaperScissors { class Program { static void Main(string[] args) { // There is no limit on the amount of weapons supported by RPSGame. Matchups are calculated depending on the order. var 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...
#Emacs_Lisp
Emacs Lisp
(defun run-length-encode (str) (let (output) (with-temp-buffer (insert str) (goto-char (point-min)) (while (not (eobp)) (let* ((char (char-after (point))) (count (skip-chars-forward (string char)))) (push (format "%d%c" count char) output)))) (mapconcat #'ide...
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.
#Lambdatalk
Lambdatalk
  // cleandisp just to display 0 when n < 10^-10 {def cleandisp {lambda {:n} {if {<= {abs :n} 1.e-10} then 0 else :n}}} -> cleandisp   {def uroots {lambda {:n} {S.map {{lambda {:n :i} {let { {:theta {/ {* 2 {PI} :i} :n}} } {cons {cleandisp {cos :theta}} ...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Tcl
Tcl
package require Tcl 8.5 package require http package require json package require textutil::split package require uri   proc getUrlWithRedirect {base args} { set url $base?[http::formatQuery {*}$args] while 1 { set t [http::geturl $url] if {[http::status $t] ne "ok"} { error "Oops: url=$url\nstatus=$s\nh...
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 n...
#Liberty_BASIC
Liberty BASIC
a=1:b=2:c=3 'assume a<>0 print quad$(a,b,c) end   function quad$(a,b,c) D=b^2-4*a*c x=-1*b if D<0 then quad$=str$(x/(2*a));" +i";str$(sqr(abs(D))/(2*a));" , ";str$(x/(2*a));" -i";str$(sqr(abs(D))/abs(2*a)) else quad$=str$(x/(2*a)+sqr(D)/(2*a));" , ";str$(x/(2*a)-sqr(D)/(2*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 inpu...
#Common_Lisp
Common Lisp
(defconstant +alphabet+ '(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z))   (defun rot13 (s) (map 'string (lambda (c &aux (n (position (char-upcase c) +alphabet+))) (if n (funcall (if (lower-case-p c) #'char-downcase #'identity) ...
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: ...
#Phix
Phix
with javascript_semantics constant dt = 0.1 atom y = 1.0 printf(1," x true/actual y calculated y relative error\n") printf(1," --- ------------- ------------- --------------\n") for i=0 to 100 do atom t = i*dt if integer(t) then atom act = power(t*t+4,2)/16 printf(1,"%4.1f  %14.9f...
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). ...
#Raku
Raku
grammar S-Exp { rule TOP {^ <s-list> $};   token s-list { '(' ~ ')' [ <in_list>+ % [\s+] | '' ] } token in_list { <s-token> | <s-list> }   proto token s-token {*} token s-token:sym<Num> {\d*\.?\d+} token s-token:sym<String> {'"' ['\"' |<-[\\"]>]*? '"'} #' token s-token:sym<Atom> {<-[()\s]>+}   } ...
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...
#Quackery
Quackery
[ 0 swap witheach + ] is sum ( [ --> n )   [ 0 ]'[ rot witheach [ over do swap dip + ] drop ] is count ( [ --> n )   [ [] 4 times [ 6 random 1+ join ] sort behead drop sum ] is attribute ( --> n )   [ [] 6 times [ attribute join ] ] is raw ( --> [ )   [ du...
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...
#Racket
Racket
#lang racket   (define (d6 . _) (+ (random 6) 1))   (define (best-3-of-4d6 . _) (apply + (rest (sort (build-list 4 d6) <))))   (define (generate-character) (let* ((rolls (build-list 6 best-3-of-4d6)) (total (apply + rolls))) (if (or (< total 75) (< (length (filter (curryr >= 15) rolls)) 2)) (...
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...
#Stata
Stata
prog def sieve args n clear qui set obs `n' gen long p=_n gen byte a=_n>1 forv i=2/`n' { if a[`i'] { loc j=`i'*`i' if `j'>`n' { continue, break } forv k=`j'(`i')`n' { qui replace a=0 in `k' } } } qui keep if a drop a end
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Python
Python
from urllib.request import urlopen, Request import xml.dom.minidom   r = Request( 'https://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml', headers={'User-Agent': 'Mozilla/5.0'}) x = urlopen(r)   tasks = [] for i in xml.dom.minidom.parseStrin...
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 AP...
#R
R
  library(XML) library(RCurl) doc <- xmlInternalTreeParse("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml") nodes <- getNodeSet(doc,"//cm") titles = as.character( sapply(nodes, xmlGetAttr, "title") ) headers <- list() counts <- list() for...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
haystack = {"Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"}; needle = "Zag"; first = Position[haystack,needle,1][[1,1]] last = Position[haystack,needle,1][[-1,1]] all = Position[haystack,needle,1][[All,1]]
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 ...
#MATLAB
MATLAB
stringCollection = {'string1','string2',...,'stringN'}
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,...
#Perl
Perl
use 5.010; use MediaWiki::API;   my $api = MediaWiki::API->new( { api_url => 'http://rosettacode.org/mw/api.php' } );   my @languages; my $gcmcontinue; while (1) { my $apih = $api->api( { action => 'query', generator => 'categorymembers', gcmtitle => 'Category...
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 numeral...
#AutoHotkey
AutoHotkey
MsgBox % stor(444)   stor(value) { romans = M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I M := 1000 CM := 900 D := 500 CD := 400 C := 100 XC := 90 L := 50 XL := 40 X := 10 IX := 9 V := 5 IV := 4 I := 1 Loop, Parse, romans, `, { While, value >= %A_LoopField% { result .= A_LoopField ...
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 decima...
#AWK
AWK
# syntax: GAWK -f ROMAN_NUMERALS_DECODE.AWK BEGIN { leng = split("MCMXC MMVIII MDCLXVI",arr," ") for (i=1; i<=leng; i++) { n = arr[i] printf("%s = %s\n",n,roman2arabic(n)) } exit(0) } function roman2arabic(r, a,i,p,q,u,ua,una,unr) { r = toupper(r) unr = "MDCLXVI" # each Roman numera...
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
#DWScript
DWScript
type TFunc = function (x : Float) : Float;   function f(x : Float) : Float; begin Result := x*x*x-3.0*x*x +2.0*x; end;   const e = 1.0e-12;   function Secant(xA, xB : Float; f : TFunc) : Float; const limit = 50; var fA, fB : Float; d : Float; i : Integer; begin fA := f(xA); for i := 0 to limit do b...
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: ...
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //------------------------------------------------------------------------------- using namespace std;   //------------------------------------------------------------------------------- enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum inde...
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...
#Erlang
Erlang
-module(rle).   -export([encode/1,decode/1]).   -include_lib("eunit/include/eunit.hrl").   encode(S) -> doEncode(string:substr(S, 2), string:substr(S, 1, 1), 1, []).   doEncode([], CurrChar, Count, R) -> R ++ integer_to_list(Count) ++ CurrChar; doEncode(S, CurrChar, Count, R) -> NextChar = string:substr(S, ...
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Liberty_BASIC
Liberty BASIC
WindowWidth =400 WindowHeight =400   'nomainwin   open "N'th Roots of One" for graphics_nsb_nf as #w   #w "trapclose [quit]"   for n =1 To 10 angle =0 #w "font arial 16 bold" print n; "th roots." #w "cls" #w "size 1 ; goto 200 200 ; down ; color lightgray ; circle 150 ; size 10 ; set 200 200 ; size...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Wren
Wren
import "/ioutil" for FileUtil import "/pattern" for Pattern import "/set" for Set import "/sort" for Sort import "/fmt" for Fmt   var p = Pattern.new("/=/={{header/|[+0/y]}}/=/=", Pattern.start) var bareCount = 0 var bareLang = {} for (fileName in ["example.txt", "example2.txt", "example3.txt"]) { var lines = FileU...
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 n...
#Logo
Logo
to quadratic :a :b :c localmake "d sqrt (:b*:b - 4*:a*:c) if :b < 0 [make "d minus :d] output list (:d-:b)/(2*:a) (2*:c)/(:d-:b) 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 n...
#Lua
Lua
function qsolve(a, b, c) if b < 0 then return qsolve(-a, -b, -c) end val = b + (b^2 - 4*a*c)^(1/2) --this never exhibits instability if b > 0 return -val / (2 * a), -2 * c / val --2c / val is the same as the "unstable" second root end   for i = 1, 12 do print(qsolve(1, 0-10^i, 1)) 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 inpu...
#Cubescript
Cubescript
alias rot13 [ push alpha [ "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" "a b c d e f g h i j k l m n o p q r s t u v w x y z" ] [ push chars [] [ loop i (strlen $arg1) [ looplist n $alpha [ if (! (listlen $chars)) [ alias chars (? (> (listindex $n (substr $arg1 $i 1)) -1) $n []) ] ] ...
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: ...
#PL.2FI
PL/I
  Runge_Kutta: procedure options (main); /* 10 March 2014 */ declare (y, dy1, dy2, dy3, dy4) float (18); declare t fixed decimal (10,1); declare dt float (18) static initial (0.1);   y = 1; do t = 0 to 10 by 0.1; dy1 = dt * ydash(t, y); dy2 = dt * ydash(t + dt/2, y + dy1/2); d...
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: ...
#PowerShell
PowerShell
  function Runge-Kutta (${function:F}, ${function:y}, $y0, $t0, $dt, $tEnd) { function RK ($tn,$yn) { $y1 = $dt*(F -t $tn -y $yn) $y2 = $dt*(F -t ($tn + (1/2)*$dt) -y ($yn + (1/2)*$y1)) $y3 = $dt*(F -t ($tn + (1/2)*$dt) -y ($yn + (1/2)*$y2)) $y4 = $dt*(F -t ($tn + $dt) -y ($yn + $y3...
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). ...
#REXX
REXX
/*REXX program parses an S-expression and displays the results to the terminal. */ input= '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))' say center('input', length(input), "═") /*display the header title to terminal.*/ say input /* " " ...
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#R
R
genStats <- function() { stats <- c(STR = 0, DEX = 0, CON = 0, INT = 0, WIS = 0, CHA = 0) for(i in seq_along(stats)) { results <- sample(6, 4, replace = TRUE) stats[i] <- sum(results[-which.min(results)]) } if(sum(stats >= 15) < 2 || (stats["TOT"] <- sum(stats)) < 75) Recall() else stats } print(genS...
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...
#Swift
Swift
import Foundation // for sqrt() and Date()   let max = 1_000_000 let maxroot = Int(sqrt(Double(max))) let startingPoint = Date()   var isprime = [Bool](repeating: true, count: max+1 ) for i in 2...maxroot { if isprime[i] { for k in stride(from: max/i, through: i, by: -1) { if isprime[k] { ...
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 AP...
#Racket
Racket
  #lang racket   (require net/url net/uri-codec json (only-in racket/dict [dict-ref ref]))   (define (RC-get verb params) ((compose1 get-pure-port string->url format) "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params)))   (define (get-category catname) (let loop ([c #f]) (define t ...
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 AP...
#Raku
Raku
use HTTP::UserAgent; use URI::Escape; use JSON::Fast; use Lingua::EN::Numbers :short;   unit sub MAIN ( Bool :nf(:$no-fetch) = False, :t(:$tier) = 1 );   # Friendlier descriptions for task categories my %cat = ( 'Programming_Tasks' => 'Task', 'Draft_Programming_Tasks' => 'Draft' );   my $client = HTTP::UserAgen...
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 ...
#Maxima
Maxima
haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"]; needle: "Zag";   findneedle(needle, haystack, [opt]):=block([idx], idx: sublist_indices(haystack, lambda([w], w=needle)), if emptyp(idx) then throw('notfound), if emptyp(opt) then return(idx), opt: first(opt), if op...
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,...
#Phix
Phix
-- demo\rosetta\Rank_Languages.exw constant output_users = false, limit = 20, -- 0 to list all languages = "http://rosettacode.org/wiki/Category:Programming_Languages", categories = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" include rosettacode_cache.e -...
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 numeral...
#Autolisp
Autolisp
  (defun c:roman() (romanNumber (getint "\n Enter number > ")) (defun romanNumber (n / uni dec hun tho nstr strlist nlist rom) (if (and (> n 0) (<= n 3999)) (progn (setq UNI (list "" "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX") DEC (list "" "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "X...
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 decima...
#BASIC256
BASIC256
function romToDec (roman$) num = 0 prenum = 0 for i = length(roman$) to 1 step -1 x$ = mid(roman$, i, 1) n = 0 if x$ = "M" then n = 1000 if x$ = "D" then n = 500 if x$ = "C" then n = 100 if x$ = "L" then n = 50 if x$ = "X" then n = 10 if x$ = "...
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#EchoLisp
EchoLisp
  (lib 'math.lib) Lib: math.lib loaded. (define fp ' ( 0 2 -3 1)) (poly->string 'x fp) → x^3 -3x^2 +2x (poly->html 'x fp) → x<sup>3</sup> -3x<sup>2</sup> +2x (define (f x) (poly x fp)) (math-precision 1.e-6) → 0.000001   (root f -1000 1000) → 2.0000000133245677 ;; 2 (root f -1000 (- 2 epsilon)) → 1.385559938161431e-7 ...
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: ...
#Clojure
Clojure
$ lein trampoline run
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...
#Euphoria
Euphoria
include misc.e   function encode(sequence s) sequence out integer prev_char,count if length(s) = 0 then return {} end if out = {} prev_char = s[1] count = 1 for i = 2 to length(s) do if s[i] != prev_char then out &= {count,prev_char} prev_char = s[...
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Lua
Lua
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs. complex = setmetatable({ __add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, __sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end, __mul = function(u, v) re...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#zkl
zkl
var [const] CURL=Import("zklCurl"), partURI="http://rosettacode.org/wiki?action=raw&title=%s", langRE=RegExp(0'!\s*==\s*{{\s*header\s*\|(.+)}}!), // == {{ header | zkl }} emptyRE=RegExp(0'!<lang\s*>!);   fcn findEmptyTags(a,b,c,etc){ // -->[lang:(task,task...)] results:=Dictionary(); foreach task in (v...
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 n...
#Maple
Maple
solve(a*x^2+b*x+c,x);   solve(1.0*x^2-10.0^9*x+1.0,x,explicit,allsolutions);   fsolve(x^2-10^9*x+1,x,complex);
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 n...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Solve[a x^2 + b x + c == 0, x] Solve[x^2 - 10^5 x + 1 == 0, x] Root[#1^2 - 10^5 #1 + 1 &, 1] Root[#1^2 - 10^5 #1 + 1 &, 2] Reduce[a x^2 + b x + c == 0, x] Reduce[x^2 - 10^5 x + 1 == 0, x] FindInstance[x^2 - 10^5 x + 1 == 0, x, Reals, 2] FindRoot[x^2 - 10^5 x + 1 == 0, {x, 0}] FindRoot[x^2 - 10^5 x + 1 == 0, {x, 10^6}]
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 inpu...
#D
D
import std.stdio; import std.ascii: letters, U = uppercase, L = lowercase; import std.string: makeTrans, translate;   immutable r13 = makeTrans(letters, //U[13 .. $] ~ U[0 .. 13] ~ U[13 .. U.length] ~ U[0 .. 13] ~ L[13 .. L.length] ~ L[0 .. 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: ...
#PureBasic
PureBasic
EnableExplicit Define.i i Define.d y=1.0, k1=0.0, k2=0.0, k3=0.0, k4=0.0, t=0.0   If OpenConsole() For i=0 To 100 t=i/10 If Not i%10 PrintN("y("+RSet(StrF(t,0),2," ")+") ="+RSet(StrF(y,4),9," ")+#TAB$+"Error ="+RSet(StrF(Pow(Pow(t,2)+4,2)/16-y,10),14," ")) EndIf k1=t*Sqr(y) ...
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). ...
#Ruby
Ruby
class SExpr def initialize(str) @original = str @data = parse_sexpr(str) end attr_reader :data, :original   def to_sexpr @data.to_sexpr end   private   def parse_sexpr(str) state = :token_start tokens = [] word = "" str.each_char do |char| case state   when :token_s...
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...
#Raku
Raku
my ( $min_sum, $hero_attr_min, $hero_count_min ) = 75, 15, 2; my @attr-names = <Str Int Wis Dex Con Cha>;   sub heroic { + @^a.grep: * >= $hero_attr_min }   my @attr; repeat until @attr.sum >= $min_sum and heroic(@attr) >= $hero_count_min {   @attr = @attr-names.map: { (1..6).roll(4).sort(+*).skip(1).s...
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...
#Tailspin
Tailspin
  templates sieve def limit: $; @: [ 2..$limit ]; 1 -> # $@ !   when <..$@::length ?($@($) * $@($) <..$limit>)> do templates sift def prime: $; @: $prime * $prime; @sieve: [ $@sieve... -> # ]; when <..~$@> do $ ! when <$@~..> do @: $@ + $prime; $ -> # ...
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 AP...
#Ring
Ring
  # Project: Rosetta Code/Count examples   load "stdlib.ring" ros= download("http://rosettacode.org/wiki/Category:Programming_Tasks") pos = 1 num = 0 totalros = 0 rosname = "" rostitle = "" for n = 1 to len(ros) nr = searchstring(ros,'<li><a href="/wiki/',pos) if nr = 0 exit else ...
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 AP...
#Ruby
Ruby
require 'open-uri' require 'rexml/document'   module RosettaCode   URL_ROOT = "http://rosettacode.org/mw"   def self.get_url(page, query) begin # Ruby 1.9.2 pstr = URI.encode_www_form_component(page) qstr = URI.encode_www_form(query) rescue NoMethodError require 'cgi' pstr = CG...
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 ...
#MAXScript
MAXScript
haystack=#("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")   for needle in #("Washington","Bush") do ( index = findItem haystack needle   if index == 0 then ( format "% is not in haystack\n" needle ) else ( format "% %\n" 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,...
#PicoLisp
PicoLisp
(load "@lib/http.l")   (for (I . X) (flip (sort (make (client "rosettacode.org" 80 "mw/index.php?title=Special:Categories&limit=5000" (while (from "<li><a href=\"/wiki/Category:") (let Cat (till "\"") (from "(") ...
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 numeral...
#AWK
AWK
  # syntax: GAWK -f ROMAN_NUMERALS_ENCODE.AWK BEGIN { leng = split("1990 2008 1666",arr," ") for (i=1; i<=leng; i++) { n = arr[i] printf("%s = %s\n",n,dec2roman(n)) } exit(0) } function dec2roman(number, v,w,x,y,roman1,roman10,roman100,roman1000) { number = int(number) # force to intege...
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 decima...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::Testing... call :toArabic MCMXC echo MCMXC = !arabic! call :toArabic MMVIII echo MMVIII = !arabic! call :toArabic MDCLXVI echo MDCLXVI = !arabic! call :toArabic CDXLIV echo CDXLIV = !arabic! call :toArabic XCIX echo XCIX = !arabic! pause>nul exit/b 0 ::The "function"... :to...
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
#Elixir
Elixir
defmodule RC do def find_roots(f, range, step \\ 0.001) do first .. last = range max = last + step / 2 Stream.iterate(first, &(&1 + step)) |> Stream.take_while(&(&1 < max)) |> Enum.reduce(sign(first), fn x,sn -> value = f.(x) cond do abs(value) < step / 100 -> ...
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: ...
#Crystal
Crystal
  # conventional weapons enum Choice Rock Paper Scissors end   BEATS = { Choice::Rock => [Choice::Paper], Choice::Paper => [Choice::Scissors], Choice::Scissors => [Choice::Rock], }   # uncomment to use additional weapons # enum Choice # Rock # Paper # Scissors # Lizard # Spock # end   # BEA...
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...
#F.23
F#
  open System open System.Text.RegularExpressions   let encode data = // encodeData : seq<'T> -> seq<int * 'T> i.e. Takes a sequence of 'T types and return a sequence of tuples containing the run length and an instance of 'T. let rec encodeData input = seq { if not (Seq.isEmpty input) then ...
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.
#Maple
Maple
RootsOfUnity := proc( n ) solve(z^n = 1, z); end proc:
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RootsUnity[nthroot_Integer?Positive] := Table[Exp[2 Pi I i/nthroot], {i, 0, nthroot - 1}]
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.
#MATLAB
MATLAB
function z = rootsOfUnity(n)   assert(n >= 1,'n >= 1'); z = roots([1 zeros(1,n-1) -1]);   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 n...
#MATLAB_.2F_Octave
MATLAB / Octave
roots([1 -3 2]) % coefficients in decreasing order of power e.g. [x^n ... x^2 x^1 x^0]
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Maxima
Maxima
solve(a*x^2 + b*x + c = 0, x);   /* 2 2 sqrt(b - 4 a c) + b sqrt(b - 4 a c) - b [x = - --------------------, x = --------------------] 2 a 2 a */   fpprec: 40$   solve(x^2 - 10^9*x + 1 = 0, x); /* [x = ...
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 inpu...
#Delphi
Delphi
  program Rot13;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function Rot13char(c: AnsiChar): AnsiChar; begin Result := c; if (c >= 'a') and (c <= 'm') or (c >= 'A') and (c <= 'M') then Result := AnsiChar(ord(c) + 13) else if (c >= 'n') and (c <= 'z') or (c >= 'N') and (c <= 'Z') then Result := AnsiC...
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: ...
#Python
Python
from math import sqrt   def rk4(f, x0, y0, x1, n): vx = [0] * (n + 1) vy = [0] * (n + 1) h = (x1 - x0) / float(n) vx[0] = x = x0 vy[0] = y = y0 for i in range(1, n + 1): k1 = h * f(x, y) k2 = h * f(x + 0.5 * h, y + 0.5 * k1) k3 = h * f(x + 0.5 * h, y + 0.5 * k2) k...
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). ...
#Rust
Rust
  //! This implementation isn't based on anything in particular, although it's probably informed by a //! lot of Rust's JSON encoding code. It should be very fast (both encoding and decoding the toy //! example here takes under a microsecond on my machine) and tries to avoid unnecessary allocation. //! //! In a real i...
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...
#Red
Red
Red ["RPG attributes generator"]   raw-attribute: does [ sum next sort collect [ loop 4 [keep random/only 6] ] ]   raw-attributes: does [ collect [ loop 6 [keep raw-attribute] ] ]   valid-attributes?: func [b][ n: 0 foreach attr b [ if attr > 14 [n: n + 1] ] all [...
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...
#Tcl
Tcl
package require Tcl 8.5   proc sieve n { if {$n < 2} {return {}}   # create a container to hold the sequence of numbers. # use a dictionary for its speedy access (like an associative array) # and for its insertion order preservation (like a list) set nums [dict create] for {set i 2} {$i <= $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 AP...
#Run_BASIC
Run BASIC
html "<table border=1><tr bgcolor=wheat align=center><td>Num</td><td>Task</td><td>Examples</td></tr>"   a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks") a$ = word$(a$,1,"</table></div>") i = instr(a$,"<a href=""/wiki/") i = instr(a$,"<a href=""/wiki/",i+1) while i > 0 count = count + 1 i = in...
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 AP...
#Rust
Rust
extern crate reqwest; extern crate url; extern crate rustc_serialize;   use std::io::Read; use self::url::Url; use rustc_serialize::json::{self, Json};   pub struct Task { page_id: u64, pub title: String, }   #[derive(Debug)] enum ParseError { /// Something went wrong with the HTTP request to the API. H...
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 ...
#Nanoquery
Nanoquery
$haystack = list() append $haystack "Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" append $haystack "Bush" "Bozo"   $needles = list() append $needles "Washington" append $needles "Bush"   for ($i = 0) ($i < len($needles)) ($i = $i + 1) $needle = $needles[$i] try // use array lookup syntax to get the index o...
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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   driver(arg) -- call the test wrapper return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method searchListOfWords(haystack, needle, forwards = (1 == 1), respectCase = (1 == 1)) public static signals Exce...
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,...
#PowerShell
PowerShell
  $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json") $get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000") $ma...
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 numeral...
#BASIC
BASIC
1 N = 1990: GOSUB 5: PRINT N" = "V$ 2 N = 2008: GOSUB 5: PRINT N" = "V$ 3 N = 1666: GOSUB 5: PRINT N" = "V$; 4 END 5 V = N:V$ = "": FOR I = 0 TO 12: FOR L = 1 TO 0 STEP 0:A = VAL ( MID$ ("1E3900500400100+90+50+40+10+09+05+04+01",I * 3 + 1,3)) 6 L = (V - A) > = 0:V$ = V$ + MID$ ("M.CMD.CDC.XCL.XLX.IXV.IVI",I ...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#BBC_BASIC
BBC BASIC
PRINT "MCMXCIX", FNromandecode("MCMXCIX") PRINT "MMXII", FNromandecode("MMXII") PRINT "MDCLXVI", FNromandecode("MDCLXVI") PRINT "MMMDCCCLXXXVIII", FNromandecode("MMMDCCCLXXXVIII") END   DEF FNromandecode(roman$) LOCAL i%, j%, p%, n%, r%() DIM r%(7) : r%() = 0,1,5,10,50,10...
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
#Erlang
Erlang
% Implemented by Arjun Sunel -module(roots). -export([main/0]). main() -> F = fun(X)->X*X*X - 3*X*X + 2*X end, Step = 0.001, % Using smaller steps will provide more accurate results Start = -1, Stop = 3, Sign = F(Start) > 0, X = Start, while(X, Step, Start, Stop, Sign,F).   while(X, Step, Start, Stop, Sign,F) -...
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#D
D
import std.stdio, std.random, std.string, std.conv, std.array, std.typecons;   enum Choice { rock, paper, scissors }   bool beats(in Choice c1, in Choice c2) pure nothrow @safe @nogc { with (Choice) return (c1 == paper && c2 == rock) || (c1 == scissors && c2 == paper) || ...
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Factor
Factor
USING: io kernel literals math.parser math.ranges sequences sequences.extras sequences.repeating splitting.extras splitting.monotonic strings ; IN: rosetta-code.run-length-encoding   CONSTANT: alpha $[ CHAR: A CHAR: Z [a,b] >string ]   : encode ( str -- str ) [ = ] monotonic-split [ [ length number>string ] [ first...
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.
#Maxima
Maxima
solve(1 = x^n, x)
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#MiniScript
MiniScript
  complexRoots = function(n) result = [] for i in range(0, n-1) real = cos(2*pi * i/n) if abs(real) < 1e-6 then real = 0 imag = sin(2*pi * i/n) if abs(imag) < 1e-6 then imag = 0 result.push real + " " + "+" * (imag>=0) + imag + "i" end for return result end functi...
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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 0 П1 ИП1 sin ИП1 cos С/П 2 пи * ИП0 / ИП1 + П1 БП 03
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 n...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П2 С/П /-/ <-> / 2 / П3 x^2 С/П ИП2 / - Вx <-> КвКор НОП x>=0 28 ИП3 x<0 24 <-> /-/ + / Вx С/П /-/ КвКор ИП3 С/П
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 n...
#Modula-3
Modula-3
MODULE Quad EXPORTS Main;   IMPORT IO, Fmt, Math;   TYPE Roots = ARRAY [1..2] OF LONGREAL;   VAR r: Roots;   PROCEDURE Solve(a, b, c: LONGREAL): Roots = VAR sd: LONGREAL := Math.sqrt(b * b - 4.0D0 * a * c); x: LONGREAL; BEGIN IF b < 0.0D0 THEN x := (-b + sd) / (2.0D0 * a); RETURN Roots{x, 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 inpu...
#Dyalect
Dyalect
func Char.Rot13() { return Char(this.Order() + 13) when this is >= 'a' and <= 'm' or >= 'A' and <= 'M' return Char(this.Order() - 13) when this is >= 'n' and <= 'z' or >= 'N' and <= 'Z' return this }   func String.Rot13() { var cs = [] for c in this { cs.Add(c.Rot13()) } ...
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: ...
#R
R
rk4 <- function(f, x0, y0, x1, n) { vx <- double(n + 1) vy <- double(n + 1) vx[1] <- x <- x0 vy[1] <- y <- y0 h <- (x1 - x0)/n for(i in 1:n) { k1 <- h*f(x, y) k2 <- h*f(x + 0.5*h, y + 0.5*k1) k3 <- h*f(x + 0.5*h, y + 0.5*k2) k4 <- h*f(x + h, y + k3) vx[i +...
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: ...
#Racket
Racket
  (define (RK4 F δt) (λ (t y) (define δy1 (* δt (F t y))) (define δy2 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy1))))) (define δy3 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy2))))) (define δy4 (* δt (F (+ t δt) (+ y δy1)))) (list (+ t δt) (+ y (* 1/6 (+ δy1 (* 2 δy2) (* 2 δy3) δy4))))))  
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). ...
#Scheme
Scheme
(define (sexpr-read port) (define (help port) (let ((char (read-char port))) (cond ((or (eof-object? char) (eq? char #\) )) '()) ((eq? char #\( ) (cons (help port) (help port))) ((char-whitespace? char) (help port)) ((eq? char #\"") (cons (quote-read port) (help port))) (#...
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...
#REXX
REXX
/* REXX 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. */ Do try=1 By 1 ge15=0 sum=0 ol='' Do i=1 To 6 rl='' Do j=1 To 4 rl=rl (random(5)+1) End rl=wordso...
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...
#TI-83_BASIC
TI-83 BASIC
Input "Limit:",N N→Dim(L1) For(I,2,N) 1→L1(I) End For(I,2,SQRT(N)) If L1(I)=1 Then For(J,I*I,N,I) 0→L1(J) End End End For(I,2,N) If L1(I)=1 Then Disp i End End ClrList L1
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 AP...
#Scala
Scala
import scala.language.postfixOps   object TaskCount extends App { import java.net.{ URL, URLEncoder } import scala.io.Source.fromURL   System.setProperty("http.agent", "*") val allTasksURL = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=50...
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 ...
#Nim
Nim
let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]   for needle in ["Bush", "Washington"]: let f = haystack.find(needle) if f >= 0: echo f, " ", needle else: raise newException(ValueError, needle & " not in haystack")
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,...
#PureBasic
PureBasic
Procedure handleError(value, msg.s) If value = 0 MessageRequester("Error", msg) End EndIf EndProcedure   Structure languageInfo name.s pageCount.i EndStructure   #JSON_web_data = 0 ;ID# for our parsed JSON web data object   Define NewList languages.languageInfo()   Define blah.s, object_val, allPages_me...
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 numeral...
#BASIC256
BASIC256
  print 1666+" = "+convert$(1666) print 2008+" = "+convert$(2008) print 1001+" = "+convert$(1001) print 1999+" = "+convert$(1999)   function convert$(value) convert$="" arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 } roman$ = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"} for ...
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 decima...
#BCPL
BCPL
get "libhdr"   let roman(s) = valof $( let digit(ch) = valof $( let ds = table 'm','d','c','l','x','v','i' let vs = table 1000,500,100,50,10,5,1 for i=0 to 6 if ds!i=(ch|32) then resultis vs!i resultis 0 $) let acc = 0 for i=1 to s%0 $( let d = digit(s%i) ...
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
#ERRE
ERRE
  PROGRAM ROOTS_FUNCTION   !VAR E,X,STP,VALUE,S%,I%,LIMIT%,X1,X2,D   FUNCTION F(X) F=X*X*X-3*X*X+2*X END FUNCTION   BEGIN X=-1 STP=1.0E-6 E=1.0E-9 S%=(F(X)>0)   PRINT("VERSION 1: SIMPLY STEPPING X") WHILE X<3.0 DO VALUE=F(X) IF ABS(VALUE)<E THEN PRINT("ROOT FOUND AT X =";X) S%=NO...
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
#Fortran
Fortran
PROGRAM ROOTS_OF_A_FUNCTION   IMPLICIT NONE   INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15) REAL(dp) :: f, e, x, step, value LOGICAL :: s   f(x) = x*x*x - 3.0_dp*x*x + 2.0_dp*x   x = -1.0_dp ; step = 1.0e-6_dp ; e = 1.0e-9_dp   s = (f(x) > 0) DO WHILE (x < 3.0) value = f(x) IF(ABS(value) < ...
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Elixir
Elixir
defmodule Rock_paper_scissors do def play, do: loop([1,1,1])   defp loop([r,p,s]=odds) do IO.gets("What is your move? (R,P,S,Q) ") |> String.upcase |> String.first |> case do "Q" -> IO.puts "Good bye!" human when human in ["R","P","S"] -> IO.puts "Your move is #{play_to_s...
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...
#FALSE
FALSE
1^[^$~][$@$@=$[%%\1+\$0~]?~[@.,1\$]?%]#%\., {encode}