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/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Raku
Raku
constant $n = 9516311845790656153499716760847001433441357; constant $e = 65537; constant $d = 5617843187844953170308463622230283376298685;   my $secret-message = "ROSETTA CODE";   package Message { my @alphabet = slip('A' .. 'Z'), ' '; my $rad = +@alphabet; my %code = @alphabet Z=> 0 .. *; subset Text o...
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...
#Dyalect
Dyalect
func getThree(n) { var g3 = [] for i in 0..33 { g3.Add(rnd(max: n) + 1) } g3.Sort() g3.RemoveAt(0) g3 }   func getSix() { var g6 = [] for i in 0..5 { g6.Add(getThree(6).Sum()) } g6 }   func Array.Sum() { var acc = 0 for x in this { acc += x } ...
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...
#EasyLang
EasyLang
len v[] 6 repeat vsum = 0 vmin = 0 for i range 6 val = 0 min = 6 for j range 4 h = random 6 + 1 val += h if h < min min = h . . val -= min v[i] = val if val >= 15 vmin += 1 . vsum += val . until vsum >= 75 and vmin >= 2 . print "Attribu...
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...
#Raku
Raku
sub sieve( Int $limit ) { my @is-prime = False, False, slip True xx $limit - 1;   gather for @is-prime.kv -> $number, $is-prime { if $is-prime { take $number; loop (my $s = $number**2; $s <= $limit; $s += $number) { @is-prime[$s] = False; } } ...
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...
#BBC_BASIC
BBC BASIC
VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support   SYS "LoadLibrary", "URLMON.DLL" TO urlmon% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF special$ = "+()'"   url$ = "http://www.rosettacode.org/w/api.php?action=query" + \ \ "&list=categorymembers&cmtitle...
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...
#Bracmat
Bracmat
( ( get-page = . sys$(str$("wget -q -O wget.out \"" !arg \")) & get$("wget.out",HT ML) ) & get-page$"http://rosettacode.org/wiki/Category:Programming_Tasks"  : ? (table.?) ?tasklist (.table.) ? & 0:?list & whl ' ( !tasklist  :  ? ( a . (href.@(?:"/wiki/" ?href)) (title.?t...
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 ...
#Go
Go
package main   var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads", "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", ...
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,...
#Delphi
Delphi
  program Rank_languages_by_popularity;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Classes, IdHttp, IdBaseComponent, IdComponent, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, System.RegularExpressions, System.Generics.Collections, System.Generics...
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...
#BASIC
BASIC
DECLARE FUNCTION RLDecode$ (i AS STRING) DECLARE FUNCTION RLEncode$ (i AS STRING)   DIM initial AS STRING, encoded AS STRING, decoded AS STRING   INPUT "Type something: ", initial encoded = RLEncode(initial) decoded = RLDecode(encoded) PRINT initial PRINT encoded PRINT decoded   FUNCTION RLDecode$ (i AS STRING) DIM...
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.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;   procedure Roots_Of_Unity is Root : Complex; begin for N in 2..10 loop Put_Line ("N =" & Integer'Image (N)); for K in 0..N - 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.
#ALGOL_68
ALGOL 68
FORMAT complex fmt=$g(-6,4)"⊥"g(-6,4)$; FOR root FROM 2 TO 10 DO printf(($g(4)$,root)); FOR n FROM 0 TO root-1 DO printf(($xf(complex fmt)$,complex exp( 0 I 2*pi*n/root))) OD; printf($l$) OD
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...
#Ada
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); ...
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...
#AppleScript
AppleScript
to rot13(textString) do shell script "tr a-zA-Z n-za-mN-ZA-M <<<" & quoted form of textString end 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: ...
#FreeBASIC
FreeBASIC
' version 03-10-2015 ' compile with: fbc -s console ' translation of BBC BASIC   Dim As Double y = 1, t, actual, k1, k2, k3, k4   Print   For i As Integer = 0 To 100   t = i / 10   If t = Int(t) Then actual = ((t ^ 2 + 4) ^ 2) / 16 Print "y("; Str(t); ") ="; y ; Tab(27); "Error = "; actual - y ...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Erlang
Erlang
  -module( find_unimplemented_tasks ). -include_lib( "xmerl/include/xmerl.hrl" ).   -export( [init_http/0, per_language/1, rosetta_code_list_of/1] ).   init_http() -> application:start( inets ).   per_language( Language ) -> ok = init_http(), Tasks = rosetta_code_list_of( "Programming_Tasks" ), Uninplemented = Task...
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Transd
Transd
#lang transd   MainModule: { code: "(+ 5 x)",   _start: (lambda (textout (- (to-Int (with x 100 (snd (eval code)))) (to-Int (with x 1 (snd (eval code))))) )) }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#TXR
TXR
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0) (- (eval ^(let ((x ,x1)) ,code-fragment)) (eval ^(let ((x ,x0)) ,code-fragment))))   (eval-subtract-for-two-values-of-x 1 2) ;; yields -4.67077427047161
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). ...
#F.23
F#
  module SExpr (* This module is a very simple port of the OCaml version to F# (F-Sharp) *) (* The original OCaml setatment is comment out and the F# statement(s) follow *) (* Port performed by Bob Elward 23 Feb 2020 *)   (* The .Net standard would use "+" and not "^" for string concatenation *) (* I kept the "^" to be...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#OCaml
OCaml
#load "str.cma"   let langs = Str.split (Str.regexp " ") "actionscript ada algol68 amigae applescript autohotkey awk bash basic \ befunge bf c cfm cobol cpp csharp d delphi e eiffel factor false forth \ fortran fsharp haskell haxe j java javascript lisaac lisp logo lua m4 \ mathematica maxscript m...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Ruby
Ruby
  #!/usr/bin/ruby   require 'openssl' # for mod_exp only require 'prime'   def rsa_encode blocks, e, n blocks.map{|b| b.to_bn.mod_exp(e, n).to_i} end   def rsa_decode ciphers, d, n rsa_encode ciphers, d, n end   # all numbers in blocks have to be < modulus, or information is lost # for secure encryption only use bi...
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...
#Factor
Factor
USING: combinators.short-circuit dice formatting io kernel math math.statistics qw sequences ; IN: rosetta-code.rpg-attributes-generator   CONSTANT: stat-names qw{ Str Dex Con Int Wis Cha }   : attribute ( -- n ) 4 [ ROLL: 1d6 ] replicate 3 <iota> kth-largests sum ;   : stats ( -- seq ) 6 [ attribute ] replicate ; ...
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...
#FreeBASIC
FreeBASIC
#define min(a, b) iif(a < b, a, b)   function d6() as integer 'simulates a marked regular hexahedron coming to rest on a plane return 1+int(rnd*6) end function   function roll_stat() as integer 'rolls four dice, returns the sum of the three highest dim as integer a=d6(), b=d6(), c=d6(), d=d6() retur...
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...
#RATFOR
RATFOR
    program prime # define(true,1) define(false,0) # integer loop,loop2,limit,k,primes,count integer isprime(1000)   limit = 1000 count = 0   for (loop=1; loop<=limit; loop=loop+1) { isprime(loop) = true }   isprime(1) = false   for (loop=2; loop<=limit; loop=loop+1)     { if (isprime(loop) ==...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net;   class Task { private string _task; private int _examples;   public Task(string task, int examples) { _task = task; _examples = examples; }   public string Name...
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 ...
#Groovy
Groovy
def haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] def needles = ["Washington","Bush","Wally"] needles.each { needle -> def index = haystack.indexOf(needle) def lastindex = haystack.lastIndexOf(needle) if (index < 0) { assert lastindex < 0 println 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,...
#Erlang
Erlang
  -module( rank_languages_by_popularity ).   -export( [task/0] ).   -record( print_fold, {place=0, place_step=1, previous_count=0} ).   task() -> ok = find_unimplemented_tasks:init(), Category_programming_languages = find_unimplemented_tasks:rosetta_code_list_of( "Programming_Languages" ), Programming_languages = [X...
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...
#BASIC256
BASIC256
  function FBString(lon, cad$) # Definimos la función String en BASIC256 cadena$ = "" for a = 1 to lon cadena$ += cad$ next a return cadena$ end function   function RLDecode(i$) rCount$ = "" : outP$ = ""   for Loop0 = 1 to length(i$) m$ = mid(i$, Loop0, 1) begin case case m$ = "0" rCount$ += m$ c...
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.
#Arturo
Arturo
rect: function [r,phi][ to :complex @[ r * cos phi, r * sin phi ] ] roots: function [n][ map 0..dec n 'k -> rect 1.0 2 * k * pi / n ]   loop 2..10 'nr -> print [pad to :string nr 3 "=>" join.with:", " to [:string] .format:".3f" roots nr]
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.
#AutoHotkey
AutoHotkey
n := 8, a := 8*atan(1)/n Loop %n% i := A_Index-1, t .= cos(a*i) ((s:=sin(a*i))<0 ? " - i*" . -s : " + i*" . s) "`n" Msgbox % t
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...
#ALGOL_68
ALGOL 68
quadratic equation: BEGIN   MODE ROOTS = UNION([]REAL, []COMPL); MODE QUADRATIC = STRUCT(REAL a,b,c);   PROC solve = (QUADRATIC q)ROOTS: BEGIN REAL a = a OF q, b = b OF q, c = c OF q; REAL sa = b**2 - 4*a*c; IF sa >=0 THEN # handle the +ve case as REAL # REAL sqrt sa = ( b<0 | sqrt(sa) | -s...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Applesoft_BASIC
Applesoft BASIC
100HOME:INPUT"ENTER A STRING:";S$:FORL=1TOLEN(S$):I$=MID$(S$,L,1):LC=(ASC(I$)>95)*32:C$=CHR$(ASC(I$)-LC):IFC$>="A"ANDC$<="Z"THENC$=CHR$(ASC(C$)+13):C$=CHR$(ASC(C$)-26*(C$>"Z")):I$=CHR$(ASC(C$)+LC) 110A$=A$+I$:NEXT:PRINTA$
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: ...
#FutureBasic
FutureBasic
window 1   def fn dydx( x as double, y as double ) as double = x * sqr(y) def fn exactY( x as long ) as double = ( x ^2 + 4 ) ^2 / 16   long i double h, k1, k2, k3, k4, x, y, result   h = 0.1 y = 1 for i = 0 to 100 x = i * h if x == int(x) result = fn exactY( x ) print "y("; mid$( str$(x), 2, len$(str$(x) )...
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: ...
#Go
Go
package main   import ( "fmt" "math" )   type ypFunc func(t, y float64) float64 type ypStepFunc func(t, y, dt float64) float64   // newRKStep takes a function representing a differential equation // and returns a function that performs a single step of the forth-order // Runge-Kutta method. func newRK4Step(yp y...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Go
Go
package main   import ( "encoding/xml" "fmt" "io" "net/http" "net/url" )   const language = "Go"   var baseQuery = "http://rosettacode.org/mw/api.php?action=query" + "&format=xml&list=categorymembers&cmlimit=100"   func req(u string, foundCm func(string)) string { resp, err := http.Get(u) ...
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#UNIX_Shell
UNIX Shell
eval_with_x() { set -- "`x=$2; eval "$1"`" "`x=$3; eval "$1"`" expr "$2" - "$1" }   eval_with_x ' # compute 2 ** $x p=1 while test $x -gt 0; do p=`expr $p \* 2` x=`expr $x - 1` done echo $p ' 3 5 # Prints '24'
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Wren
Wren
import "meta" for Meta   var x Meta.eval("x = 2") System.print("First x = %(x)") var y = x // save this value   Meta.eval("x = 5") System.print("Second x = %(x)")   Meta.eval("x = x - y") System.print("Delta x = %(x)")
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). ...
#Factor
Factor
USING: formatting kernel math.parser multiline peg peg.ebnf regexp sequences prettyprint words ; IN: rosetta-code.s-expressions   STRING: input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) ;   EBNF: sexp>seq [=[ ws = [\n\t\r ]* => [[ drop ignore ]] digits = [0-9]+ number = digits => [[ s...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Perl
Perl
my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Phix
Phix
with javascript_semantics constant ltext = `_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp cpp-qt csharp css d delphi diff dos dot eiffel email fortran freebasic genero gettext glsl gml gnu...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Rust
Rust
  extern crate num;   use num::bigint::BigUint; use num::integer::Integer; use num::traits::{One, Zero};   fn mod_exp(b: &BigUint, e: &BigUint, n: &BigUint) -> Result<BigUint, &'static str> { if n.is_zero() { return Err("modulus is zero"); } if b >= n { // base is too large and should be spl...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Scala
Scala
  object RSA_saket{ val d = BigInt("5617843187844953170308463622230283376298685") val n = BigInt("9516311845790656153499716760847001433441357") val e = 65537 val text = "Rosetta Code" val encode = (msg:BigInt) => pow_mod(msg,e,n) val decode = (msg:BigInt) => pow_mod(msg,d,n) val getmsg = (tx...
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...
#FOCAL
FOCAL
01.10 S T=0 01.20 F X=1,6;D 4;S AT(X)=S3;S T=T+S3 01.30 I (T-75)1.1 01.40 S K=0;F X=1,6;D 2 01.50 I (K-2)1.1 01.55 T "STR DEX CON INT WIS CHA TOTAL",! 01.60 F X=1,6;T %2,AT(X)," " 01.70 T T,! 01.80 Q   02.10 I (AT(X)-15)2.3,2.2,2.2 02.20 S K=K+1 02.30 R   04.01 C--ROLL 4 D6ES AND GIVE SUM OF LARGEST 3 04.10 S XS=...
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...
#Forth
Forth
require random.fs : d6 ( -- roll ) 6 random 1 + ;   variable smallest : genstat ( -- stat ) d6 dup smallest ! 3 0 do d6 dup smallest @ < if dup smallest ! then + loop smallest @ - ;   variable strong variable total : genstats ( -- cha wis int con dex str ) 0 strong ! 0 total ! 6 0 do gen...
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...
#Red
Red
  primes: function [n [integer!]][ poke prim: make bitset! n 1 true r: 2 while [r * r <= n][ repeat q n / r - 1 [poke prim q + 1 * r true] until [not pick prim r: r + 1] ] collect [repeat i n [if not prim/:i [keep i]]] ]   primes 100 == [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 7...
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...
#Clojure
Clojure
(ns count-examples (:import [java.net URLEncoder]) (:use [clojure.contrib.http.agent :only (http-agent string)] [clojure.contrib.json :only (read-json)] [clojure.contrib.string :only (join)]))   (defn url-encode [v] (URLEncoder/encode (str v) "utf-8"))   (defn rosettacode-get [path params] (let [p...
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 ...
#Haskell
Haskell
import Data.List   haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] needles = ["Washington","Bush"]
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,...
#F.23
F#
open System open System.Text.RegularExpressions   [<EntryPoint>] let main argv = let rosettacodeSpecialCategoriesAddress = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" let rosettacodeProgrammingLaguagesAddress = "http://rosettacode.org/wiki/Category:Programming_L...
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...
#BBC_BASIC
BBC BASIC
input$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" PRINT "Input: " input$ rle$ = FNencodeRLE(input$) output$ = FNdecodeRLE(rle$) PRINT "Output: " output$ END   DEF FNencodeRLE(text$) LOCAL n%, r%, c$, o$ n% = 1 WHILE n% <= LEN(text...
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.
#AWK
AWK
  # syntax: GAWK -f ROOTS_OF_UNITY.AWK BEGIN { pi = 3.1415926 for (n=2; n<=5; n++) { printf("%d: ",n) for (root=0; root<=n-1; root++) { real = cos(2 * pi * root / n) imag = sin(2 * pi * root / n) printf("%8.5f %8.5fi",real,imag) if (root != n-1) { printf(", ") } ...
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.
#BASIC
BASIC
CLS PI = 3.1415926# n = 5 'this can be changed for any desired n angle = 0 'start at angle 0 DO real = COS(angle) 'real axis is the x axis IF (ABS(real) < 10 ^ -5) THEN real = 0 'get rid of annoying sci notation imag = SIN(angle) 'imaginary axis is the y axis IF (ABS(imag) < 10 ^ -5) THEN imag = 0 'get rid...
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...
#AutoHotkey
AutoHotkey
MsgBox % quadratic(u,v, 1,-3,2) ", " u ", " v MsgBox % quadratic(u,v, 1,3,2) ", " u ", " v MsgBox % quadratic(u,v, -2,4,-2) ", " u ", " v MsgBox % quadratic(u,v, 1,0,1) ", " u ", " v SetFormat FloatFast, 0.15e MsgBox % quadratic(u,v, 1,-1.0e8,1) ", " u ", " v   quadratic(ByRef x1, ByRef x2, a,b,c) { ; -> #real roots {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...
#Arturo
Arturo
rot13: function [c][ case [in? lower c] when? -> `a`..`m` -> return to :char (to :integer c) + 13 when? -> `n`..`z` -> return to :char (to :integer c) - 13 else -> return c ]   loop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 'ch -> prints rot13 ch   print ""
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: ...
#Groovy
Groovy
  class Runge_Kutta{ static void main(String[] args){ def y=1.0,t=0.0,counter=0; def dy1,dy2,dy3,dy4; def real; while(t<=10) {if(counter%10==0) {real=(t*t+4)*(t*t+4)/16; println("y("+t+")="+ y+ " Error:"+ (real-y)); }   dy1=dy(dery(y,t)); dy2=dy(dery(y+dy1/2,t+0.05)); dy3=dy(dery(y+dy2/2,t+0.05)); dy4=dy(dery(y+dy3,t+0...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Haskell
Haskell
import Network.Browser import Network.HTTP import Network.URI import Data.List import Data.Maybe import Text.XML.Light import Control.Arrow import Data.Char   getRespons url = do rsp <- Network.Browser.browse $ do setAllowRedirects True setOutHandler $ const (return ()) -- quiet request $ getRequest url...
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#zkl
zkl
fcn evalWithX(text,x) { f:=Compiler.Compiler.compileText(text); f.x = x; // set free var in compiled blob f.__constructor(); // run blob vm.regX // compiler sets the VMs X register for cases like this } const TEXT="var x; x*2"; // variables need to be declared evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4
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). ...
#Go
Go
package main   import ( "errors" "fmt" "reflect" "strconv" "strings" "unicode" )   var input = `((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))`   func main() { fmt.Println("input:") fmt.Println(input)   s, err := parseSexp(input) if err != nil { fmt.Pr...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (let Lang '("ada" "awk" "c" "forth" "prolog" "python" "z80") (in NIL (while (echo "<") (let S (till ">" T) (cond ((pre? "code " S) (prin "<lang" (cddddr (chop S)))) ((member S Lang) (prin "<lang " S)) ...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#PureBasic
PureBasic
If Not OpenConsole() End ElseIf CountProgramParameters() <> 2 PrintN("Usage: "+GetFilePart(ProgramFilename())+" InFile OutFile") End EndIf   Define Infile$ =ProgramParameter(), Outfile$=ProgramParameter() If ReadFile(0,Infile$) NewList Out$() Define line$, part$, new$, pos1, pos2 While Not Eof(0) line...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i"; include "bytedata.s7i";   const proc: main is func local const string: plainText is "Rosetta Code"; # Use a key big enough to hold 16 bytes of plain text in a single block. const bigInteger: modulus is 9516311845790656153499716760847001433441357_; co...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Sidef
Sidef
const n = 9516311845790656153499716760847001433441357 const e = 65537 const d = 5617843187844953170308463622230283376298685   module Message { var alphabet = [('A' .. 'Z')..., ' '] var rad = alphabet.len var code = Hash(^rad -> map {|i| (alphabet[i], i) }...) func encode(String t) { [code{t.reve...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "sort" "time" )   func main() { s := rand.NewSource(time.Now().UnixNano()) r := rand.New(s) for { var values [6]int vsum := 0 for i := range values { var numbers [4]int for j := range numbers { ...
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...
#REXX
REXX
/*REXX program generates and displays primes via the sieve of Eratosthenes algorithm.*/ parse arg H .; if H=='' | H=="," then H= 200 /*optain optional argument from the CL.*/ w= length(H); @prime= right('prime', 20) /*W: is used for aligning the output.*/ @.=. ...
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...
#D
D
  import tango.io.Stdout; import tango.net.http.HttpClient; import tango.net.http.HttpHeaders; import tango.text.xml.Document; import tango.text.Util;   alias HttpHeader.ContentLength CL;   auto url = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&...
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 ...
#HicEst
HicEst
CHARACTER haystack='Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo.' CHARACTER needle*10   DLG(TItle="Enter search string", Edit=needle)   n = EDIT(Text=haystack, Option=2, End, Count=needle) ! Option = word   IF( n == 0 ) THEN WRITE(Messagebox="!") needle, "not found" ! bus not found ELSE first = EDIT(Text=...
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,...
#Go
Go
package main   import ( "encoding/xml" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "regexp" "sort" "strconv" "strings" )   var baseQuery = "http://rosettacode.org/mw/api.php?action=query" + "&format=xml&list=categorymembers&cmlimit=500"   func req(u string, foundCm func(string)) string { resp, err :=...
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...
#Befunge
Befunge
~"y"- ~$ v <temp var for when char changes format: first,'n' and a newline.  : a char then a v _"n",v number then a space continuously 9 example: 1 n > v ,+< a5 b2 decoded:aaaaabb th...
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.
#BBC_BASIC
BBC BASIC
@% = &20408 FOR n% = 2 TO 5 PRINT STR$(n%) ": " ; FOR root% = 0 TO n%-1 real = COS(2*PI * root% / n%) imag = SIN(2*PI * root% / n%) PRINT real imag "i" ; IF root% <> n%-1 PRINT "," ; NEXT PRINT NEXT 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.
#C
C
#include <stdio.h> #include <math.h>   int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i;   for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a...
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...
#AutoHotkey
AutoHotkey
task = ( Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> ) lang := "no language", out := Object(lang, 0), total := 0 Loop Parse, task, `r`n If RegExMatch(A_LoopField, "==\s*{{\s*header\s*\|\s*([^\s\}]+)\s*}}\s*==",...
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...
#BBC_BASIC
BBC BASIC
FOR test% = 1 TO 7 READ a$, b$, c$ PRINT "For a = " ; a$ ", b = " ; b$ ", c = " ; c$ TAB(32) ; PROCsolvequadratic(EVAL(a$), EVAL(b$), EVAL(c$)) NEXT END   DATA 1, -1E9, 1 DATA 1, 0, 1 DATA 2, -1, -6 DATA 1, 2, -2 DATA 0.5, SQR(2), 1 DATA 1, 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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <complex.h> #include <math.h>   typedef double complex cplx;   void quad_root (double a, double b, double c, cplx * ra, cplx *rb) { double d, e; if (!a) { *ra = b ? -c / b : 0; *rb = 0; return; } if (!c) { *ra = 0; *rb = -b / a; return; }   b /= 2; if (...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#AutoHotkey
AutoHotkey
ROT13(string) ; by Raccoon July-2009 { Static a := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " Static b := "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM " s= Loop, Parse, string { c := substr(b,instr(a,A_LoopField,True),1) if (c != " ") s .= c else s .= A_LoopField ...
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: ...
#Hare
Hare
use fmt; use math;   export fn main() void = { rk4_driver(&f, 0.0, 10.0, 1.0, 0.1); };   fn rk4_driver(func: *fn(_: f64, _: f64) f64, t_init: f64, t_final: f64, y_init: f64, h: f64) void = { let n = ((t_final - t_init) / h): int; let tn: f64 = t_init; let yn: f64 = y_init; let i: int = 1;   fmt::printfln("{: 2} {...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Icon_and_Unicon
Icon and Unicon
$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500" $define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title=" $define RCUA "User-Agent: Unicon Rosetta 0.1" $define RCXUA "X-Unicon: http://unicon.org/" $define ...
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). ...
#Haskell
Haskell
import qualified Data.Functor.Identity as F import qualified Text.Parsec.Prim as Prim import Text.Parsec ((<|>), (<?>), many, many1, char, try, parse, sepBy, choice, between) import Text.Parsec.Token (integer, float, whiteSpace, stringLiteral, makeTokenParser) import Text.Parsec.Char (noneOf) impo...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Python
Python
# coding: utf-8   import sys import re   langs = ['ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog', 'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus', 'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache', 'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocam...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Tcl
Tcl
package require Tcl 8.5   # This is a straight-forward square-and-multiply implementation that relies on # Tcl 8.5's bignum support (based on LibTomMath) for speed. proc modexp {b expAndMod} { lassign $expAndMod -> e n if {$b >= $n} {puts stderr "WARNING: modulus too small"} for {set r 1} {$e != 0} {set e [...
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...
#Haskell
Haskell
import Control.Monad (replicateM) import System.Random (randomRIO) import Data.Bool (bool) import Data.List (sort)   character :: IO [Int] character = discardUntil (((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=))) (replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int)))   dis...
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...
#Ring
Ring
  limit = 100 sieve = list(limit) for i = 2 to limit for k = i*i to limit step i sieve[k] = 1 next if sieve[i] = 0 see "" + i + " " ok next  
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...
#EGL
EGL
package com.eglexamples.client;   import org.eclipse.edt.rui.widgets.*;   handler RosettaCodeHandler type RUIhandler{initialUI =[ui], title = "Rosetta Code Tasks and Counts"}   ui GridLayout{columns = 3, rows = 4, cellPadding = 4, children = [ b1, dg1, l1, l2, l3, l4 ]};   b1 Button{ layoutData = new GridLayout...
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...
#Erlang
Erlang
  -module(rosseta_examples). -include_lib("xmerl/include/xmerl.hrl").   -export([main/0]).   main() -> application:start(inets), Titles = read_titles(empty), Result = lists:foldl(fun(Title,Acc) -> Acc + calculate_one(Title) end, 0, Titles), io:format("Total: ~p examples.\n",[Result]), application:stop(...
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 ...
#Icon_and_Unicon
Icon and Unicon
  link lists   procedure main() haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] # the haystack every needle := !["Bush","Washington"] do { # the needles   if i := lindex(haystack,needle) then { ...
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,...
#Groovy
Groovy
def html = new URL('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000').getText([ connectTimeout:500, readTimeout:15000, requestProperties: [ 'User-Agent': 'Firefox/2.0.0.4']]) def count = [:] (html =~ '<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>').each { match...
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...
#Bracmat
Bracmat
( run-length = character otherCharacter acc begin end .  :?acc & 0:?begin & @( !arg  :  ? [!begin  %@?character  ? [?end ( (%@:~!character:?otherCharacter) ? & !acc !end+-1*!begin !character:?acc ...
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics;   class Program { static IEnumerable<Complex> RootsOfUnity(int degree) { return Enumerable .Range(0, degree) .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree...
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.
#C.2B.2B
C++
#include <complex> #include <cmath> #include <iostream>   double const pi = 4 * std::atan(1);   int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
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...
#Erlang
Erlang
  -module( find_bare_lang_tags ).   -export( [task/0] ).   task() -> {ok, Binary} = file:read_file( "priv/find_bare_lang_tags_1" ), Lines = string:tokens( erlang:binary_to_list(Binary), "\n" ), {_Lang, Dict} = lists:foldl( fun count_empty_lang/2, {"no language", dict:new()}, Lines ), Count_langs = [{dict:fetch(X, D...
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...
#C.23
C#
using System; using System.Numerics;   class QuadraticRoots { static Tuple<Complex, Complex> Solve(double a, double b, double c) { var q = -(b + Math.Sign(b) * Complex.Sqrt(b * b - 4 * a * c)) / 2; return Tuple.Create(q / a, c / q); }   static void Main() { Console.WriteLine(...
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...
#AWK
AWK
# usage: awk -f rot13.awk BEGIN { for(i=0; i < 256; i++) { amap[sprintf("%c", i)] = i } for(l=amap["a"]; l <= amap["z"]; l++) { rot13[l] = sprintf("%c", (((l-amap["a"])+13) % 26 ) + amap["a"]) } FS = "" } { o = "" for(i=1; i <= NF; i++) { if ( amap[tolower($i)] in rot13 ) { c = rot13[am...
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: ...
#Haskell
Haskell
dv :: Floating a => a -> a -> a dv = (. sqrt) . (*)   fy t = 1 / 16 * (4 + t ^ 2) ^ 2   rk4 :: (Enum a, Fractional a) => (a -> a -> a) -> a -> a -> a -> [(a, a)] rk4 fd y0 a h = zip ts $ scanl (flip fc) y0 ts where ts = [a,h ..] fc t y = sum . (y :) . zipWith (*) [1 / 6, 1 / 3, 1 / 3, 1 / 6] $ ...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#J
J
require 'strings web/gethttp'   findUnimpTasks=: ('Programming_Tasks' -.&getCategoryMembers ,&'/Omit') ([ #~ -.@e.) getCategoryMembers   getTagContents=: dyad define 'starttag endtag'=. x ('\' -.~ endtag&taketo)&.>@(starttag&E. <@((#starttag)&}.);.1 ]) y )   NB. RosettaCode Utilities parseTitles=: ('"title":"';'"')...
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#Icon_and_Unicon
Icon and Unicon
link ximage   procedure main() in := "((data 'quoted data' 123 4.5) (data (!@# (4.5) '(more' 'data)')))" # in := map(in,"'","\"") # uncomment to put back double quotes if desired write("Input: ",image(in)) write("Structure: \n",ximage(S := string2sexp(in))) write("Output: ",image(sexp2string(S))) end   proc...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#R
R
  fixtags <- function(page) { langs <- c("c", "c-sharp", "r") # a complete list is required, obviously langs <- paste(langs, collapse="|") page <- gsub(paste("<(", langs, ")>", sep=""), "<lang \\1>", page) page <- gsub(paste("</(", langs, ")>", sep=""), "</#####lang>", page) page <- gsub(paste("<code(...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Racket
Racket
  #lang racket   (define lang-names '("X" "Y" "Z"))   (define rx (regexp (string-join lang-names "|" #:before-first "<((/?(?:code)?)(?:( )?(" #:after-last "))?)>")))   (let loop () ; does all in a single scan (define m (regexp-match rx (current-input-port) 0 #f (current...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Raku
Raku
my @langs = < abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi diff _div dos dot eiffel email fortran freebasic genero gettext glsl gml gnuplot groov...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Numerics Imports System.Text   Module Module1 Sub Main() Dim n As BigInteger = BigInteger.Parse("9516311845790656153499716760847001433441357") Dim e As BigInteger = 65537 Dim d As BigInteger = BigInteger.Parse("5617843187844953170308463622230283376298685") ...
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...
#J
J
  roll=: [: >: 4 6 ?@:$ 6: massage=: +/ - <./ generate_attributes=: massage@:roll accept=: (75 <: +/) *. (2 <: [: +/ 15&<:) Until=: conjunction def 'u^:(0-:v)^:_'   NB. show displays discarded attribute sets NB. and since roll ignores arguments, echo would suffice in place of show show=: [ echo   NB. use: generate_char...
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...
#Ruby
Ruby
def eratosthenes(n) nums = [nil, nil, *2..n] (2..Math.sqrt(n)).each do |i| (i**2..n).step(i){|m| nums[m] = nil} if nums[i] end nums.compact end   p eratosthenes(100)
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...
#F.23
F#
#r "System.Xml.Linq.dll"   let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" let uri2 task = sprintf "http://www.rosettacode.org/w/index.php?title=%s&action=raw" task   [|for xml in (System.Xml.Linq.XDocument.Load uri1).Root.Des...
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...
#Factor
Factor
USING: arrays assocs concurrency.combinators concurrency.semaphores formatting hashtables http.client io json.reader kernel math math.parser sequences splitting urls.encoding ; IN: rosetta-code.count-examples   CONSTANT: list-url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Prog...