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/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 ...
#DWScript
DWScript
var haystack : array of String = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];   function Find(what : String) : Integer; begin Result := haystack.IndexOf(what); if Result < 0 then raise Exception.Create('not found'); end;   PrintLn(Find("Ronald")); // 3 PrintLn(Find('McDonald')); /...
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Sidef
Sidef
var (a, b) = (-5, 7); say eval '(a * b).abs'; # => 35 say (a * b -> abs); # => 35
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Slate
Slate
`(4 + 5) evaluate. `(4 + 5) evaluateIn: prototypes.
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Smalltalk
Smalltalk
[ 4 + 5 ] value.
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#XPL0
XPL0
proc NumOut(Num); \Output positive integer with commas int Num, Dig, Cnt; [Cnt:= [0]; Num:= Num/10; Dig:= rem(0); Cnt(0):= Cnt(0)+1; if Num then NumOut(Num); Cnt(0):= Cnt(0)-1; ChOut(0, Dig+^0); if rem(Cnt(0)/3)=0 & Cnt(0) then ChOut(0, ^,); ];   func IsPrime(N); \Return 'true' if N is prime int N, I; [i...
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP // saving 664,578 primes (vs generating them on the fly) seems a bit overkill   fcn safePrime(p){ ((p-1)/2).probablyPrime() } // p is a BigInt prime   fcn safetyList(sN,nsN){ p,safe,notSafe := BI(2),List(),List(); do{ if(safePrime(p)) safe.append(p.toInt()) el...
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: ...
#ALGOL_68
ALGOL 68
  BEGIN PROC rk4 = (PROC (REAL, REAL) REAL f, REAL y, x, dx) REAL : BEGIN CO Fourth-order Runge-Kutta method CO REAL dy1 = dx * f(x, y); REAL dy2 = dx * f(x + dx / 2.0, y + dy1 / 2.0); REAL dy3 = dx * f(x + dx / 2.0, y + dy2 / 2.0); REAL dy4 = dx * f(x + dx, y + dy3); y + (dy1 + 2.0...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Input source code is "10 x" , X is locally bound to 3 & 2 and the resulting expressions evaluated. (10 x /. x -> 3 ) - (10 x /. x -> 2 ) -> 10
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function r = calcit(f, val1, val2) x = val1; a = eval(f); x = val2; b = eval(f); r = b-a; end
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#ALGOL_68
ALGOL 68
# S-Expressions # CHAR nl = REPR 10; # mode representing an S-expression # MODE SEXPR = STRUCT( UNION( VOID, STRING, REF SEXPR ) element, REF SEXPR next ); # creates an initialises an SEXPR # PROC new s expr = REF SEXPR: HEAP SEXPR := ( EMPTY, NIL ); # reports an error # PROC error = ( STRING msg )VOID: print( ( "**** ...
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...
#FreeBASIC
FreeBASIC
' version 17-01-2017 ' compile with: fbc -s console   #Include Once "gmp.bi"   Dim As Mpz_ptr e, d, n, pt, ct   e = Allocate(Len(__mpz_struct)) d = Allocate(Len(__mpz_struct)) n = Allocate(Len(__mpz_struct)) pt = Allocate(Len(__mpz_struct)) : mpz_init(pt) ct = Allocate(Len(__mpz_struct)) : mpz_init(ct)   mpz_init_se...
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...
#ALGOL_68
ALGOL 68
BEGIN # RPG attributes generator #   INT attrib count = 6; MODE RESULT = STRUCT( BOOL success, INT sum, high count, [ 1 : attrib count ]INT a );   PROC generate attrib = INT: BEGIN INT min := 255, sum := 0; FOR i FROM 0 TO 3 DO INT v = ENTIER( next random * 6 ) + 1; ...
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...
#PL.2FM
PL/M
100H:   DECLARE PRIME$MAX LITERALLY '5000';   /* CREATE SIEVE OF GIVEN SIZE */ MAKE$SIEVE: PROCEDURE(START, SIZE); DECLARE (START, SIZE, M, N) ADDRESS; DECLARE PRIME BASED START BYTE;   PRIME(0)=0; /* 0 AND 1 ARE NOT PRIMES */ PRIME(1)=0; DO N=2 TO SIZE; PRIME(N)=1; /* ASSUME ALL OTHERS ARE...
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Sidef
Sidef
struct City { String name, Number population, }   var cities = [ City("Lagos", 21), City("Cairo", 15.2), City("Kinshasa-Brazzaville", 11.3), City("Greater Johannesburg", 7.55), City("Mogadishu", 5.85), City("Khartoum-Omdurman", 4.98), City("Dar Es Salaam", 4.7), City("Alexandria"...
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 ...
#E
E
def haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]   /** meet the 'raise an exception' requirement */ def find(needle) { switch (haystack.indexOf1(needle)) { match ==(-1) { throw("an exception") } match index { return index } } }   println(find("Ronald")) # pr...
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#SNOBOL4
SNOBOL4
expression = "' page ' (i + 1)" i = 7 output = eval(expression) end
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Sparkling
Sparkling
let fn = exprtofn("13 + 37"); fn() // -> 50
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Tcl
Tcl
set four 4 set result1 [eval "expr {$four + 5}"] ;# string input   set result2 [eval [list expr [list $four + 5]]] ;# list input
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#TI-89_BASIC
TI-89 BASIC
#lang transd   MainModule : { str: "(textout \"eval output: \" (+ 1 1))",   _start: (λ (eval str) ) }
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#ALGOL_W
ALGOL W
begin real procedure rk4 ( real procedure f ; real value y, x, dx ) ; begin  % Fourth-order Runge-Kutta method % real dy1, dy2, dy3, dy4; dy1 := dx * f(x, y); dy2 := dx * f(x + dx / 2.0, y + dy1 / 2.0); dy3 := dx * f(x + dx / 2.0, y + dy2 / 2.0); dy4 := dx * f(x + dx, y + dy3)...
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: ...
#APL
APL
  ∇RK4[⎕]∇ ∇ [0] Z←R(Y¯ RK4)Y;T;YN;TN;∆T;∆Y1;∆Y2;∆Y3;∆Y4 [1] (T R ∆T)←R [2] LOOP:→(R≤TN←¯1↑T)/EXIT [3] ∆Y1←∆T×TN Y¯ YN←¯1↑Y [4] ∆Y2←∆T×(TN+∆T÷2)Y¯ YN+∆Y1÷2 [5] ∆Y3←∆T×(TN+∆T÷2)Y¯ YN+∆Y2÷2 [6] ∆Y4←∆T×(TN+∆T)Y¯ YN+∆Y3 [7] Y←Y,YN+(∆Y1+(2×∆Y2)+(2×∆Y3)+∆Y4)÷6 [8] T←T,TN+∆T [9] →LOOP [10] EXIT:Z←...
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...
#Metafont
Metafont
vardef evalit(expr s, va, vb) = save x,a,b; x := va; a := scantokens s; x := vb; b := scantokens s; a-b enddef;   show(evalit("2x+1", 5, 3)); end
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...
#Nim
Nim
import macros, strformat   macro eval(s, x: static[string]): untyped = parseStmt(&"let x={x}\n{s}")   echo(eval("x+1", "3.1"))
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...
#ooRexx
ooRexx
  say evalWithX("x**2", 2) say evalWithX("x**2", 3.1415926)   ::routine evalWithX use arg expression, x   -- X now has the value of the second argument interpret "return" expression  
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). ...
#APL
APL
pretty⊂(0((3 'Hi')(3 'Bye')(1 'A string')(0((3 'Depth')(2 42))))) ( Hi Bye "A string" ( Depth ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { var n, e, d, bb, ptn, etn, dtn big.Int pt := "Rosetta Code" fmt.Println("Plain text: ", pt)   // a key set big enough to hold 16 bytes of plain text in // a single block (to simplify the example) and also big enough //...
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...
#APL
APL
roll←{(+/-⌊/)¨?¨6/⊂4/6}⍣{(75≤+/⍺)∧2≤+/⍺≥15}
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...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program rpg.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBTIRAGES, 4 .equ ...
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...
#PL.2FSQL
PL/SQL
CREATE OR REPLACE PACKAGE sieve_of_eratosthenes AS TYPE array_of_booleans IS varray(100000000) OF BOOLEAN; TYPE table_of_integers IS TABLE OF INTEGER; FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined; END sieve_of_eratosthenes; /   CREATE OR REPLACE PACKAGE BODY sieve_of_eratosthenes AS FUNCTI...
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#SQL
SQL
  CREATE TABLE african_capitals(name varchar2(100), population_in_millions NUMBER(3,2));  
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 ...
#Elena
Elena
import system'routines; import extensions;   public program() { var haystack := new string[]{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"};   new string[]{"Washington", "Bush"}.forEach:(needle) { var index := haystack.indexOfElement:needle;   if (index == -1) ...
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Transd
Transd
#lang transd   MainModule : { str: "(textout \"eval output: \" (+ 1 1))",   _start: (λ (eval str) ) }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#UNIX_Shell
UNIX Shell
$ a=42 $ b=a $ eval "echo \$$b" 42
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Ursa
Ursa
# writes hello world to the console eval "out \"hello world\" endl console" console  
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,...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   with Ada.Containers.Ordered_Sets; with Ada.Strings.Less_Case_Insensitive;   with AWS.Client; with AWS.Response;   ...
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...
#11l
11l
F encode(input_string) V count = 1 V prev = Char("\0") [(Char, Int)] lst L(character) input_string I character != prev I prev != Char("\0") lst.append((prev, count)) count = 1 prev = character E count++ lst.append((input_string.last, count)) ...
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: ...
#AWK
AWK
  # syntax: GAWK -f RUNGE-KUTTA_METHOD.AWK # converted from BBC BASIC BEGIN { print(" t y error") y = 1 for (i=0; i<=100; i++) { t = i / 10 if (t == int(t)) { actual = ((t^2+4)^2) / 16 printf("%2d %12.7f %g\n",t,y,actual-y) } k1 = t * sqrt(y) k2 = (t ...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Go
Go
package main   import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" )   type Result struct { lang string users int }   func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "h...
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...
#Oz
Oz
declare fun {EvalWithX Program A B} {Compiler.evalExpression Program env('X':B) _} - {Compiler.evalExpression Program env('X':A) _} end in {Show {EvalWithX "{Exp X}" 0.0 1.0}}
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...
#PARI.2FGP
PARI/GP
test(f,a,b)=f=eval(f);f(a)-f(b); test("x->print(x);x^2-sin(x)",1,3)
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). ...
#Arturo
Arturo
code: { ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) }   s: first to :block code inspect.muted s print as.code s
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...
#Haskell
Haskell
module RSAMaker where import Data.Char ( chr )   encode :: String -> [Integer] encode s = map (toInteger . fromEnum ) s   rsa_encode :: Integer -> Integer -> [Integer] -> [Integer] rsa_encode n e numbers = map (\num -> mod ( num ^ e ) n ) numbers   rsa_decode :: Integer -> Integer -> [Integer] -> [Integer] rsa_deco...
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...
#Arturo
Arturo
vals: []   while [or? 75 > sum vals 2 > size select vals => [&>=15]] [ vals: new []   while [6 > size vals][ rands: new map 1..4 => [random 1 6] remove 'rands .once (min rands) 'vals ++ sum rands ] ]   print ["values:" vals ] print ["with sum:" sum vals]
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...
#Atari_BASIC
Atari BASIC
100 REM RPG character generator 110 DIM AT(5) 120 DIM AT$(18) 130 AT$="StrDexConIntWisCha" 140 PT=0:SA=0 150 PRINT CHR$(125);CHR$(29);CHR$(31);"Rolling..." 160 FOR AI=0 TO 5 170 DT=0:MI=6:REM dice total, min die 180 FOR I=0 TO 3 190 D=INT(RND(1)*6)+1 200 DT=DT+D 210 IF D<MI THEN MI=D 220 NEXT I 230 DT=DT-MI 240 AT(AI)=...
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...
#Pony
Pony
use "time" // for testing use "collections"   class Primes is Iterator[U32] // returns an Iterator of found primes... let _bitmask: Array[U8] = [ 1; 2; 4; 8; 16; 32; 64; 128 ] var _lmt: USize let _cmpsts: Array[U8] var _ndx: USize = 2 var _curr: U32 = 2   new create(limit: U32) ? => _lmt = USize.from[U3...
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Standard_ML
Standard ML
type city = { name : string, population : real }   val citys : city list = [ { name = "Lagos", population = 21.0 }, { name = "Cairo", population = 15.2 }, { name = "Kinshasa-Brazzaville", population = 11.3 }, { name = "Greater Johannesburg", population = ...
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Swift
Swift
struct Place { var name: String var population: Double }   let places = [ Place(name: "Lagos", population: 21.0), Place(name: "Cairo", population: 15.2), Place(name: "Kinshasa-Brazzaville", population: 11.3), Place(name: "Greater Johannesburg", population: 7.55), Place(name: "Mogadishu", population: 5.85)...
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 ...
#Elixir
Elixir
haystack = ~w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)   Enum.each(~w(Bush Washington), fn needle -> index = Enum.find_index(haystack, fn x -> x==needle end) if index, do: (IO.puts "#{index} #{needle}"), else: raise "#{needle} is not in haystack\n" end)
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Wren
Wren
$ wren-cli \\/"- \_/ wren v0.3.0 > 20 + 22 42 > 5 * 81.sqrt 45 > var triple = Fn.new { |x| x * 3 } > triple.call(16) 48 >
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#zkl
zkl
Compiler.Compiler.compileText( "fcn f(text){text.len()}").f("foobar") //-->6
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,...
#ALGOL_68
ALGOL 68
PROC good page = (REF STRING page) BOOL: IF grep in string("^HTTP/[0-9.]* 200", page, NIL, NIL) = 0 THEN TRUE ELSE IF INT start, end; grep in string("^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*", page, start, end) = 0 THEN print (page[start : end]) ELSE ...
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...
#8086_Assembly
8086 Assembly
.model small ; 128k .exe file .stack 1024 ; load SP with 0400h .data ; no data segment needed   .code   start:   mov ax,@code mov ds,ax mov es,ax   mov si,offset TestString mov di,offset OutputRam   cld   compressRLE: lodsb cmp al,0 ;null te...
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: ...
#BASIC
BASIC
y = 1 for i = 0 to 100 t = i / 10   if t = int(t) then actual = ((t ^ 2 + 4) ^ 2) / 16 print "y("; int(t); ") = "; left(string(y), 13), "Error = "; left(string(actual - y), 13) end if   k1 = t * sqr(y) k2 = (t + 0.05) * sqr(y + 0.05 * k1) k3 = (t + 0.05) * sqr(y + 0.05 * k2) k4 = (t + 0.10...
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: ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   double rk4(double(*f)(double, double), double dx, double x, double y) { double k1 = dx * f(x, y), k2 = dx * f(x + dx / 2, y + k1 / 2), k3 = dx * f(x + dx / 2, y + k2 / 2), k4 = dx * f(x + dx, y + k3); return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6; }   doub...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Julia
Julia
""" Rank languages on Rosetta Code's site by number of users."""   using HTTP using JSON3   const URI = "http://rosettacode.org/mw" const PARAMS = [ "action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers", "gcmtitle" => "Category:Language users", "gcmlim...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Nim
Nim
import algorithm, httpclient, json, strformat, strscans, strutils   const Action = "action=query" Format = "format=json" FormatVersion = "formatversion=2" Generator = "generator=categorymembers" GcmTitle = "gcmtitle=Category:Language%20users" GcmLimit = "gcmlimit=500" Prop = "prop=categoryinfo"   Page =...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Perl
Perl
use strict; use warnings; use JSON; use URI::Escape; use LWP::UserAgent;   my $client = LWP::UserAgent->new; $client->agent("Rosettacode Perl task solver"); my $url = 'http://rosettacode.org/mw'; my $minimum = 100;   sub uri_query_string { my(%fields) = @_; 'action=query&format=json&formatversion=2&' . join...
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...
#Perl
Perl
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;}   print eval_with_x('3 * $x', 5, 10), "\n"; # Prints "15".
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...
#Phix
Phix
without javascript_semantics requires("1.0.1") include eval.e function eval_with_x(string expr, integer a, b) return eval(expr,{"x"},{{"x",b}})[1] - eval(expr,{"x"},{{"x",a}})[1] end function ?eval_with_x("integer x = power(2,x)",3,5)
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). ...
#AutoHotkey
AutoHotkey
S_Expressions(Str){ Str := RegExReplace(Str, "s)(?<![\\])"".*?[^\\]""(*SKIP)(*F)|((?<![\\])[)(]|\s)", "`n$0`n") Str := RegExReplace(Str, "`am)^\s*\v+") , Cnt := 0 loop, parse, Str, `n, `r { Cnt := A_LoopField=")" ? Cnt-1 : Cnt Res .= tabs(Cnt) A_LoopField "`r`n" Cnt := A_LoopField="(" ? Cnt+1 : Cnt } return...
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
#11l
11l
V languages = [‘abap’, ‘actionscript’, ‘actionscript3’, ‘ada’, ‘apache’, ‘applescript’, ‘apt_sources’, ‘asm’, ‘asp’, ‘autoit’, ‘avisynth’, ‘bar’, ‘bash’, ‘basic4gl’, ‘bf’, ‘blitzbasic’, ‘bnf’, ‘boo’, ‘c’, ‘caddcl’, ‘cadlisp’, ‘cfdg’, ‘cfm’, ‘cil’, ‘c_mac’, ‘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...
#Icon_and_Unicon
Icon and Unicon
procedure main() # rsa demonstration   n := 9516311845790656153499716760847001433441357 e := 65537 d := 5617843187844953170308463622230283376298685 b := 2^integer(log(n,2)) # for blocking write("RSA Demo using\n n = ",n,"\n e = ",e,"\n d = ",d,"\n b = ",b)   every m := !["Rosetta Cod...
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...
#BASIC256
BASIC256
function min(a, b) if a < b then return a else return b end function   function d6() #simulates a marked regular hexahedron coming to rest on a plane return 1 + int(rand * 6) end function   function roll_stat() #rolls four dice, returns the sum of the three highest 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...
#Pop11
Pop11
define eratostenes(n); lvars bits = inits(n), i, j; for i from 2 to n do if bits(i) = 0 then printf('' >< i, '%s\n'); for j from 2*i by i to n do 1 -> bits(j); endfor; endif; endfor; enddefine;
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Tcl
Tcl
# records is a list of dicts. set records { { name "Lagos" population 21.0 } { name "Cairo" population 15.2 } { name "Kinshasa-Brazzaville" population 11.3 } { name "Greater Johannesburg" population 7.55 } { name "Mogadishu" population 5.85 } { name "Khartoum-Om...
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 ...
#Erlang
Erlang
-module(index). -export([main/0]).   main() -> Haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"], Needles = ["Washington","Bush"], lists:foreach(fun ?MODULE:print/1, [{N,pos(N, Haystack)} || N <- Needles]).   pos(Needle, Haystack) -> pos(Needle, Haystack, 1). pos(_, [], _) ->...
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,...
#AutoHotkey
AutoHotkey
MembsUrl = http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000 ValidUrl = http://rosettacode.org/wiki/Category:Programming_Languages WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")   ; Get the webpages WebRequest.Open("GET", MembsUrl),WebRequest.Send() MembsPage := WebRequest.ResponseText W...
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...
#Action.21
Action!
BYTE FUNC GetLength(CHAR ARRAY s BYTE pos) CHAR c BYTE len   c=s(pos) len=1 DO pos==+1 IF pos<=s(0) AND s(pos)=c THEN len==+1 ELSE EXIT FI OD RETURN (len)   BYTE FUNC GetNumber(CHAR ARRAY s BYTE POINTER pos) BYTE num,len CHAR ARRAY tmp(5)   len=0 DO len==+1 tmp(le...
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: ...
#C.23
C#
  using System;   namespace RungeKutta { class Program { static void Main(string[] args) { //Incrementers to pass into the known solution double t = 0.0; double T = 10.0; double dt = 0.1;   // Assign the number of elements needed for th...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Phix
Phix
1: 397 - C 2: 278 - C++ =: 278 - Java 4: 266 - Python 5: 240 - JavaScript 6: 171 - Perl 7: 168 - PHP 8: 139 - SQL 9: 131 - UNIX Shell 10: 121 - C sharp 11: 120 - BASIC 12: 118 - Pascal 13: 102 - Haskell 14: 93 - Ruby 15: 81 - Fortran 16: 70 - Visual Basic 17: 65 - Prolog 18: 61 - Scheme 19: ...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Python
Python
"""Rank languages by number of users. Requires Python >=3.5"""   import requests   # MediaWiki API URL. URL = "http://rosettacode.org/mw/api.php"   # Query string parameters PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Lang...
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...
#PHP
PHP
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; }   echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
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...
#PicoLisp
PicoLisp
(let Expression '(+ X (* X X)) # Local expression (println (+ (let X 3 (eval Expression) ) (let X 4 (eval Expression) ) ) ) (let Function (list '(X) Expression) # Build a local function (println (+ (Function 3) (Fu...
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). ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h>   enum { S_NONE, S_LIST, S_STRING, S_SYMBOL };   typedef struct { int type; size_t len; void *buf; } s_expr, *expr;   void whine(const char *s) { fprintf(stderr, "parse error before ==>%.10s\n", s); }   expr parse_string(const char *s, ch...
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
#AutoHotkey
AutoHotkey
; usage: > fixtags.ahk input.txt ouput.txt FileRead, text, %1% langs = ada,awk,autohotkey,etc slang = /lang slang := "<" . slang . "/>" Loop, Parse, langs, `, { tag1 = <%A_LoopField%> tag2 = </%A_LoopField%> text := RegExReplace(text, tag1, "<lang " . A_LoopField . ">") text := RegExReplace(text, tag2, slang) ...
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
#D
D
import std.stdio, std.regex, std.string, std.array;   immutable langs = "_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 freebasi...
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...
#J
J
N=: 9516311845790656153499716760847001433441357x E=: 65537x D=: 5617843187844953170308463622230283376298685x   ] text=: 'Rosetta Code' Rosetta Code ] num=: 256x #. a.i.text 25512506514985639724585018469 num >: N NB. check if blocking is necessary (0 means no) 0 ] enc=: N&|@^&E num 9167094427443566...
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...
#Java
Java
  public static void main(String[] args) { /* This is probably not the best method...or even the most optimized way...however it works since n and d are too big to be ints or longs This was also only tested with 'Rosetta Code' and 'Hello World' It's also pretty limited on plainText size (anything bigger...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <time.h>   int compareInts(const void *i1, const void *i2) { int a = *((int *)i1); int b = *((int *)i2); return a - b; }   int main() { int i, j, nsum, vsum, vcount, values[6], numbers[4]; srand(time(NULL)); for (;;) { vsum = 0; for...
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...
#PowerShell
PowerShell
function Sieve ( [int] $num ) { $isprime = @{} 2..$num | Where-Object { $isprime[$_] -eq $null } | ForEach-Object { $_ $isprime[$_] = $true $i=$_*$_ for ( ; $i -le $num; $i += $_ ) { $isprime[$i] = $false } } }
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Wren
Wren
import "/dynamic" for Tuple   var Element = Tuple.create("Element", ["record", "index"])   var findFirst = Fn.new { |seq, pred| var i = 0 for (e in seq) { if (pred.call(e)) return Element.new(e, i) i = i + 1 } return Element.new(null, -1) }   var City = Tuple.create("City", ["name", "pop...
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 ...
#Euphoria
Euphoria
  include std/search.e include std/console.e   --the string "needle" and example haystacks to test the procedure sequence searchStr1 = "needle" sequence haystack1 = { "needle", "needle", "noodle", "node", "need", "needle ", "needle" } sequence haystack2 = {"spoon", "fork", "hay", "knife", "needle", "barn", "etcetera",...
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,...
#AWK
AWK
function join(array, start, end, sep, result, i) { result = array[start] for (i = start + 1; i <= end; i++) result = result sep array[i] return result }   function trim(str) { gsub(/^[[:blank:]]+|[[:blank:]\n]+$/, "", str) return str }   function http2var( sit...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Fixed; use Ada.Strings.Fixed; procedure Test_Run_Length_Encoding is function Encode (Data : String) return String is begin if Data'Length = 0 then return ""; else declare Code  : constant Character := Data (Data'...
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: ...
#C.2B.2B
C++
/* * compiled with: * g++ (Debian 8.3.0-6) 8.3.0 * * g++ -std=c++14 -o rk4 % * */ # include <iostream> # include <math.h>   auto rk4(double f(double, double)) { return [f](double t, double y, double dt) -> double { double dy1 { dt * f( t , y ) }, dy2 { dt * f( t+dt/2, y+dy1/2 ) }, ...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Racket
Racket
#lang racket   (require racket/hash net/url json)   (define limit 64) (define (replacer cat) (regexp-replace #rx"^Category:(.*?) User$" cat "\\1")) (define category "Category:Language users") (define entries "users")   (define api-url (string->url "http://rosettacode.org/mw/api.php")) (define (make-co...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users
Rosetta Code/Rank languages by number of users
Task Sort most popular programming languages based on the number of users on Rosetta Code. Show the languages with at least 100 users. A method to solve the task Users of a computer programming language   X   are those referenced in the page: https://rosettacode.org/wiki/Category:X_User, or preferably: ht...
#Raku
Raku
use HTTP::UserAgent; use URI::Escape; use JSON::Fast;   my $client = HTTP::UserAgent.new;   my $url = 'http://rosettacode.org/mw';   my $start-time = now;   say "========= Generated: { DateTime.new(time) } =========";   my $lang = 1; my $rank = 0; my $last = 0; my $tie = ' '; my $minimum = 25;   .say for mediawiki-...
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...
#Pike
Pike
> int x=10; Result: 10 > x * 5; Result: 50 > dump wrapper Last compiled wrapper: 001: mapping(string:mixed) ___hilfe = ___Hilfe->variables; 002: # 1 003: mixed ___HilfeWrapper() { return (([mapping(string:int)](mixed)___hilfe)->x) * 5; ; } 004: >
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...
#Python
Python
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a})   >>> eval_with_x('2 ** x', 3, 5) 24
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). ...
#C.23
C#
  using System; using System.Collections.Generic; using System.Text;   public class SNode { private List<SNode> _items; public string Name { get; set; } public IReadOnlyCollection<SNode> Items { get { return _items.AsReadOnly(); } } public SNode() { this._items ...
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
#Delphi
Delphi
  program Fix_code_tags;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, System.Classes, System.RegularExpressions;   const LANGS: array of string = ['abap', 'actionscript', 'actionscript3', 'ada', 'apache', 'applescript', 'apt_sources', 'asm', 'asp', 'autoit', 'avisynth', 'bash', 'basic4...
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...
#Julia
Julia
function rsaencode(clearmsg::AbstractString, nmod::Integer, expub::Integer) bytes = parse(BigInt, "0x" * bytes2hex(collect(UInt8, clearmsg))) return powermod(bytes, expub, nmod) end   function rsadecode(cryptmsg::Integer, nmod::Integer, dsecr::Integer) decoded = powermod(encoded, dsecr, nmod) return joi...
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...
#Kotlin
Kotlin
// version 1.1.4-3   import java.math.BigInteger   fun main(args: Array<String>) { val n = BigInteger("9516311845790656153499716760847001433441357") val e = BigInteger("65537") val d = BigInteger("5617843187844953170308463622230283376298685") val c = Charsets.UTF_8 val plainText = "Rosetta Code" ...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   static class Module1 { static Random r = new Random();   static List<int> getThree(int n) { List<int> g3 = new List<int>(); for (int i = 0; i < 4; i++) g3.Add(r.Next(n) + 1); g3.Sort(); g3.RemoveAt(0); return g3; ...
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...
#Processing
Processing
int i=2; int maxx; int maxy; int max; boolean[] sieve;   void setup() { size(1000, 1000); // frameRate(2); maxx=width; maxy=height; max=width*height; sieve=new boolean[max+1];   sieve[1]=false; plot(0, false); plot(1, false); for (int i=2; i<=max; i++) { sieve[i]=true; plot(i, true); } }  ...
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#zkl
zkl
list:=T(SD("name","Lagos", "population",21.0), // SD is a fixed dictionary SD("name","Cairo", "population",15.2), SD("name","Kinshasa-Brazzaville", "population",11.3), SD("name","Greater Johannesburg", "population", 7.55), SD("name","Mogadishu", "population", 5.85), SD("name","Khartoum-Omdur...
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 ...
#F.23
F#
List.findIndex (fun x -> x = "bar") ["foo"; "bar"; "baz"; "bar"] // -> 1 // A System.Collections.Generic.KeyNotFoundException // is raised, if the predicate does not evaluate to // true for any list elemen...
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,...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" SortUp% = FN_sortinit(0,0)  : REM Ascending SortDown% = FN_sortinit(1,0) : REM Descending   VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support DIM lang$(1000), tasks%(1000) NORM_IGNORECASE = 1   SYS "LoadLibrary", "URLMON.DLL" TO urlmon% 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...
#ALGOL_68
ALGOL 68
STRING input := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; STRING output := "12W1B12W3B24W1B14W";   MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID;   PROC gen char string = (REF STRING s, YIELDCHAR yield)VOID: FOR i FROM LWB s TO UPB s DO yield(s[i]) OD;   CO # Note: T...
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...
#11l
11l
F rot13(string) V r = ‘ ’ * string.len L(c) string r[L.index] = S c ‘a’..‘z’ Char(code' (c.code - ‘a’.code + 13) % 26 + ‘a’.code) ‘A’..‘Z’ Char(code' (c.code - ‘A’.code + 13) % 26 + ‘A’.code) ...