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 the haystack. See also Search a list of records
#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')); // exception
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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#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; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int N, SafeCnt, UnsafeCnt Unsafes(40); [SafeCnt:= 0; UnsafeCnt:= 0; Text(0, "First 35 safe primes:^M^J"); for N:= 1 to 10_000_000-1 do [if IsPrime(N) then [if IsPrime( (N-1)/2 ) then [SafeCnt:= SafeCnt+1; if SafeCnt <= 35 then [NumOut(N); ChOut(0, ^ )]; ] else [Unsafes(UnsafeCnt):= N; UnsafeCnt:= UnsafeCnt+1; ]; ]; if N = 999_999 then [Text(0, "^M^JSafe primes below 1,000,000: "); NumOut(SafeCnt); Text(0, "^M^JUnsafe primes below 1,000,000: "); NumOut(UnsafeCnt); ]; ]; Text(0, "^M^JFirst 40 unsafe primes:^M^J"); for N:= 0 to 40-1 do [NumOut(Unsafes(N)); ChOut(0, ^ )]; Text(0, "^M^JSafe primes below 10,000,000: "); NumOut(SafeCnt); Text(0, "^M^JUnsafe primes below 10,000,000: "); NumOut(UnsafeCnt); CrLf(0); ]
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   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#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()) else notSafe.append(p.toInt()); p.nextPrime(); }while(safe.len()<sN or notSafe.len()<nsN); println("The first %d safe primes are: %s".fmt(sN,safe[0,sN].concat(","))); println("The first %d unsafe primes are: %s".fmt(nsN,notSafe[0,nsN].concat(","))); }(35,40);
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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 * dy2 + 2.0 * dy3 + dy4) / 6.0 END; REAL x0 = 0, x1 = 10, y0 = 1.0; CO Boundary conditions. CO REAL dx = 0.1; CO Step size. CO INT num points = ENTIER ((x1 - x0) / dx + 0.5); CO Add 0.5 for rounding errors. CO [0:num points]REAL y; y[0] := y0; CO Grid and starting point.CO PROC dy by dx = (REAL x, y) REAL : x * sqrt(y); CO Differential equation. CO FOR i TO num points DO y[i] := rk4 (dy by dx, y[i-1], x0 + dx * (i - 1), dx) OD; print ((" x true y calc y relative error", newline)); FOR i FROM 0 BY 10 TO num points DO REAL x = x0 + dx * i; REAL true y = (x * x + 4.0) ^ 2 / 16.0; printf (($3(-zzd.7dxxx), -d.4de-ddl$, x, true y, y[i], y[i] / true y - 1.0)) OD 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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#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( ( "**** ", msg, newline ) ); # S-expression reader - reads and returns an S-expression from the string s # PROC s reader = ( STRING s )REF SEXPR: BEGIN PROC at end = BOOL: s pos > UPB s; PROC curr = CHAR: IF at end THEN REPR 0 ELSE s[ s pos ] FI; PROC skip spaces = VOID: WHILE NOT at end AND ( curr = " " OR curr = nl ) DO s pos +:= 1 OD; PROC end of list = BOOL: at end OR curr = ")"; INT s pos := LWB s; INT t pos; [ ( UPB s - LWB s ) + 1 ]CHAR token; # token text - large enough to hold the whole string if necessary # # adds the current character to the token # PROC add curr = VOID: token[ t pos +:= 1 ] := curr; # get an s expression element from s # PROC get element = REF SEXPR: BEGIN REF SEXPR result = new s expr; skip spaces; # get token text # IF at end THEN # no element # element OF result := EMPTY ELIF curr = "(" THEN s pos +:= 1; skip spaces; IF NOT end of list THEN REF SEXPR nested expression = get element; REF SEXPR element pos := nested expression; element OF result := nested expression; skip spaces; WHILE NOT end of list DO element pos := next OF element pos := get element; skip spaces OD FI; IF curr = ")" THEN s pos +:= 1 ELSE error( "Missing "")""" ) FI ELIF curr = ")" THEN s pos +:= 1; error( "Unexpected "")""" ); element OF result := EMPTY ELSE # quoted or unquoted string # t pos := LWB token - 1; IF curr /= """" THEN # unquoted string # WHILE add curr; s pos +:= 1; NOT at end AND curr /= " " AND curr /= "(" AND curr /= ")" AND curr /= """" AND curr /= nl DO SKIP OD ELSE # quoted string # WHILE add curr; s pos +:= 1; NOT at end AND curr /= """" DO SKIP OD; IF curr /= """" THEN # missing string quote # error( "Unterminated string: <<" + token[ : t pos ] + ">>" ) ELSE # have the closing quote # add curr; s pos +:= 1 FI FI; element OF result := token[ : t pos ] FI; result END # get element # ;   REF SEXPR s expr = get element; skip spaces; IF NOT at end THEN # extraneuos text after the expression # error( "Unexpected text at end of expression: " + s[ s pos : ] ) FI;   s expr END # s reader # ; # prints an S expression # PROC s writer = ( REF SEXPR s expr )VOID: BEGIN # prints an S expression with a suitable indent # PROC print indented s expression = ( REF SEXPR s expr, INT indent )VOID: BEGIN REF SEXPR s pos := s expr; WHILE REF SEXPR( s pos ) ISNT REF SEXPR( NIL ) DO FOR i TO indent DO print( ( " " ) ) OD; CASE element OF s pos IN (VOID ): print( ( "()", newline ) ) , (STRING s): print( ( s, newline ) ) , (REF SEXPR e): BEGIN print( ( "(", newline ) ); print indented s expression( e, indent + 4 ); FOR i TO indent DO print( ( " " ) ) OD; print( ( ")", newline ) ) END OUT error( "Unexpected S expression element" ) ESAC; s pos := next OF s pos OD END # print indented s expression # ;   print indented s expression( s expr, 0 ) END # s writer # ; # test the eader and writer with the example from the task # s writer( s reader( "((data ""quoted data"" 123 4.5)" + nl + " (data (!@# (4.5) ""(more"" ""data)"")))" + nl ) )
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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_set_str(e, "65537", 10) mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10) mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10)   Dim As ZString Ptr plaintext : plaintext = Allocate(1000) Dim As ZString Ptr text  : text = Allocate(1000) *plaintext = "Rosetta Code"   mpz_import(pt, Len(*plaintext), 1, 1, 0, 0, plaintext)   If mpz_cmp(pt, n) > 0 Then GoTo clean_up   mpz_powm(ct, pt, e, n) gmp_printf(!" Encoded: %Zd\n", ct)   mpz_powm(pt, ct, d, n) gmp_printf(!" Decoded: %Zd\n", pt)   mpz_export(text, NULL, 1, 1, 0, 0, pt) Print "As string: "; *text   clean_up: DeAllocate(plaintext) : DeAllocate(text) mpz_clear(e) : mpz_clear(d) : mpz_clear(n) mpz_clear(pt) : mpz_clear(ct)   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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; IF v < min THEN min := v FI; sum +:= v OD; sum - min END # generate attrib #;   PROC generate = ( REF RESULT res )VOID: BEGIN high count OF res := 0; sum OF res := 0; FOR i FROM LWB a OF res TO UPB a OF res DO INT v = generate attrib; IF v >= 15 THEN high count OF res +:= 1 FI; sum OF res +:= v; ( a OF res )[ i ] := v OD; success OF res := ( high count OF res >= 2 AND sum OF res >= 75 ) END # generate # ;   RESULT res; success OF res := FALSE; WHILE NOT success OF res DO generate( res ); print( ( "attribs: " ) ); FOR i FROM LWB a OF res TO UPB a OF res DO print( ( whole( ( a OF res )[ i ], 0 ) ) ); IF i < UPB a OF res THEN print( ( " " ) ) FI OD; print( ( " sum=", whole( sum OF res, 0 ) , " highCount=", whole( high count OF res, 0 ) , " ", IF success OF res THEN "success" ELSE "failed" FI , newline ) ) OD   END
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 PRIME AT BEGINNING */ END;   DO N=2 TO SIZE; IF PRIME(N) THEN DO; /* IF A NUMBER IS PRIME... */ DO M=N*N TO SIZE BY N; PRIME(M) = 0; /* THEN ITS MULTIPLES ARE NOT */ END; END; END; END MAKE$SIEVE;   /* CP/M CALLS */ BDOS: PROCEDURE(FUNC, ARG); DECLARE FUNC BYTE, ARG ADDRESS; GO TO 5; END BDOS;   DECLARE BDOS$EXIT LITERALLY '0', BDOS$PRINT LITERALLY '9';   /* PRINT A 16-BIT NUMBER */ PRINT$NUMBER: PROCEDURE(N); DECLARE (N, P) ADDRESS; DECLARE S (8) BYTE INITIAL ('.....',10,13,'$'); DECLARE C BASED P BYTE; P = .S(5); DIGIT: P = P - 1; C = (N MOD 10) + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL BDOS(BDOS$PRINT, P); END PRINT$NUMBER;   /* PRINT ALL PRIMES UP TO N */ PRINT$PRIMES: PROCEDURE(N, SIEVE); DECLARE (I, N, SIEVE) ADDRESS; DECLARE PRIME BASED SIEVE BYTE; CALL MAKE$SIEVE(SIEVE, N); DO I = 2 TO N; IF PRIME(I) THEN CALL PRINT$NUMBER(I); END; END PRINT$PRIMES;   CALL PRINT$PRIMES(PRIME$MAX, .MEMORY);   CALL BDOS(BDOS$EXIT, 0); EOF
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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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", 4.58), City("Abidjan", 4.4), City("Casablanca", 3.98), ]   say cities.index{|city| city.name == "Dar Es Salaam"} say cities.first{|city| city.population < 5.0}.name say cities.first{|city| city.name.begins_with("A")}.population
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#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")) # prints 3 println(find("McDonald")) # will throw
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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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); y + (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0 end rk4; real x0, x1, y0, dx; integer numPoints; x0 := 0; x1 := 10; y0 := 1.0;  % Boundary conditions. % dx := 0.1;  % Step size. % numPoints := entier ((x1 - x0) / dx + 0.5);  % Add 0.5 for rounding errors. % begin real procedure dyByDx ( real value x, y ) ; x * sqrt(y); % Differential equation. % real array y ( 0 :: numPoints); y(0) := y0;  % Grid and starting point. % for i := 1 until numPoints do y(i) := rk4 (dyByDx, y(i-1), x0 + dx * (i - 1), dx); write( " x true y calc y relative error" ); for i := 0 step 10 until numPoints do begin real x, trueY; x  := x0 + dx * i; trueY := (x * x + 4.0) ** 2 / 16.0; write( r_format := "A", r_w := 12, r_d := 7, s_w := 3, x, trueY, y( i ) , r_format := "S", r_w := 12, y( i ) / trueY - 1 ) end for_i end end.
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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←T,[⎕IO+.5]Y ∇   ∇PRINT[⎕]∇ ∇ [0] PRINT;TABLE [1] TABLE←0 10 .1({⍺×⍵*.5}RK4)1 [2] ⎕←'T' 'RK4 Y' 'ERROR'⍪TABLE,TABLE[;2]-{((4+⍵*2)*2)÷16}TABLE[;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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#APL
APL
pretty⊂(0((3 'Hi')(3 'Bye')(1 'A string')(0((3 'Depth')(2 42))))) ( Hi Bye "A string" ( Depth 42 ) )
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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 // to demonstrate efficiency of modular exponentiation. n.SetString("9516311845790656153499716760847001433441357", 10) e.SetString("65537", 10) d.SetString("5617843187844953170308463622230283376298685", 10)   // convert plain text to a number for _, b := range []byte(pt) { ptn.Or(ptn.Lsh(&ptn, 8), bb.SetInt64(int64(b))) } if ptn.Cmp(&n) >= 0 { fmt.Println("Plain text message too long") return } fmt.Println("Plain text as a number:", &ptn)   // encode a single number etn.Exp(&ptn, &e, &n) fmt.Println("Encoded: ", &etn)   // decode a single number dtn.Exp(&etn, &d, &n) fmt.Println("Decoded: ", &dtn)   // convert number to text var db [16]byte dx := 16 bff := big.NewInt(0xff) for dtn.BitLen() > 0 { dx-- db[dx] = byte(bb.And(&dtn, bff).Int64()) dtn.Rsh(&dtn, 8) } fmt.Println("Decoded number as text:", string(db[dx:])) }
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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 highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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 NBTIRAGESOK, 3 .equ NBVALUES, 6 .equ TOTALMIN, 75 .equ MAXVALUE, 15 .equ NBMAXVALUE, 2 /*******************************************/ /* Fichier des macros */ /********************************************/ .include "../../ficmacros.s"   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .ascii "Value = " sMessValeur: .fill 11, 1, ' ' @ size => 11 szCarriageReturn: .asciz "\n" sMessResultT: .ascii "Total = " sMessValeurT: .fill 11, 1, ' ' @ size => 11 .asciz "\n" sMessResultQ: .ascii "Values above 15 = " sMessValeurQ: .fill 11, 1, ' ' @ size => 11 .asciz "\n"   .align 4 iGraine: .int 123456   /*********************************/ /* UnInitialized data */ /*********************************/ .bss tiTirages: .skip 4 * NBTIRAGES tiValues: .skip 4 * NBVALUES /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   1: @ begin loop 1 mov r2,#0 @ counter value >15 mov r4,#0 @ loop indice mov r5,#0 @ total ldr r3,iAdrtiValues @ table values address 2: bl genValue @ call generate value str r0,[r3,r4,lsl #2] @ store in table add r5,r0 @ compute total cmp r0,#MAXVALUE @ count value > 15 addge r2,#1 add r4,#1 @ increment indice cmp r4,#NBVALUES @ end ? blt 2b cmp r5,#TOTALMIN @ compare 75 blt 1b @ < loop cmp r2,#NBMAXVALUE @ compare value > 15 blt 1b @ < loop ldr r0,iAdrtiValues @ display values bl displayTable mov r0,r5 @ total ldr r1,iAdrsMessValeurT @ display value bl conversion10 @ call conversion decimal ldr r0,iAdrsMessResultT bl affichageMess @ display message   mov r0,r2 @ counter value > 15 ldr r1,iAdrsMessValeurQ @ display value bl conversion10 @ call conversion decimal ldr r0,iAdrsMessResultQ bl affichageMess @ display message   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrsMessValeurT: .int sMessValeurT iAdrsMessResultT: .int sMessResultT iAdrsMessValeurQ: .int sMessValeurQ iAdrsMessResultQ: .int sMessResultQ iAdrtiValues: .int tiValues /******************************************************************/ /* generate value */ /******************************************************************/ /* r0 returns the value */ genValue: push {r1-r4,lr} @ save registers mov r4,#0 @ indice loop ldr r1,iAdrtiTirages @ table tirage address 1: mov r0,#6 bl genereraleas @ result 0 to 5 add r0,#1 @ for 1 to 6 str r0,[r1,r4,lsl #2] @ store tirage add r4,#1 @ increment indice cmp r4,#NBTIRAGES @ end ? blt 1b @ no -> loop ldr r0,iAdrtiTirages @ table tirage address mov r1,#0 @ first item mov r2,#NBTIRAGES @ number of tirages bl shellSort @ sort table decreasing mov r4,#0 @ raz indice loop mov r0,#0 @ total ldr r1,iAdrtiTirages @ table tirage address 2: ldr r2,[r1,r4,lsl #2] @ read tirage add r0,r2 @ compute sum add r4,#1 @ inrement indice cmp r4,#NBTIRAGESOK @ end ? blt 2b 100: pop {r1-r4,lr} bx lr @ return iAdrtiTirages: .int tiTirages /***************************************************/ /* shell Sort decreasing */ /***************************************************/ /* r0 contains the address of table */ /* r1 contains the first element but not use !! */ /* this routine use first element at index zero !!! */ /* r2 contains the number of element */ shellSort: push {r0-r7,lr} @save registers   sub r2,#1 @ index last item mov r1,r2 @ init gap = last item 1: @ start loop 1 lsrs r1,#1 @ gap = gap / 2 beq 100f @ if gap = 0 -> end mov r3,r1 @ init loop indice 1 2: @ start loop 2 ldr r4,[r0,r3,lsl #2] @ load first value mov r5,r3 @ init loop indice 2 3: @ start loop 3 cmp r5,r1 @ indice < gap blt 4f @ yes -> end loop 2 sub r6,r5,r1 @ index = indice - gap ldr r7,[r0,r6,lsl #2] @ load second value cmp r4,r7 @ compare values strgt r7,[r0,r5,lsl #2] @ store if > subgt r5,r1 @ indice = indice - gap bgt 3b @ and loop 4: @ end loop 3 str r4,[r0,r5,lsl #2] @ store value 1 at indice 2 add r3,#1 @ increment indice 1 cmp r3,r2 @ end ? ble 2b @ no -> loop 2 b 1b @ yes loop for new gap   100: @ end function pop {r0-r7,lr} @ restaur registers bx lr @ return     /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message add r3,#1 cmp r3,#NBVALUES - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess 100: pop {r0-r3,lr} bx lr /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3 //movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3 ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD /***************************************************/ /* Generation random number */ /***************************************************/ /* r0 contains limit */ genereraleas: push {r1-r4,lr} @ save registers ldr r4,iAdriGraine ldr r2,[r4] ldr r3,iNbDep1 mul r2,r3,r2 ldr r3,iNbDep1 add r2,r2,r3 str r2,[r4] @ maj de la graine pour appel suivant cmp r0,#0 beq 100f mov r1,r0 @ divisor mov r0,r2 @ dividende bl division mov r0,r3 @ résult = remainder   100: @ end function pop {r1-r4,lr} @ restaur registers bx lr @ return /*****************************************************/ iAdriGraine: .int iGraine iNbDep1: .int 0x343FD iNbDep2: .int 0x269EC3 /***************************************************/ /* integer division unsigned */ /***************************************************/ division: /* r0 contains dividend */ /* r1 contains divisor */ /* r2 returns quotient */ /* r3 returns remainder */ push {r4, lr} mov r2, #0 @ init quotient mov r3, #0 @ init remainder mov r4, #32 @ init counter bits b 2f 1: @ loop movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C cmp r3, r1 @ compute r3 - r1 and update cpsr subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 2: subs r4, r4, #1 @ r4 <- r4 - 1 bpl 1b @ if r4 >= 0 (N=0) then loop pop {r4, lr} bx lr    
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined IS flag array_of_booleans; ptr INTEGER; i INTEGER; BEGIN flag := array_of_booleans(FALSE, TRUE); flag.extend(n - 2, 2); ptr := 1; << outer_loop >> WHILE ptr * ptr <= n LOOP WHILE NOT flag(ptr) LOOP ptr := ptr + 1; END LOOP; i := ptr * ptr; WHILE i <= n LOOP flag(i) := FALSE; i := i + ptr; END LOOP; ptr := ptr + 1; END LOOP outer_loop; FOR i IN 1 .. n LOOP IF flag(i) THEN pipe ROW (i); END IF; END LOOP; RETURN; END find_primes; END sieve_of_eratosthenes; /
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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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 the haystack. See also Search a list of records
#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) { console.printLine(needle," is not in haystack") } else { console.printLine(needle, " - ", index) } } }
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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#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;   procedure Test is   use Ada.Strings;   function "+" (S : String) return Unbounded_String renames To_Unbounded_String;   type A_Language_Count is record Count  : Integer := 0; Language : Unbounded_String; end record;   function "=" (L, R : A_Language_Count) return Boolean is begin return L.Language = R.Language; end "=";   function "<" (L, R : A_Language_Count) return Boolean is begin -- Sort by 'Count' and then by Language name return L.Count < R.Count or else (L.Count = R.Count and then Less_Case_Insensitive (Left => To_String (L.Language), Right => To_String (R.Language))); end "<";   package Sets is new Ada.Containers.Ordered_Sets (A_Language_Count); use Sets;   Counts : Set;   procedure Find_Counts (S : String) is Title_Str : constant String  := "title=""Category:"; End_A_Str : constant String  := "</a> (";   Title_At  : constant Natural := Index (S, Title_Str); begin if Title_At /= 0 then declare Bracket_At : constant Natural := Index (S (Title_At + Title_Str'Length .. S'Last), ">"); End_A_At  : constant Natural := Index (S (Bracket_At + 1 .. S'Last), End_A_Str); Space_At  : constant Natural := Index (S (End_A_At + End_A_Str'Length .. S'Last), " "); Count  : constant Natural := Natural'Value (S (End_A_At + End_A_Str'Length .. Space_At - 1)); Language  : constant String  := S (Title_At + Title_Str'Length .. Bracket_At - 2); begin if Bracket_At /= 0 and then End_A_At /= 0 and then Space_At /= 0 then begin Counts.Insert (New_Item => (Count, +Language)); exception when Constraint_Error => Put_Line (Standard_Error, "Warning: repeated language: " & Language); -- Ignore repeated results. null; end; end if; -- Recursively parse the string for languages and counts Find_Counts (S (Space_At + 1 .. S'Last)); end; end if;   end Find_Counts;   Place : Natural := 1;   procedure Display (C : Cursor) is begin Put (Place, Width => 1); Put (". "); Put (Element (C).Count, Width => 1); Put (" - "); Put_Line (To_String (Element (C).Language)); Place := Place + 1; end Display;   Http_Source : constant AWS.Response.Data := AWS.Client.Get ("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); begin Find_Counts (AWS.Response.Message_Body (Http_Source)); Counts.Reverse_Iterate (Display'Access); end Test;  
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#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)) R lst   F decode(lst) V q = ‘’ L(character, count) lst q ‘’= character * count R q   V value = encode(‘aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa’) print(‘Encoded value is ’value.map(v -> String(v[1])‘’v[0])) print(‘Decoded value is ’decode(value))
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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 + 0.05) * sqrt(y + 0.05 * k1) k3 = (t + 0.05) * sqrt(y + 0.05 * k2) k4 = (t + 0.10) * sqrt(y + 0.10 * k3) y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6 } exit(0) }  
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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 := "http://rosettacode.org/mw/api.php?" action := "action=query" format := "format=json" fversion := "formatversion=2" generator := "generator=categorymembers" gcmTitle := "gcmtitle=Category:Language%20users" gcmLimit := "gcmlimit=500" prop := "prop=categoryinfo" rawContinue := "rawcontinue=" page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion, generator, gcmTitle, gcmLimit, prop, rawContinue) resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re.FindAllStringSubmatch(string(body), -1) resp.Body.Close() var results []Result for _, match := range matches { if len(match) == 5 { users, _ := strconv.Atoi(match[4]) if users >= minimum { result := Result{match[1], users} results = append(results, result) } } } sort.Slice(results, func(i, j int) bool { return results[j].users < results[i].users })   fmt.Println("Rank Users Language") fmt.Println("---- ----- --------") rank := 0 lastUsers := 0 lastRank := 0 for i, result := range results { eq := " " rank = i + 1 if lastUsers == result.users { eq = "=" rank = lastRank } else { lastUsers = result.users lastRank = rank } fmt.Printf(" %-2d%s  %3d  %s\n", rank, eq, result.users, result.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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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_decode d n ciphers = map (\c -> mod ( c ^ d ) n ) ciphers   decode :: [Integer] -> String decode encoded = map ( chr . fromInteger ) encoded   divisors :: Integer -> [Integer] divisors n = [m | m <- [1..n] , mod n m == 0 ]   isPrime :: Integer -> Bool isPrime n = divisors n == [1,n]   totient :: Integer -> Integer -> Integer totient prime1 prime2 = (prime1 - 1 ) * ( prime2 - 1 )   myE :: Integer -> Integer myE tot = head [n | n <- [2..tot - 1] , gcd n tot == 1]   myD :: Integer -> Integer -> Integer -> Integer myD e n phi = head [d | d <- [1..n] , mod ( d * e ) phi == 1]   main = do putStrLn "Enter a test text!" text <- getLine let primes = take 90 $ filter isPrime [1..] p1 = last primes p2 = last $ init primes tot = totient p1 p2 e = myE tot n = p1 * p2 rsa_encoded = rsa_encode n e $ encode text d = myD e n tot encrypted = concatMap show rsa_encoded decrypted = decode $ rsa_decode d n rsa_encoded putStrLn ("Encrypted: " ++ encrypted ) putStrLn ("And now decrypted: " ++ decrypted )
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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 highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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)=DT 250 PT=PT+DT 260 IF DT>=15 THEN SA=SA+1 270 NEXT AI 280 IF PT<75 OR SA<2 THEN 140 290 PRINT CHR$(125);"Character Attributes:" 300 PRINT 310 FOR AI=0 TO 5 315 POSITION 10,AI+2 320 PRINT AT$(AI*3+1,AI*3+3);":"; 330 POSITION 16-INT(AT(AI)/10),AI+2 340 PRINT AT(AI) 350 NEXT AI 360 POSITION 8,9 370 PRINT "Total: ";PT 380 PRINT 390 PRINT "Do you accept? "; 400 OPEN #1,4,0,"K:" 410 GET #1,K 420 IF K<>78 AND K<>89 THEN 410 430 PRINT CHR$(K) 440 CLOSE #1 450 IF K=78 THEN 140 460 POSITION 0,13 470 PRINT "Excellent. Good luck on your adventure!"
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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[U32](limit) let sqrtlmt = USize.from[F64](F64.from[U32](limit).sqrt()) _cmpsts = Array[U8].init(0, (_lmt + 8) / 8) // already zeroed; bit array _cmpsts(0)? = 3 // mark 0 and 1 as not prime! if sqrtlmt < 2 then return end for p in Range[USize](2, sqrtlmt + 1) do if (_cmpsts(p >> 3)? and _bitmask(p and 7)?) == 0 then var s = p * p // cull start address for p * p! let slmt = (s + (p << 3)).min(_lmt + 1) while s < slmt do let msk = _bitmask(s and 7)? var c = s >> 3 while c < _cmpsts.size() do _cmpsts(c)? = _cmpsts(c)? or msk c = c + p end s = s + p end end end   fun ref has_next(): Bool val => _ndx < (_lmt + 1)   fun ref next(): U32 ? => _curr = U32.from[USize](_ndx); _ndx = _ndx + 1 while (_ndx <= _lmt) and ((_cmpsts(_ndx >> 3)? and _bitmask(_ndx and 7)?) != 0) do _ndx = _ndx + 1 end _curr   actor Main new create(env: Env) => let limit: U32 = 1_000_000_000 try env.out.write("Primes to 100: ") for p in Primes(100)? do env.out.write(p.string() + " ") end var count: I32 = 0 for p in Primes(1_000_000)? do count = count + 1 end env.out.print("\nThere are " + count.string() + " primes to a million.") let t = Time let start = t.millis() let prms = Primes(limit)? let elpsd = t.millis() - start count = 0 for _ in prms do count = count + 1 end env.out.print("Found " + count.string() + " primes to " + limit.string() + ".") env.out.print("This took " + elpsd.string() + " milliseconds.") end
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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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 = 7.55 }, { name = "Mogadishu", population = 5.85 }, { name = "Khartoum-Omdurman", population = 4.98 }, { name = "Dar Es Salaam", population = 4.7 }, { name = "Alexandria", population = 4.58 }, { name = "Abidjan", population = 4.4 }, { name = "Casablanca", population = 3.98 } ]   val firstCityi = #1 (valOf (List.findi (fn (_, city) => #name(city) = "Dar Es Salaam") citys)) val firstBelow5M = #name (valOf (List.find (fn city => #population(city) < 5.0) citys)) val firstPopA = #population (valOf (List.find (fn city => String.substring (#name(city), 0, 1) = "A") citys))
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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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), Place(name: "Khartoum-Omdurman", population: 4.98), Place(name: "Dar Es Salaam", population: 4.7), Place(name: "Alexandria", population: 4.58), Place(name: "Abidjan", population: 4.4), Place(name: "Casablanca", population: 3.98) ]
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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 environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#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,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#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 print ("unknown error retrieving page") FI; FALSE FI;   MODE LISTOFSTRING = STRUCT(REF LINK first, last, INT upb); MODE LINK = STRUCT(STRING value, REF LINK next);   PRIO LISTINIT = 1; OP LISTINIT = (REF LISTOFSTRING new, REF LINK first)REF LISTOFSTRING: ( new := (first, first, (first IS REF LINK(NIL) | 0 | 1 )); new );   OP +:= = (REF LISTOFSTRING list, []CHAR item)VOID: ( HEAP LINK new := (STRING(item), REF LINK(NIL)); IF first OF list IS REF LINK(NIL) THEN first OF list := new ELSE next OF last OF list := new FI; last OF list := new; upb OF list +:= 1 );   OP UPB = (LISTOFSTRING list)INT: upb OF list;   OP ARRAYOFSTRING = (LISTOFSTRING list)[]STRING:( [UPB list]STRING out; REF LINK this := first OF list; FOR i TO UPB list DO out[i] := value OF this; this := next OF this OD; out );   INT match=0, no match=1, out of memory error=2, other error=3;   PROC re split = (STRING re split, REF STRING beetles)[]STRING:( LISTOFSTRING out := (NIL, NIL, 0); # LISTINIT REF LINK NIL; # INT start := 1, pos, end; WHILE grep in string(re split, beetles[start:], pos, end) = match DO out +:= beetles[start:start+pos-2]; out +:= beetles[start+pos-1:start+end-1]; start +:= end OD; IF start > UPB beetles THEN out +:= beetles[start:] FI; ARRAYOFSTRING(out) );     IF STRING reply; INT rc = http content (reply, "www.rosettacode.org", "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=500", 0); rc /= 0 OR NOT good page (reply) THEN print (("Error:",strerror (rc))) ELSE STRING # hack: HTML should be parsed by an official HTML parsing library # re html tag = "<[^>]*>", re a href category = "^<a href=""/wiki/Category:.*"" title=", re members = "([1-9][0-9]* members)";   MODE STATISTIC = STRUCT(INT members, STRING category); FLEX[0]STATISTIC stats;   OP +:= = (REF FLEX[]STATISTIC in out, STATISTIC item)VOID:( [LWB in out: UPB in out+1]STATISTIC new; new[LWB in out: UPB in out]:=in out; new[UPB new]:=item; in out := new );   # hack: needs to be manually maintained # STRING re ignore ="Programming Tasks|WikiStubs|Maintenance/OmitCategoriesCreated|"+ "Unimplemented tasks by language|Programming Languages|"+ "Solutions by Programming Language|Implementations|"+ "Solutions by Library|Encyclopedia|Language users|"+ "Solutions by Programming Task|Basic language learning|"+ "RCTemplates|Language Implementations";   FORMAT category fmt = $"<a href=""/wiki/Category:"g""" title=""Category:"g""""$; STRING encoded category, category; FORMAT members fmt = $" ("g" members)"$; INT members;   FLEX[0]STRING tokens := re split(re html tag, reply); FOR token index TO UPB tokens DO STRING token := tokens[token index]; FILE file; IF grep in string(re a href category, token, NIL, NIL) = match THEN associate(file, token); make term(file,""""); getf(file, (category fmt, encoded category, category)); close(file) ELIF grep in string(re members, token, NIL, NIL) = match THEN IF grep in string(re ignore, category, NIL, NIL) /= match THEN associate(file, token); getf(file, (members fmt, members)); stats +:= STATISTIC(members, category); close(file) FI FI OD;   OP < = (STATISTIC a,b)BOOL: members OF a < members OF b;   MODE SORTSTRUCT = STATISTIC; PR READ "prelude/sort.a68" PR;   stats := in place shell sort reverse(stats);   INT max = 10; FOR i TO (UPB stats > max | max | UPB stats) DO printf(($g(-0)". "g(-0)" - "gl$,i,stats[i])) OD FI
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#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 terminator? jz finished_Compressing ;if so, exit push di push si mov cx,0FFFFh ;exit after 65536 reps or the run length ends. xchg di,si ;scasb only works with es:di so we need to exchange repz scasb ;repeat until [es:di] != AL xchg di,si ;exchange back pop dx ;pop the old SI into DX instead! pop di   push si sub si,dx mov dx,si pop si ;now the run length is in dx, store it into output ram.   push ax mov al,dl stosb pop ax stosb ;store the letter that corresponds to the run     dec si ;we're off by one, so we need to correct for that. jmp compressRLE ;back to start   finished_Compressing:     mov bp, offset OutputRam mov bx, 32 call doMemDump ;displays a hexdump of the contents of OutputRam       mov ax,4C00h int 21h ;exit DOS     TestString byte "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",0   OutputRam byte 256 dup (0)   end start
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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) * sqr(y + 0.10 * k3) y = y + 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6 next i end
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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; }   double rate(double x, double y) { return x * sqrt(y); }   int main(void) { double *y, x, y2; double x0 = 0, x1 = 10, dx = .1; int i, n = 1 + (x1 - x0)/dx; y = (double *)malloc(sizeof(double) * n);   for (y[0] = 1, i = 1; i < n; i++) y[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]);   printf("x\ty\trel. err.\n------------\n"); for (i = 0; i < n; i += 10) { x = x0 + dx * i; y2 = pow(x * x / 4 + 1, 2); printf("%g\t%g\t%g\n", x, y[i], y[i]/y2 - 1); }   return 0; }
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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", "gcmlimit" => "999", "prop" => "categoryinfo", "rawcontinue" => "", ]   function mediawikiquery(site = URI, params = PARAMS, mintoshow = 100) langusers = Dict{String, Int}() url = site * "/api.php?" * join(map(x -> x[1] * "=" * x[2], params), "&") r = HTTP.get(url) data = JSON3.read(String(r.body)) for page in data["query"]["pages"] lang = occursin("User", page["title"]) ? split(page["title"], r"\:|\sUser")[2] : page["title"] if haskey(page, "categoryinfo") langusers[lang] = page["categoryinfo"]["size"] else langusers[lang] = 0 end end for (i, p) in enumerate(sort!([lp for lp in langusers], lt = (x, y) -> x[2] > y[2])) last(p) >= mintoshow && println(lpad(i, 2), " ", rpad(first(p), 30), last(p)) end end   mediawikiquery()  
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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/mw/api.php?" & [Action, Format, Formatversion, Generator, GcmTitle, GcmLimit, Prop].join("&")   type Counts = tuple[lang: string, count: int]   proc cmp(a, b: Counts): int = ## Compare two count tuples. Place the one with greater count field first and when ## count fields are equal, place the one with the first name in alphabetic order. result = cmp(b.count, a.count) if result == 0: result = cmp(a.lang, b.lang)   var client = newHttpClient() var counts: seq[Counts] var url = Page   while true:   # Access to the page and load the JSON representation. let response = client.get(url) if response.status != $Http200: break let root = response.body.parseJson()   # Extract language names and number of users. for node in root{"query", "pages"}: var lang: string if node["title"].getStr().scanf("Category:$+ User", lang): let count = node{"categoryinfo", "size"}.getInt() counts.add (lang, count) if "continue" notin root: break   # Load continuation page. let gcmcont = root{"continue", "gcmcontinue"}.getStr() let cont = root{"continue", "continue"}.getStr() url = Page & fmt"&gcmcontinue={gcmcont}&continue={cont}"   # Sort and display. counts.sort(cmp) var rank, lastCount = 0 for i, (lang, count) in counts: if count != lastCount: rank = i + 1 lastCount = count echo &"{rank:3} {count:4} - {lang}"
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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 '&', map { $_ . '=' . uri_escape($fields{$_}) } keys %fields }   sub mediawiki_query { my($site, $type, %query) = @_; my $url = "$site/api.php?" . uri_query_string(%query); my %languages = ();   my $req = HTTP::Request->new( GET => $url ); my $response = $client->request($req); $response->is_success or die "Failed to GET '$url': ", $response->status_line; my $data = decode_json($response->content); for my $row ( @{${$data}{query}{pages}} ) { next unless defined $$row{categoryinfo} && $$row{title} =~ /User/; my($title) = $$row{title} =~ /Category:(.*?) User/; my($count) = $$row{categoryinfo}{pages}; $languages{$title} = $count; } %languages; }   my %table = mediawiki_query( $url, 'pages', ( generator => 'categorymembers', gcmtitle => 'Category:Language users', gcmlimit => '999', prop => 'categoryinfo', rawcontinue => '', ) );   for my $k (sort { $table{$b} <=> $table{$a} } keys %table) { printf "%4d %s\n", $table{$k}, $k if $table{$k} > $minimum; }
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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#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 Res } tabs(n){ loop, % n Res .= "`t" return Res }
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’, ‘cobol’, ‘cpp’, ‘cpp-qt’, ‘csharp’, ‘css’, ‘d’, ‘delphi’, ‘diff’, ‘_div’, ‘dos’, ‘dot’, ‘eiffel’, ‘email’, ‘foo’, ‘fortran’, ‘freebasic’, ‘genero’, ‘gettext’, ‘glsl’, ‘gml’, ‘gnuplot’, ‘go’, ‘groovy’, ‘haskell’, ‘hq9plus’, ‘html4strict’, ‘idl’, ‘ini’, ‘inno’, ‘intercal’, ‘io’, ‘java’, ‘java5’, ‘javascript’, ‘kixtart’, ‘klonec’, ‘klonecpp’, ‘latex’, ‘lisp’, ‘lolcode’, ‘lotusformulas’, ‘lotusscript’, ‘lscript’, ‘lua’, ‘m68k’, ‘make’, ‘matlab’, ‘mirc’, ‘modula3’, ‘mpasm’, ‘mxml’, ‘mysql’, ‘nsis’, ‘objc’, ‘ocaml’, ‘ocaml-brief’, ‘oobas’, ‘oracle11’, ‘oracle8’, ‘pascal’, ‘per’, ‘perl’, ‘php’, ‘php-brief’, ‘pic16’, ‘pixelbender’, ‘plsql’, ‘povray’, ‘powershell’, ‘progress’, ‘prolog’, ‘providex’, ‘python’, ‘qbasic’, ‘rails’, ‘reg’, ‘robots’, ‘ruby’, ‘sas’, ‘scala’, ‘scheme’, ‘scilab’, ‘sdlbasic’, ‘smalltalk’, ‘smarty’, ‘sql’, ‘tcl’, ‘teraterm’, ‘text’, ‘thinbasic’, ‘tsql’, ‘typoscript’, ‘vb’, ‘vbnet’, ‘verilog’, ‘vhdl’, ‘vim’, ‘visualfoxpro’, ‘visualprolog’, ‘whitespace’, ‘winbatch’, ‘xml’, ‘xorg_conf’, ‘xpp’, ‘z80’]   V text = ‘Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel</bar>. Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>. Eam volumus perpetua constituto id, mea an omittam fierent vituperatoribus.’   L(lang) languages text = text.replace(‘<’lang‘>’, ‘<lang ’lang‘>’) text = text.replace(‘</’lang‘>’, ‘</’""‘lang>’) text = text.replace(‘<code ’lang‘>’, ‘<lang ’lang‘>’) text = text.replace(‘</code>’, ‘</’""‘lang>’)   print(text)
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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 Code", "Hello Word!", "This message is too long.", repl("x",*decode(n+1))] do { write("\nMessage = ",image(m)) write( "Encoded = ",m := encode(m)) if m := rsa(m,e,n) then { # unblocked write( "Encrypt = ",m) write( "Decrypt = ",m := rsa(m,d,n)) } else { # blocked every put(C := [], rsa(!block(m,b),e,n)) writes("Encrypt = ") ; every writes(!C," ") ; write() every put(P := [], rsa(!C,d,n)) writes("Decrypt = ") ; every writes(!P," ") ; write() write("Unblocked = ",m := unblock(P,b)) } write( "Decoded = ",image(decode(m))) } end   procedure mod_power(base, exponent, modulus) # fast modular exponentation result := 1 while exponent > 0 do { if exponent % 2 = 1 then result := (result * base) % modulus exponent /:= 2 base := base ^ 2 % modulus } return result end   procedure rsa(text,e,n) # return rsa encryption of numerically encoded message; fail if text < n return mod_power(text,e,text < n) end   procedure encode(text) # numerically encode ascii text as int every (message := 0) := ord(!text) + 256 * message return message end   procedure decode(message) # numerically decode int to ascii text text := "" while text ||:= char((0 < message) % 256) do message /:= 256 return reverse(text) end   procedure block(m,b) # break lg int into blocks of size b M := [] while push(M, x := (0 < m) % b) do m /:= b return M end   procedure unblock(M,b) # reassemble blocks of size b into lg int every (m := 0) := !M + b * m return m end
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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() return a + b + c + d - min(min(a, b), min(c, d)) end function   arraybase 1 dim statnames$ = {"STR", "CON", "DEX", "INT", "WIS", "CHA"} dim stat(6) acceptable = false   do sum = 0 : n15 = 0 for i = 1 to 6 stat[i] = roll_stat() sum += stat[i] if stat[i] >= 15 then n15 += 1 next i if sum >= 75 and n15 >= 2 then acceptable = true until acceptable   for i = 1 to 6 print statnames$[i]; ": "; stat[i] next i print "-------" print "TOT: "; sum end
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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-Omdurman" population 4.98 } { name "Dar Es Salaam" population 4.7 } { name "Alexandria" population 4.58 } { name "Abidjan" population 4.4 } { name "Casablanca" population 3.98 } }   # Tcl's version of "higher order programming" is a bit unusual. Instead of passing lambda # functions, it is often easier to pass script fragments. This command takes two such # arguments: $test is an expression (as understood by [expr]), and $action is a script. # thanks to [dict with], both $test and $action can refer to the fields of the current # record by name - or to other variables used in the proc, like $index or $record. proc search {records test action} { set index 0 foreach record $records { dict with record {} if $test $action incr index } error "No match found!" }   # Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" puts [search $records {$name eq "Dar Es Salaam"} {return $index}] # Find the name of the first city in this list whose population is less than 5 million puts [search $records {$population < 5.0} {return $name}] # Find the population of the first city in this list whose name starts with the letter "A" puts [search $records {[string match A* $name]} {return $population}]  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#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(_, [], _) -> undefined; pos(Needle, [Needle|_], Pos) -> Pos; pos(Needle, [_|Haystack], Pos) -> pos(Needle, Haystack, Pos+1).   print({Needle, undefined}) -> io:format("~s is not in haystack.~n",[Needle]); print({Needle, Pos}) -> io:format("~s at position ~p.~n",[Needle,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,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#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 WebRequest.Open("GET", ValidUrl),WebRequest.Send() ValidPage := WebRequest.ResponseText   ; Replace special characters StringReplace, MembsPage, MembsPage, ΜC++, µC++, All StringReplace, MembsPage, MembsPage, МК-61/52, MK-61/52, All StringReplace, ValidPage, ValidPage, ΜC++, µC++, All StringReplace, ValidPage, ValidPage, МК-61/52, MK-61/52, All   ValidREx := "s)href=""([^""]+)"" title=""Category:([^""]+)"">(?=.*</table>)" MembsREx := "title=""Category:(.+?)"">.+?\((\d+) members?\)"   ; Iterate through all matches for valid languages ValidLangs := [], FoundPos := 0 While FoundPos := RegExMatch(ValidPage, ValidREx, Match, FoundPos+1) ValidLangs[Match2] := Match1   ; Iterate through all matches for categories with members MembsLangs := [], Dupes := [], Detected := 0, FoundPos := 0 While FoundPos := RegExMatch(MembsPage, MembsREx, Match, FoundPos+1) { ; If it isn't a valid language or is a duplicate, skip it if !ValidLangs.HasKey(Match1) || Dupes.HasKey(Match1) continue   Dupes.Insert(Match1, true) Detected++   ; Initialize this member count if !IsObject(MembsLangs[Match2]) MembsLangs[Match2] := [Match1] else MembsLangs[Match2].Insert(Match1) }   ; Sort the languages with the highest member count first Sorted := [] for Members, Languages in MembsLangs Sorted.Insert(1, [Members, Languages])   ; Initialize the GUI Gui, New, HwndGuiHwnd Gui, Add, Text, w300 Center, %Detected% languages detected Gui, Add, Edit, w300 vSearchText gSearch, Filter languages Gui, Add, ListView, w300 r20 Grid gOpen vMyListView, Rank|Members|Category   ; Populate the list view LV_ModifyCol(1, "Integer"), LV_ModifyCol(2, "Integer"), LV_ModifyCol(3, 186) for Rank, Languages in Sorted for Key, Language in Languages[2] LV_Add("", Rank, Languages[1], Language)   Gui, Show,, Rosetta Code return   Open: if (A_GuiEvent == "DoubleClick") { LV_GetText(Language, A_EventInfo, 3) Run, % "http://rosettacode.org" ValidLangs[Language] } return   Search: GuiControlGet, SearchText GuiControl, -Redraw, MyListView   LV_Delete() for Rank, Languages in Sorted for Key, Language in Languages[2] if InStr(Language, SearchText) LV_Add("", Rank, Languages[1], Language)   GuiControl, +Redraw, MyListView return   GuiClose: ExitApp return
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#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(len)=s(pos^) pos^==+1 IF s(pos^)<'0 OR s(pos^)>'9 THEN EXIT FI OD tmp(0)=len num=ValB(tmp) RETURN (num)   PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN len=255-text(0) FI IF len THEN srcPtr=suffix+1 dstPtr=text+text(0)+1 MoveBlock(dstPtr,srcPtr,len) text(0)==+suffix(0) FI RETURN   PROC Encode(CHAR ARRAY in,out) BYTE pos,len CHAR ARRAY tmp(5)   pos=1 len=0 out(0)=0 WHILE pos<=in(0) DO len=GetLength(in,pos) StrB(len,tmp) Append(out,tmp) out(0)==+1 out(out(0))=in(pos) pos==+len OD RETURN   PROC Decode(CHAR ARRAY in,out) BYTE pos,num,i CHAR c   pos=1 out(0)=0 WHILE pos<=in(0) DO num=GetNumber(in,@pos) c=in(pos) pos==+1 FOR i=1 TO num DO out(0)==+1 out(out(0))=c OD OD RETURN   PROC Main() CHAR ARRAY data="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" CHAR ARRAY encoded(256),decoded(256)   PrintE("original:") PrintE(data) PutE()   Encode(data,encoded) PrintE("encoded:") PrintE(encoded) PutE()   Decode(encoded,decoded) PrintE("decoded:") PrintE(decoded) RETURN
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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 the arrays int n = (int)(((T - t) / dt)) + 1;   // Initialize the arrays for the time index 's' and estimates 'y' at each index 'i' double[] y = new double[n]; double[] s = new double[n];   // RK4 Variables double dy1; double dy2; double dy3; double dy4;   // RK4 Initializations int i = 0; s[i] = 0.0; y[i] = 1.0;   Console.WriteLine(" ===================================== "); Console.WriteLine(" Beging 4th Order Runge Kutta Method "); Console.WriteLine(" ===================================== ");   Console.WriteLine(); Console.WriteLine(" Given the example Differential equation: \n"); Console.WriteLine(" y' = t*sqrt(y) \n"); Console.WriteLine(" With the initial conditions: \n"); Console.WriteLine(" t0 = 0" + ", y(0) = 1.0 \n"); Console.WriteLine(" Whose exact solution is known to be: \n"); Console.WriteLine(" y(t) = 1/16*(t^2 + 4)^2 \n"); Console.WriteLine(" Solve the given equations over the range t = 0...10 with a step value dt = 0.1 \n"); Console.WriteLine(" Print the calculated values of y at whole numbered t's (0.0,1.0,...10.0) along with the error \n"); Console.WriteLine();   Console.WriteLine(" y(t) " +"RK4" + " ".PadRight(18) + "Absolute Error"); Console.WriteLine(" -------------------------------------------------"); Console.WriteLine(" y(0) " + y[i] + " ".PadRight(20) + (y[i] - solution(s[i])));   // Iterate and implement the Rk4 Algorithm while (i < y.Length - 1) {   dy1 = dt * equation(s[i], y[i]); dy2 = dt * equation(s[i] + dt / 2, y[i] + dy1 / 2); dy3 = dt * equation(s[i] + dt / 2, y[i] + dy2 / 2); dy4 = dt * equation(s[i] + dt, y[i] + dy3);   s[i + 1] = s[i] + dt; y[i + 1] = y[i] + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6;   double error = Math.Abs(y[i + 1] - solution(s[i + 1])); double t_rounded = Math.Round(t + dt, 2);   if (t_rounded % 1 == 0) { Console.WriteLine(" y(" + t_rounded + ")" + " " + y[i + 1] + " ".PadRight(5) + (error)); }   i++; t += dt;   };//End Rk4   Console.ReadLine(); }   // Differential Equation public static double equation(double t, double y) { double y_prime; return y_prime = t*Math.Sqrt(y); }   // Exact Solution public static double solution(double t) { double actual; actual = Math.Pow((Math.Pow(t, 2) + 4), 2)/16; return actual; } } }
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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: 59 - Common Lisp 20: 58 - AWK
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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:Language users", "gcmlimit": 500, "prop": "categoryinfo", }     def fetch_data(): counts = {} continue_ = {"continue": ""}   # Keep making HTTP requests to the MediaWiki API if more records are # available. while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status()   data = resp.json()   # Grab the title (language) and size (count) only. counts.update( { p["title"]: p.get("categoryinfo", {}).get("size", 0) for p in data["query"]["pages"] } )   continue_ = data.get("continue", {})   return counts     if __name__ == "__main__": # Request data from the MediaWiki API. counts = fetch_data()   # Filter out languages that have less than 100 users. at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]   # Sort languages by number of users top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)   # Pretty print for i, lang in enumerate(top_languages): print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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) (Function 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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#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, char **e) { expr ex = calloc(sizeof(s_expr), 1); char buf[256] = {0}; int i = 0;   while (*s) { if (i >= 256) { fprintf(stderr, "string too long:\n"); whine(s); goto fail; } switch (*s) { case '\\': switch (*++s) { case '\\': case '"': buf[i++] = *s++; continue;   default: whine(s); goto fail; } case '"': goto success; default: buf[i++] = *s++; } } fail: free(ex); return 0;   success: *(const char **)e = s + 1; ex->type = S_STRING; ex->buf = strdup(buf); ex->len = strlen(buf); return ex; }   expr parse_symbol(const char *s, char **e) { expr ex = calloc(sizeof(s_expr), 1); char buf[256] = {0}; int i = 0;   while (*s) { if (i >= 256) { fprintf(stderr, "symbol too long:\n"); whine(s); goto fail; } if (isspace(*s)) goto success; if (*s == ')' || *s == '(') { s--; goto success; }   switch (*s) { case '\\': switch (*++s) { case '\\': case '"': case '(': case ')': buf[i++] = *s++; continue; default: whine(s); goto fail; } case '"': whine(s); goto success; default: buf[i++] = *s++; } } fail: free(ex); return 0;   success: *(const char **)e = s + 1; ex->type = S_SYMBOL; ex->buf = strdup(buf); ex->len = strlen(buf); return ex; }   void append(expr list, expr ele) { list->buf = realloc(list->buf, sizeof(expr) * ++list->len); ((expr*)(list->buf))[list->len - 1] = ele; }   expr parse_list(const char *s, char **e) { expr ex = calloc(sizeof(s_expr), 1), chld; char *next;   ex->len = 0;   while (*s) { if (isspace(*s)) { s++; continue; }   switch (*s) { case '"': chld = parse_string(s+1, &next); if (!chld) goto fail; append(ex, chld); s = next; continue; case '(': chld = parse_list(s+1, &next); if (!chld) goto fail; append(ex, chld); s = next; continue; case ')': goto success;   default: chld = parse_symbol(s, &next); if (!chld) goto fail; append(ex, chld); s = next; continue; } }   fail: whine(s); free(ex); return 0;   success: *(const char **)e = s+1; ex->type = S_LIST; return ex; }   expr parse_term(const char *s, char **e) { while (*s) { if (isspace(*s)) { s++; continue; } switch(*s) { case '(': return parse_list(s+1, e); case '"': return parse_string(s+1, e); default: return parse_symbol(s+1, e); } } return 0; }   void print_expr(expr e, int depth) { #define sep() for(i = 0; i < depth; i++) printf(" ") int i; if (!e) return;     switch(e->type) { case S_LIST: sep(); puts("("); for (i = 0; i < e->len; i++) print_expr(((expr*)e->buf)[i], depth + 1); sep(); puts(")"); return; case S_SYMBOL: case S_STRING: sep(); if (e->type == S_STRING) putchar('"'); for (i = 0; i < e->len; i++) { switch(((char*)e->buf)[i]) { case '"': case '\\': putchar('\\'); break; case ')': case '(': if (e->type == S_SYMBOL) putchar('\\'); }   putchar(((char*)e->buf)[i]); } if (e->type == S_STRING) putchar('"'); putchar('\n'); return; } }   int main() { char *next; const char *in = "((data da\\(\\)ta \"quot\\\\ed data\" 123 4.5)\n" " (\"data\" (!@# (4.5) \"(mo\\\"re\" \"data)\")))";   expr x = parse_term(in, &next);   printf("input is:\n%s\n", in); printf("parsed as:\n"); print_expr(x, 0); return 0; }
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) text := RegExReplace(text, "<code (.+?)>(.*?)</code>" , "<lang $1>$2" . slang) } FileAppend, % text, %2%  
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 freebasic genero gettext glsl gml gnuplot groovy haskell hq9plus html4strict idl ini inno intercal io java java5 javascript kixtart klonec klonecpp latex lisp lolcode lotusformulas lotusscript lscript lua m68k make matlab mirc modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray powershell progress prolog providex python qbasic rails reg robots ruby sas scala scheme scilab sdlbasic smalltalk smarty sql tcl teraterm text thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro visualprolog whitespace winbatch xml xorg_conf xpp z80".split;   string fixTags(string text) { static immutable slang = "/lang"; static immutable code = "code";   foreach (immutable lang; langs) { text = text.replace("<%s>".format(lang), "<lang %s>".format(lang)); text = text.replace("</%s>".format(lang), "<%s>".format(slang)); }   return text.replace("<%s (.+?)>(.*?)</%s>" .format(code, code).regex("g"), "<lang $1>$2<%s>".format(slang)); }   void main() { ("lorem ipsum <c>some c code</c>dolor sit amet, <csharp>some " ~ "csharp code</csharp> consectetur adipisicing elit, <code r>" ~ " some r code </code>sed do eiusmod tempor incididunt") .fixTags .writeln; }
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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 916709442744356653386978770799029131264344 ] dec=: N&|@^&D enc 25512506514985639724585018469 ] final=: a. {~ 256x #.inv dec Rosetta Code
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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 than the above will fail) */ BigInteger n = new BigInteger("9516311845790656153499716760847001433441357"); BigInteger e = new BigInteger("65537"); BigInteger d = new BigInteger("5617843187844953170308463622230283376298685"); Charset c = Charsets.UTF_8; String plainText = "Rosetta Code"; System.out.println("PlainText : " + plainText); byte[] bytes = plainText.getBytes(); BigInteger plainNum = new BigInteger(bytes); System.out.println("As number : " + plainNum); BigInteger Bytes = new BigInteger(bytes); if (Bytes.compareTo(n) == 1) { System.out.println("Plaintext is too long"); return; } BigInteger enc = plainNum.modPow(e, n); System.out.println("Encoded: " + enc); BigInteger dec = enc.modPow(d, n); System.out.println("Decoded: " + dec); String decText = new String(dec.toByteArray(), c); System.out.println("As text: " + decText); }  
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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 (i = 0; i < 6; ++i) { for (j = 0; j < 4; ++j) { numbers[j] = 1 + rand() % 6; } qsort(numbers, 4, sizeof(int), compareInts); nsum = 0; for (j = 1; j < 4; ++j) { nsum += numbers[j]; } values[i] = nsum; vsum += values[i]; } if (vsum < 75) continue; vcount = 0; for (j = 0; j < 6; ++j) { if (values[j] >= 15) vcount++; } if (vcount < 2) continue; printf("The 6 random numbers generated are:\n"); printf("["); for (j = 0; j < 6; ++j) printf("%d ", values[j]); printf("\b]\n"); printf("\nTheir sum is %d and %d of them are >= 15\n", vsum, vcount); break; } return 0; }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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"])   var cities = [ City.new("Lagos", 21.0), City.new("Cairo", 15.2), City.new("Kinshasa-Brazzaville", 11.3), City.new("Greater Johannesburg", 7.55), City.new("Mogadishu", 5.85), City.new("Khartoum-Omdurman", 4.98), City.new("Dar Es Salaam", 4.7), City.new("Alexandria", 4.58), City.new("Abidjan", 4.4), City.new("Casablanca", 3.98) ]   var index = findFirst.call(cities) { |c| c.name == "Dar Es Salaam" }.index System.print("Index of the first city whose name is 'Dar Es Salaam' is %(index).") var city = findFirst.call(cities) { |c| c.pop < 5 }.record.name System.print("First city whose population is less than 5 million is %(city).") var pop = findFirst.call(cities) { |c| c.name[0] == "A" }.record.pop System.print("The population of the first city whose name begins with 'A' is %(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 the haystack. See also Search a list of records
#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", "more hay", "needle", "a cow", "farmer", "needle", "dirt"} sequence haystack3 = {"needle"} sequence haystack4 = {"no", "need le s", "in", "this", "haystack"} sequence haystack5 = {"knee", "needle", "dull", "needle"} sequence haystack6 = {}   --search procedure with console output procedure haystackSearch(sequence hStack) sequence foundNeedles = find_all(searchStr1, hStack) puts(1,"---------------------------------\r\n") if object(foundNeedles) and length(foundNeedles) > 0 then printf(1, "First needle found at index %d \r\n", foundNeedles[1])   if length(foundNeedles) > 1 then printf(1, "Last needle found at index %d \r\n", foundNeedles[length(foundNeedles)] )   for i = 1 to length(foundNeedles) do printf(1, "Needle #%d ", i) printf(1, "was at index %d .\r\n", foundNeedles[i]) end for   else puts(1, "There was only one needle found in this haystack. \r\n") end if   else puts(1, "Simulated exception - No needles found in this haystack.\r\n") end if   end procedure   --runs the procedure on all haystacks haystackSearch(haystack1) haystackSearch(haystack2) haystackSearch(haystack3) haystackSearch(haystack4) haystackSearch(haystack5) haystackSearch(haystack6) --wait for user to press a key to exit any_key()  
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#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( site,path,server,j,output) {   RS = ORS = "\r\n"   site = "rosettacode.org" path = "/mw/api.php" \ "?action=query" \ "&generator=categorymembers" \ "&gcmtitle=Category:Programming%20Languages" \ "&gcmlimit=500" \ (gcmcontinue "" ? "&gcmcontinue=" gcmcontinue : "") \ "&prop=categoryinfo" \ "&format=txt"   server = "/inet/tcp/0/" site "/80" print "GET " path " HTTP/1.0" |& server print "Host: " site |& server print "" |& server while ((server |& getline) > 0) { if($0 != 0) { j++ output[j] = $0 } } close(server) if(length(output) == 0) return -1 else return join(output, 1, j, "\n") }   function parse(webpage ,c,a,i,b,e,pages) {   # Check for API continue code ie. a new page of results available match(webpage, "gcmcontinue[]] =>[^)]+[^)]", a) if(a[0] != "") { split(a[0], b, ">") gcmcontinue = trim(b[2]) } else gcmcontinue = ""   c = split(webpage, a, "[[][0-9]{1,7}[]]")   while(i++ < c) { if(match(a[i], /[pages]/)) { match(a[i], "pages[]] =>[^[]+[^[]", b) split(b[0], e, ">") pages = trim(e[2]) + 0 } else pages = 0 if(match(a[i], /[title]/)) { match(a[i], "title[]] =>[^[]+[^[]", b) split(b[0], e, ":") e[2] = trim(e[2]) if ( substr(e[2], length(e[2]), 1) == ")" ) e[2] = trim( substr(e[2], 1, length(e[2]) - 1) ) if(length(e[2]) > 0) G[e[2]] = pages } } }   BEGIN {   parse( http2var() ) # First 500 while ( gcmcontinue != "" ) parse( http2var() ) # Next 500, etc   # https://www.gnu.org/software/gawk/manual/html_node/Controlling-Scanning.html PROCINFO["sorted_in"] = "@val_type_desc" for ( language in G ) print ++i ". " language " - " G[language]   }
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#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'First); Index : Integer := Data'First + 1; begin while Index <= Data'Last and then Code = Data (Index) loop Index := Index + 1; end loop; declare Prefix : constant String := Integer'Image (Index - Data'First); begin return Prefix (2..Prefix'Last) & Code & Encode (Data (Index..Data'Last)); end; end; end if; end Encode; function Decode (Data : String) return String is begin if Data'Length = 0 then return ""; else declare Index : Integer := Data'First; Count : Natural := 0; begin while Index < Data'Last and then Data (Index) in '0'..'9' loop Count := Count * 10 + Character'Pos (Data (Index)) - Character'Pos ('0'); Index := Index + 1; end loop; if Index > Data'First then return Count * Data (Index) & Decode (Data (Index + 1..Data'Last)); else return Data; end if; end; end if; end Decode; begin Put_Line (Encode ("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); Put_Line (Decode ("12W1B12W3B24W1B14W")); end Test_Run_Length_Encoding;
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#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 ) }, dy3 { dt * f( t+dt/2, y+dy2/2 ) }, dy4 { dt * f( t+dt , y+dy3 ) }; return ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6; }; }   int main(void) { constexpr double TIME_MAXIMUM { 10.0 }, T_START { 0.0 }, Y_START { 1.0 }, DT { 0.1 }, WHOLE_TOLERANCE { 1e-12 };   auto dy = rk4( [](double t, double y) -> double { return t*sqrt(y); } ) ;   for ( auto y { Y_START }, t { T_START }; t <= TIME_MAXIMUM; y += dy(t,y,DT), t += DT ) if (ceilf(t)-t < WHOLE_TOLERANCE) printf("y(%4.1f)\t=%12.6f \t error: %12.6e\n", t, y, std::fabs(y - pow(t*t+4,2)/16));   return 0; }
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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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-complete-url gcmcontinue) (struct-copy url api-url [query `([format . "json"] [action . "query"] [generator . "categorymembers"] [gcmtitle . ,category] [gcmlimit . "200"] [gcmcontinue . ,gcmcontinue] [continue . ""] [prop . "categoryinfo"])]))   (define @ hash-ref)   (define table (make-hash))   (let loop ([gcmcontinue ""]) (define resp (read-json (get-pure-port (make-complete-url gcmcontinue)))) (hash-union! table (for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))]) (values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0)))) (cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))   (for/fold ([prev #f] [rank #f] #:result (void)) ([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)]) (match-define (cons cat size) item) (define this-rank (if (equal? prev size) rank (add1 i))) (printf "Rank: ~a ~a ~a\n" (~a this-rank #:align 'right #:min-width 2) (~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14) (replacer cat)) (values size this-rank))
http://rosettacode.org/wiki/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: https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. In order to find the list of such categories,   it's possible to first parse the entries of: http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. Then download and parse each computer language   users   category to find the number of users of that computer language. Sample output on 18 February 2019: Language Users -------------------------- C 391 Java 276 C++ 275 Python 262 JavaScript 238 Perl 171 PHP 167 SQL 138 UNIX Shell 131 BASIC 120 C sharp 118 Pascal 116 Haskell 102 A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.
#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-query( $url, 'pages', :generator<categorymembers>, :gcmtitle<Category:Language users>, :gcmlimit<350>, :rawcontinue(), :prop<categoryinfo> )   .map({ %( count => .<categoryinfo><pages> || 0, lang => .<title>.subst(/^'Category:' (.+) ' User'/, ->$/ {$0}) ) })   .sort( { -.<count>, .<lang> } )   .map( { last if .<count> < $minimum; display(.<count>, .<lang>) } );   say "========= elapsed: {(now - $start-time).round(.01)} seconds =========";   sub display ($count, $which) { if $last != $count { $last = $count; $rank = $lang; $tie = ' ' } else { $tie = 'T' }; sprintf "#%3d Rank: %2d %s with %-4s users:  %s", $lang++, $rank, $tie, $count, $which; }   sub mediawiki-query ($site, $type, *%query) { my $url = "$site/api.php?" ~ uri-query-string( :action<query>, :format<json>, :formatversion<2>, |%query); my $continue = '';   gather loop { my $response = $client.get("$url&$continue"); my $data = from-json($response.content); take $_ for $data.<query>.{$type}.values; $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last); } }   sub uri-query-string (*%fields) { join '&', %fields.map: { "{.key}={uri-escape .value}" } }
http://rosettacode.org/wiki/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 Eval. Dynamic variable names is a similar task.
#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 Eval. Dynamic variable names is a similar task.
#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). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#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 = new List<SNode>(); } public SNode(string name):this() { this.Name=name; } public void AddNode(SNode node) { this._items.Add(node); } }   public class SNodeFull : SNode { private bool _isLeaf; public bool IsLeaf { get => _isLeaf; } public SNodeFull(bool isLeaf) : base() { this._isLeaf = isLeaf; }   public SNodeFull(string name, bool isLeaf) : base(name) { this._isLeaf = isLeaf; }   public SNodeFull RootNode { get; set; }   public void AddNode(SNodeFull node) { base.AddNode(node); node.RootNode = this; } }    
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', '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', 'go', 'groovy', 'haskell', 'hq9plus', 'html4strict', 'idl', 'ini', 'inno', 'intercal', 'io', 'java', 'java5', 'javascript', 'kixtart', 'klonec', 'klonecpp', 'latex', 'lisp', 'lolcode', 'lotusformulas', 'lotusscript', 'lscript', 'lua', 'm68k', 'make', 'matlab', 'mirc', 'modula3', 'mpasm', 'mxml', 'mysql', 'nsis', 'objc', 'ocaml', 'ocaml-brief', 'oobas', 'oracle11', 'oracle8', 'pascal', 'per', 'perl', 'php', 'php-brief', 'pic16', 'pixelbender', 'plsql', 'povray', 'powershell', 'progress', 'prolog', 'providex', 'python', 'qbasic', 'rails', 'reg', 'robots', 'ruby', 'sas', 'scala', 'scheme', 'scilab', 'sdlbasic', 'smalltalk', 'smarty', 'sql', 'tcl', 'teraterm', 'text', 'thinbasic', 'tsql', 'typoscript', 'vb', 'vbnet', 'verilog', 'vhdl', 'vim', 'visualfoxpro', 'visualprolog', 'whitespace', 'winbatch', 'xml', 'xorg_conf', 'xpp', 'z80'];   procedure repl(const Match: TMatch; var code: ansistring);   procedure replace(_new: ansistring); begin code := StringReplace(code, Match.Value, '<' + _new + '>', [rfReplaceAll]); end;   begin if Match.Value = '/code' then begin replace('/lang'); exit; end;   if Match.Value = '</code>' then begin replace('/lang'); exit; end;   var mid := Lowercase(Trim(copy(Match.Value, 2, length(Match.Value) - 2)));   for var lg in LANGS do begin if mid = lg then begin replace(format('lang %s', [lg])); exit; end;   if mid[1] = '/' then begin replace('/lang'); exit; end;   if (pos('code', mid) = 1) and (copy(mid, 6, length(mid) - 2) = lg) then begin replace(format('lang %s', [lg])); exit; end; end; end;   function Lang(input: ansistring): ansistring; var reg: Tregex; match: TMatch; begin reg := TRegex.Create('<[^>]+>'); Result := input; for match in reg.Matches(input) do Repl(match, Result); end;   function ReadAll: Ansistring; var Buffer: array[0..1000] of byte; StdIn: TStream; Count: Integer; buf: Ansistring; begin StdIn := THandleStream.Create(GetStdHandle(STD_INPUT_HANDLE)); Result := ''; while True do begin Count := StdIn.Read(Buffer, 1000); if Count = 0 then Break; SetLength(buf, Count); CopyMemory(@buf[1], @Buffer[0], Count); Result := Result + buf; end; StdIn.Free; end;   procedure Fix(); var input, output: ansistring; begin input := ReadAll; output := Lang(input); writeln(output); end;   begin Fix; end.
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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 join(Char.(hex2bytes(hex(decoded)))) end   msg = "Rosetta Code." nmod = big"9516311845790656153499716760847001433441357" expub = 65537 dsecr = big"5617843187844953170308463622230283376298685"   encoded = rsaencode(msg, nmod, expub) decoded = rsadecode(encoded, nmod, dsecr) println("\n# $msg\n -> ENCODED: $encoded\n -> DECODED: $decoded")
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 number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#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" println("PlainText : $plainText") val bytes = plainText.toByteArray(c) val plainNum = BigInteger(bytes) println("As number : $plainNum") if (plainNum > n) { println("Plaintext is too long") return }   val enc = plainNum.modPow(e, n) println("Encoded  : $enc")   val dec = enc.modPow(d, n) println("Decoded  : $dec")   val decText = dec.toByteArray().toString(c) println("As text  : $decText") }
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#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; }   static List<int> getSix() { List<int> g6 = new List<int>(); for (int i = 0; i < 6; i++) g6.Add(getThree(6).Sum()); return g6; }   static void Main(string[] args) { bool good = false; do { List<int> gs = getSix(); int gss = gs.Sum(); int hvc = gs.FindAll(x => x > 14).Count; Console.Write("attribs: {0}, sum={1}, ({2} sum, high vals={3})", string.Join(", ", gs), gss, gss >= 75 ? "good" : "low", hvc); Console.WriteLine(" - {0}", (good = gs.Sum() >= 75 && hvc > 1) ? "success" : "failure"); } while (!good); } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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); } }   void draw() { if (!sieve[i]) { while (i*i<max && !sieve[i]) { i++; } } if (sieve[i]) { print(i+" "); for (int j=i*i; j<=max; j+=i) { if (sieve[j]) { sieve[j]=false; plot(j, false); } } } if (i*i<max) { i++; } else { noLoop(); println("finished"); } }   void plot(int pos, boolean active) { set(pos%maxx, pos/maxx, active?#000000:#ffffff); }
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/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "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-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#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-Omdurman", "population", 4.98), SD("name","Dar Es Salaam", "population", 4.7), SD("name","Alexandria", "population", 4.58), SD("name","Abidjan", "population", 4.4), SD("name","Casablanca", "population", 3.98));   // Test case 1: n:=list.filter1n(fcn(city){ city["name"]=="Dar Es Salaam" }); // one way n:=list.filter1n(fcn(city){ city["name"].matches("dar es salaam") }); // or this way n.println("==index of ",list[n].values);   // Test case 2: city:=list.filter1(fcn(city){ city["population"]<5.0 }); // stop after first match city["name"].println(" is the first city with population under 5 million.");   // Test case 3: city:=list.filter1(fcn(city){ city["name"][0]=="A" }); println("The first \"A*\" city (%s) with population under 5 million: %f".fmt(city.values.xplode()));
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#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 element.
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,540 entries) Phix Rank: 2 (1,531 entries) Wren Rank: 3 (1,507 entries) Julia Rank: 4 (1,494 entries) Go Rank: 5 (1,488 entries) Raku Rank: 6 (1,448 entries) Perl Rank: 7 (1,402 entries) Nim Rank: 8 (1,382 entries) Python Rank: 9 (1,204 entries) C Rank: 10 (1,152 entries) REXX ... Notes   Each language typically demonstrates one or two methods of accessing the data:   with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)   with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).   The scraping and API solutions can be separate subsections, see the Tcl example.   Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping) If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.   A complete ranked listing of all   813   languages (from the REXX example) is included here   ──►   output from the REXX program.
#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% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF   PRINT "Downloading languages list..." url$ = "http://rosettacode.org/wiki/Category:Programming_Languages" file$ = @tmp$ + "languages.htm" SYS UDTF, 0, url$, file$, 0, 0 TO fail% IF fail% ERROR 100, "File download failed (languages)"   file% = OPENIN(file$) index% = 0 WHILE NOT EOF#file% REPEAT a$ = GET$#file% IF INSTR(a$, "<a href=""/wiki/Category") = 0 EXIT REPEAT i% = INSTR(a$, "</a>") IF i% = 0 EXIT REPEAT j% = i% REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = ">" OR i% = 0 IF i% = 0 EXIT REPEAT lang$(index%) = MID$(a$, i%+1, j%-i%-1) IF lang$(index%) <> "Languages" index% += 1 UNTIL TRUE ENDWHILE CLOSE #file%   C% = index% CALL SortUp%, lang$(0)   PRINT "Downloading categories list..." url$ = "http://www.rosettacode.org/w/index.php" url$ += "?title=Special:Categories&limit=5000" file$ = @tmp$ + "categories.htm" SYS UDTF, 0, url$, file$, 0, 0 TO fail% IF fail% ERROR 100, "File download failed (categories)"   file% = OPENIN(file$) WHILE NOT EOF#file% REPEAT a$ = GET$#file% i% = INSTR(a$, "member") IF i% = 0 EXIT REPEAT REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = "(" OR i% = 0 IF i% = 0 EXIT REPEAT tasks% = VAL(MID$(a$, i%+1)) IF tasks% = 0 EXIT REPEAT REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = "<" OR i% = 0 IF i% = 0 EXIT REPEAT j% = i% REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = ">" OR i% = 0 IF i% = 0 EXIT REPEAT k% = FNwhere(lang$(), MID$(a$, i%+1, j%-i%-1), index%-1) IF k% <> -1 tasks%(k%) += tasks% UNTIL TRUE ENDWHILE CLOSE #file%   CALL SortDown%, tasks%(0), lang$(0)   VDU 14 @% = 3 : REM Column width PRINT "List of languages as of " TIME$ FOR i% = 0 TO index%-1 IF tasks%(i%) = 0 EXIT FOR PRINT i%+1 ". " tasks%(i%) " - " lang$(i%) NEXT END   DEF FNwhere(a$(), S$, T%) LOCAL B%, C%, H% H% = 2 WHILE H%<T% H% *= 2:ENDWHILE H% /= 2 REPEAT IF (B%+H%)<=T% THEN SYS "CompareString", 0, NORM_IGNORECASE, S$, -1, a$(B%+H%), -1 TO C% IF C% >= 2 B% += H% ENDIF H% /= 2 UNTIL H%=0 SYS "CompareString", 0, NORM_IGNORECASE, S$, -1, a$(B%), -1 TO C% IF C% = 2 THEN = B% ELSE = -1
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. Example Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW Output: 12W1B12W3B24W1B14W Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
#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: The following 2 lines use currying. This not supported by ELLA ALGOL 68RS # GENCHAR input seq = gen char string(input,), output seq = gen char string(output,); END CO   GENCHAR input seq = (YIELDCHAR yield)VOID: gen char string(input, yield), output seq = (YIELDCHAR yield)VOID: gen char string(output, yield);   PROC gen encode = (GENCHAR gen char, YIELDCHAR yield)VOID: ( INT count := 0; CHAR prev; # FOR CHAR c IN # gen char( # ) DO ( # ## (CHAR c)VOID: ( IF count = 0 THEN count := 1; prev := c ELIF c NE prev THEN STRING str count := whole(count,0); gen char string(str count, yield); count := 1; yield(prev); prev := c ELSE count +:=1 FI # OD # )); IF count NE 0 THEN STRING str count := whole(count,0); gen char string(str count,yield); yield(prev) FI );   STRING zero2nine = "0123456789";   PROC gen decode = (GENCHAR gen char, YIELDCHAR yield)VOID: ( INT repeat := 0; # FOR CHAR c IN # gen char( # ) DO ( # ## (CHAR c)VOID: ( IF char in string(c, LOC INT, zero2nine) THEN repeat := repeat*10 + ABS c - ABS "0" ELSE FOR i TO repeat DO yield(c) OD; repeat := 0 FI # OD # )) );   # iterate through input string # print("Encode input: "); # FOR CHAR c IN # gen encode(input seq, # ) DO ( # ## (CHAR c)VOID: print(c) # OD # ); print(new line);   # iterate through output string # print("Decode output: "); # FOR CHAR c IN # gen decode(output seq, # ) DO ( # ## (CHAR c)VOID: print(c) # OD # ); print(new line)
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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) E c R r   print(rot13(‘foo’)) print(rot13(‘sbb’))