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/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... | #EchoLisp | EchoLisp |
(define (eval-with-x prog x)
(eval prog (environment-new (list (list 'x x)))))
(define prog '( + 1 (* x x)))
(eval-with-x prog 10) → 101
(eval-with-x prog 1000) → 1000001
(- (eval-with-x prog 1000) (eval-with-x prog 10)) → 999900
;; check x is unbound (no global)
x
😖️ error: #|user| : unbound variable : x
... |
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... | #Ada | Ada |
WITH GMP, GMP.Integers, Ada.Text_IO, GMP.Integers.Aliased_Internal_Value, Interfaces.C;
USE GMP, Gmp.Integers, Ada.Text_IO, Interfaces.C;
PROCEDURE Main IS
FUNCTION "+" (U : Unbounded_Integer) RETURN Mpz_T IS (Aliased_Internal_Value (U));
FUNCTION "+" (S : String) RETURN Unbounded_Integer IS (To_Unbounded_Int... |
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... | #PARI.2FGP | PARI/GP | Eratosthenes(lim)={
my(v=Vecsmall(lim\1,unused,1));
forprime(p=2,sqrt(lim),
forstep(i=p^2,lim,p,
v[i]=0
)
);
for(i=1,lim,if(v[i],print1(i", ")))
}; |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Phix | Phix | constant CITY_NAME = 1, POPULATION = 2
constant municipalities = {{"Lagos",21},
{"Cairo",15.2},
{"Kinshasa-Brazzaville",11.3},
{"Greater Johannesburg",7.55},
{"Mogadishu",5.85},
{"Khart... |
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 ... | #C.2B.2B | C++ | #include <string>
#include <algorithm>
#include <iterator>
#include <cstddef>
#include <exception>
#include <iostream>
// an exception to throw (actually, throwing an exception in this case is generally considered bad style, but it's part of the task)
class not_found: public std::exception
{
public:
not_found(std::... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Maxima | Maxima | /* Here is how to create a function and return a value at runtime. In the first example,
the function is made global, i.e. it still exists after the statement is run. In the second example, the function
is declared local. The evaluated string may read or write any variable defined before eval_string is run. */
kill(f... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Nanoquery | Nanoquery | exec("println \"hello, world\"")
exec("a = 1\nif a = 1\nprintln \"a is 1\"\nend\nprintln \"test\"") |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Nim | Nim | import ../compiler/[nimeval, llstream, ast], strformat, os
let std = findNimStdLibCompileTime()
let modules = [std, std / "pure", std / "std", std / "core"]
var intr = createInterpreter("script", modules)
#dynamic variable
let varname = commandLineParams()[0]
let expr = commandLineParams()[1]
#wrap the naked vari... |
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
... | #Raku | Raku | sub comma { $^i.flip.comb(3).join(',').flip }
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes(10_000_000);
my %filter = @primes.Set;
my $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };
for 'safe', 35, 'unsafe', 40 -> $type, $quantity {
say "Th... |
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... | #Elena | Elena | import extensions;
import extensions'scripting;
public program()
{
var text := program_arguments[1];
var arg := program_arguments[2];
var program := lscript.interpret(text);
console.printLine(
text,",",arg," = ",program.eval(arg.toReal()));
} |
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... | #Erlang | Erlang |
-module( runtime_evaluation ).
-export( [evaluate_form/2, form_from_string/1, task/0] ).
evaluate_form( Form, {Variable_name, Value} ) ->
Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ),
{value, Evaluation, _} = erl_eval:expr( Form, Bindings ),
Evaluation.
form_from_string( 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... | #ALGOL_68 | ALGOL 68 |
COMMENT
First cut. Doesn't yet do blocking and deblocking. Also, as
encryption and decryption are identical operations but for the
reciprocal exponents used, only one has been implemented below.
A later release will address these issues.
COMMENT
BEGIN
PR precision=1000 PR
MODE LLI = LONG LONG ... |
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... | #Pascal | Pascal |
program primes(output)
const
PrimeLimit = 1000;
var
primes: set of 1 .. PrimeLimit;
n, k: integer;
needcomma: boolean;
begin
{ calculate the primes }
primes := [2 .. PrimeLimit];
for n := 1 to trunc(sqrt(PrimeLimit)) do
begin
if n in primes
then
begin
k := n*n;
while k < PrimeLi... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #PHP | PHP |
<?php
$data_array = [
['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', '... |
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 ... | #Ceylon | Ceylon | shared test void searchAListTask() {
value haystack = [
"Zig", "Zag", "Wally", "Ronald", "Bush",
"Krusty", "Charlie", "Bush", "Bozo"];
assert(exists firstIdx = haystack.firstOccurrence("Bush"));
assert(exists lastIdx = haystack.lastOccurrence("Bush"));
assertEquals(firstIdx, ... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Oforth | Oforth | "[ [ $a, 12], [$b, 1.2], [ $c, [ $aaa, $bbb, $ccc ] ], [ $torun, #first ] ]" perform .s
[1] (List) [[a, 12], [b, 1.2], [c, [aaa, bbb, ccc]], [torun, #first]]
"12 13 +" perform
[1:interpreter] ExCompiler : Can't evaluate <+> |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #ooRexx | ooRexx |
a = .array~of(1, 2, 3)
ins = "loop num over a; say num; end"
interpret ins
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #OxygenBasic | OxygenBasic |
function ExecSeries(string s,double b,e,i) as string
'===================================================
'
sys a,p
string v,u,tab,cr,er
'
'PREPARE OUTPUT BUFFER
'
p=1
cr=chr(13) chr(10)
tab=chr(9)
v=nuls 4096
mid v,p,s+cr+cr
p+=4+len s
'
double x,y,z 'shared variables
'
'COMPILE... |
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
... | #REXX | REXX | /*REXX program lists a sequence (or a count) of ──safe── or ──unsafe── primes. */
parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 35 /*Not specified? Then assume default.*/
if kind=='' | kind=="," then kind= 'SAFE' ... |
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... | #Factor | Factor | USE: eval
: eval-bi@- ( a b program -- n )
tuck [ ( y -- z ) eval ] 2bi@ - ; |
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... | #Forth | Forth | : f-" ( a b snippet" -- )
[char] " parse ( code len )
2dup 2>r evaluate
swap 2r> evaluate
- . ;
2 3 f-" dup *" \ 5 (3*3 - 2*2) |
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... | #Genyris | Genyris | defmacro add100() (+ x 100)
var x 23
var firstresult (add100)
x = 1000
print
+ firstresult (add100) |
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... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main(void)
{
mpz_t n, d, e, pt, ct;
mpz_init(pt);
mpz_init(ct);
mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10);
mpz_init_set_str(e, "65537", 10);
mpz_init_set_str(d, "5617843187844953170... |
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... | #Perl | Perl | sub sieve {
my $n = shift;
my @composite;
for my $i (2 .. int(sqrt($n))) {
if (!$composite[$i]) {
for (my $j = $i*$i; $j <= $n; $j += $i) {
$composite[$j] = 1;
}
}
}
my @primes;
for my $i (2 .. $n) {
$composite[$i] || push @primes, $i;
}
@primes;
} |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #PicoLisp | PicoLisp | (scl 2)
(de *Data
("Lagos" 21.0)
("Cairo" 15.2)
("Kinshasa-Brazzaville" 11.3)
("Greater Johannesburg" 7.55)
("Mogadishu" 5.85)
("Khartoum-Omdurman" 4.98)
("Dar Es Salaam" 4.7)
("Alexandria" 4.58)
("Abidjan" 4.4)
("... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #PowerShell | PowerShell |
$jsonData = @'
[
{ "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... |
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 ... | #Clojure | Clojure | (let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]]
(let [idx (.indexOf haystack "Zig")]
(if (neg? idx)
(throw (Error. "item not found."))
idx))) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Oz | Oz | declare
%% simplest case: just evaluate expressions without bindings
R1 = {Compiler.virtualStringToValue "{Abs ~42}"}
{Show R1}
%% eval expressions with additional bindings and
%% the possibility to kill the evaluation by calling KillProc
KillProc
R2 = {Compiler.evalExpression "{Abs A}" unit('A':~42) ?K... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #PARI.2FGP | PARI/GP | runme(f)={
f()
};
runme( ()->print("Hello world!") ) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Perl | Perl | my ($a, $b) = (-5, 7);
$ans = eval 'abs($a * $b)'; # => 35 |
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
... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
p = 1
num = 0
limit1 = 36
limit2 = 41
safe1 = 1000000
safe2 = 10000000
see "the first 35 Safeprimes are: " + nl
while true
p = p + 1
p2 = (p-1)/2
if isprime(p) and isprime(p2)
num = num + 1
if num < limit1
see " " + p
... |
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
... | #Ruby | Ruby | require "prime"
class Integer
def safe_prime? #assumes prime
((self-1)/2).prime?
end
end
def format_parts(n)
partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
"There are %d safes and %d unsafes below #{n}."% partitions
end
puts "First 35 safe-primes:"
p Prime.each.lazy.select(&:safe_prime... |
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... | #Go | Go | package main
import (
"bitbucket.org/binet/go-eval/pkg/eval"
"fmt"
"go/parser"
"go/token"
)
func main() {
// an expression on x
squareExpr := "x*x"
// parse to abstract syntax tree
fset := token.NewFileSet()
squareAst, err := parser.ParseExpr(squareExpr)
if err != nil {
... |
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... | #C.23 | C# | using System;
using System.Numerics;
using System.Text;
class Program
{
static void Main(string[] args)
{
BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
BigInteger e = 65537;
BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685")... |
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... | #Phix | Phix | constant limit = 1000
sequence primes = {}
sequence flags = repeat(1, limit)
for i=2 to floor(sqrt(limit)) do
if flags[i] then
for k=i*i to limit by i do
flags[k] = 0
end for
end if
end for
for i=2 to limit do
if flags[i] then
primes &= i
end if
end for
pp(primes,{pp_... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Python | Python | cities = [
{ "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 },
... |
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 ... | #CLU | CLU | % Search an indexable, ordered collection.
% The collection needs to provide `indexes' and `fetch';
% the element type needs to provide `equal'.
search = proc [T, U: type] (haystack: T, needle: U)
returns (int) signals (not_found)
where T has indexes: itertype (T) yields (int),
f... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Phix | Phix | -- demo\rosetta\Runtime_evaluation.exw
without javascript_semantics
requires("1.0.1")
include eval.e -- (not an autoinclude, pulls in around 90% of the interpreter/compiler proper)
string code = """
integer i = 0
bool r_init = false
sequence r
if not r_init then r = {} end if
for k=1 to 4 do
i += k
r &= k
end... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #PHP | PHP |
<?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #PicoLisp | PicoLisp | program demo = compile_string(#"
string name=\"demo\";
string hello()
{
return(\"hello, i am \"+name);
}");
demo()->hello();
Result: "hello, i am demo" |
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
... | #Rust | Rust | fn is_prime(n: i32) -> bool {
for i in 2..n {
if i * i > n {
return true;
}
if n % i == 0 {
return false;
}
}
n > 1
}
fn is_safe_prime(n: i32) -> bool {
is_prime(n) && is_prime((n - 1) / 2)
}
fn is_unsafe_prime(n: i32) -> bool {
is_prime(n) && !is_prime((n - 1) / 2)
}
fn next_prime(n: i32) -> i... |
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... | #Groovy | Groovy | def cruncher = { x1, x2, program ->
Eval.x(x1, program) - Eval.x(x2, program)
} |
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... | #J | J | EvalWithX=. monad : 0
'CODE V0 V1'=. y
(". CODE [ x=. V1) - (". CODE [ x=. V0)
)
EvalWithX '^x';0;1
1.71828183 |
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... | #Common_Lisp | Common Lisp | (defparameter *n* 9516311845790656153499716760847001433441357)
(defparameter *e* 65537)
(defparameter *d* 5617843187844953170308463622230283376298685)
;; magic
(defun encode-string (message)
(parse-integer (reduce #'(lambda (x y) (concatenate 'string x y))
(loop for c across message collect (format nil "~2,'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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def sequence /# ( ini end [step] ) #/
( ) swap for 0 put endfor
enddef
1000 var limit
( 1 limit ) sequence
( 2 limit ) for >ps
( tps dup * limit tps ) for
dup limit < if 0 swap set else drop endif
endfor
cps
endfor
( 1 limit 0 ) remove
pstack |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Racket | Racket |
#lang racket
(define (findf/pos proc lst)
(let loop ([lst lst] [pos 0])
(cond
[(null? lst) #f]
[(proc (car lst)) pos]
[else (loop (cdr lst) (add1 pos))])))
|
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Raku | Raku | my @cities =
{ 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 => ... |
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 ... | #COBOL | COBOL | *> This is written to COBOL85, which does not include exceptions.
IDENTIFICATION DIVISION.
PROGRAM-ID. Search-List.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 haystack-area.
78 Haystack-Size VALUE 10.
03 haystack-data.
05 FILLER PIC X(7) ... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Pike | Pike | program demo = compile_string(#"
string name=\"demo\";
string hello()
{
return(\"hello, i am \"+name);
}");
demo()->hello();
Result: "hello, i am demo" |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #PowerShell | PowerShell |
$test2plus2 = '2 + 2 -eq 4'
Invoke-Expression $test2plus2
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Python | Python | >>> exec '''
x = sum([1,2,3,4])
print x
'''
10 |
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
... | #Shale | Shale | #!/usr/local/bin/shale
// Safe and unsafe primes.
//
// Safe prime p: (p - 1) / 2 is prime
// Unsafe prime: any prime that is not a safe prime
primes library
init dup var {
pl sieve type primes::()
10000000 0 pl generate primes::()
} =
isSafe dup var {
1 - 2 / pl isprime primes::()
} =
comma dup var {
... |
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
... | #Sidef | Sidef | func is_safeprime(p) {
is_prime(p) && is_prime((p-1)/2)
}
func is_unsafeprime(p) {
is_prime(p) && !is_prime((p-1)/2)
}
func safeprime_count(from, to) {
from..to -> count_by(is_safeprime)
}
func unsafeprime_count(from, to) {
from..to -> count_by(is_unsafeprime)
}
say "First 35 safe-primes:"
say (... |
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... | #Java | Java | import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static cla... |
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... | #D | D | void main() {
import std.stdio, std.bigint, std.algorithm, std.string, std.range,
modular_exponentiation;
immutable txt = "Rosetta Code";
writeln("Plain text: ", txt);
// A key set big enough to hold 16 bytes of plain text in
// a single block (to simplify the example) and... |
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... | #PHP | PHP |
function iprimes_upto($limit)
{
for ($i = 2; $i < $limit; $i++)
{
$primes[$i] = true;
}
for ($n = 2; $n < $limit; $n++)
{
if ($primes[$n])
{
for ($i = $n*$n; $i < $limit; $i += $n)
{
$primes[$i] = false;
}
}
}
return $primes;
}
echo wordwrap(
'Primes less or ... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #REXX | REXX | /*REXX program (when using criteria) locates values (indices) from an associate array. */
$="Lagos=21, Cairo=15.2, Kinshasa-Brazzaville=11.3, Greater Johannesburg=7.55, Mogadishu=5.85,",
"Khartoum-Omdurman=4.98, Dar Es Salaam=4.7, Alexandria=4.58, Abidjan=4.4, Casablanca=3.98"
@.= '(city not found)'; city.=... |
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 ... | #Common_Lisp | Common Lisp | (let ((haystack '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)))
(dolist (needle '(Washington Bush))
(let ((index (position needle haystack)))
(if index
(progn (print index) (princ needle))
(progn (print needle) (princ "is not in haystack")))))) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Quackery | Quackery | 10 $ "1 swap times [ i 1+ * ]" quackery echo |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #R | R | expr1 <- quote(a+b*c)
expr2 <- parse(text="a+b*c")[[1]]
expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`))) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Racket | Racket |
#lang racket
(require racket/sandbox)
(define e (make-evaluator 'racket))
(e '(define + *))
(e '(+ 10 20))
(+ 10 20)
;; (e '(delete-file "/etc/passwd"))
;; --> delete-file: `delete' access denied for /etc/passwd
|
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
... | #Simula | Simula |
BEGIN
CLASS BOOLARRAY(N); INTEGER N;
BEGIN
BOOLEAN ARRAY DATA(0:N-1);
END BOOLARRAY;
CLASS INTARRAY(N); INTEGER N;
BEGIN
INTEGER ARRAY DATA(0:N-1);
END INTARRAY;
REF(BOOLARRAY) PROCEDURE SIEVE(LIMIT);
INTEGER LIMIT;
BEGIN
REF(BOOLARRAY) C;
... |
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
... | #Smalltalk | Smalltalk | [
| isSafePrime printFirstNElements |
isSafePrime := [:p | ((p-1)//2) isPrime].
printFirstNElements :=
[:coll :n |
(coll to:n)
do:[:p | Transcript show:p]
separatedBy:[Transcript space]
].
(Iterator on:[:b | Integer primesUpTo:10000000 do... |
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... | #JavaScript | JavaScript | function evalWithX(expr, a, b) {
var x = a;
var atA = eval(expr);
x = b;
var atB = eval(expr);
return atB - atA;
} |
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... | #Jsish | Jsish | /* Runtime evaluation in an environment, in Jsish */
function evalWithX(expr, a, b) {
var x = a;
var atA = eval(expr);
x = b;
var atB = eval(expr);
return atB - atA;
}
;evalWithX('Math.exp(x)', 0, 1);
;evalWithX('Math.exp(x)', 1, 0);
/*
=!EXPECTSTART!=
evalWithX('Math.exp(x)', 0, 1) ==> 1.718281... |
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... | #Delphi | Delphi |
program RSA_code;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigIntegers;
type
TRSA = record
private
n, e, d: BigInteger;
class function PlainTextAsNumber(data: AnsiString): BigInteger; static;
class function NumberAsPlainText(Num: BigInteger): AnsiString; static;
public
constru... |
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... | #11l | 11l | random:seed(Int(Time().unix_time()))
V total = 0
V count = 0
[Int] attributes
L total < 75 | count < 2
attributes = (0..5).map(attribute -> (sum(sorted((0..3).map(roll -> random:(1 .. 6)))[1..])))
L(attribute) attributes
I attribute >= 15
count++
total = sum(attributes)
print(total‘ ’att... |
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... | #Picat | Picat |
primes(N) = L =>
A = new_array(N),
foreach(I in 2..floor(sqrt(N)))
if (var(A[I])) then
foreach(J in I**2..I..N)
A[J]=0
end
end
end,
L=[I : I in 2..N, var(A[I])].
|
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Ring | Ring |
# Project : Search a list of records
cities = [[:name = "Lagos",:population = 21.0 ],
[:name = "Cairo",:population = 15.2 ],
[:name = "Kinshasa-Brazzaville",:population = 11.3 ],
[:name = "Greater Johannesburg",:population = 7.55],
[:name = "Mogadishu",:populat... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Ruby | Ruby | cities = [
{name: "Lagos", population: 21},
{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... |
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 ... | #D | D | import std.algorithm, std.range, std.string;
auto firstIndex(R, T)(R hay, T needle) {
auto i = countUntil(hay, needle);
if (i == -1)
throw new Exception("No needle found in haystack");
return i;
}
auto lastIndex(R, T)(R hay, T needle) {
return walkLength(hay) - firstIndex(retro(hay), needle) - 1;
}
vo... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Raku | Raku | use MONKEY-SEE-NO-EVAL;
my ($a, $b) = (-5, 7);
my $ans = EVAL 'abs($a * $b)'; # => 35 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #REBOL | REBOL | a: -5
b: 7
answer: do [abs a * b] ; => 35 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #REXX | REXX | /*REXX program illustrates the ability to execute code entered at runtime (from C.L.)*/
numeric digits 10000000 /*ten million digits should do it. */
bee=51
stuff= 'bee=min(-2,44); say 13*2 "[from inside the box.]"; abc=abs(bee)'
interpret stuff
say 'bee=' bee
say 'abc=' abc
say
... |
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
... | #Swift | Swift | import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q <... |
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
... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Console
Namespace safety
Module SafePrimes
Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet()
Sub Main()
For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35)
WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes... |
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:
... | #11l | 11l | F rk4(f, x0, y0, x1, n)
V vx = [0.0] * (n + 1)
V vy = [0.0] * (n + 1)
V h = (x1 - x0) / Float(n)
V x = x0
V y = y0
vx[0] = x
vy[0] = y
L(i) 1..n
V k1 = h * f(x, y)
V k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
V k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
V k4 = h * f(x + h, y + k3)
... |
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... | #Julia | Julia | macro evalwithx(expr, a, b)
return quote
x = $a
tmp = $expr
x = $b
return $expr - tmp
end
end
@evalwithx(2 ^ x, 3, 5) # raw expression (AST) |
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... | #Kotlin | Kotlin | // Kotlin JS version 1.1.4-3
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
} |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #11l | 11l | T Token
T.enum Kind
INT
FLOAT
STRING
IDENT
LPAR
RPAR
END
Kind kind
String val
F (kind, val = ‘’)
.kind = kind
.val = val
F lex(input_str)
[Token] result
V pos = 0
F current()
R I @pos < @input_str.len {@input_str[@pos]} E Char("\0"... |
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... | #Erlang | Erlang |
%%% @author Tony Wallace <tony@tony.gen.nz>
%%% @doc
%%% For details of the algorithms used see
%%% https://en.wikipedia.org/wiki/Modular_exponentiation
%%% @end
%%% Created : 21 Jul 2021 by Tony Wallace <tony@resurrection>
-module mod.
-export [mod_mult/3,mod_exp/3,binary_exp/2,test/0].
mod_mult(I1,I2,Mod) when ... |
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... | #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
putch: equ 2h
time: equ 2ch
org 100h
section .text
mov ah,time ; Retrieve system time from MS-DOS
int 21h
call rseed ; Seed the RNG
rolls: xor ah,ah ; AH=0 (running total)
mov dx,6 ; DH=0 (amount >=15), DL=6 (counter)
mov di,attrs
attr: call roll4 ; Roll an attribute
mov al,14
cmp al,bh ... |
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... | #PicoLisp | PicoLisp | (de sieve (N)
(let Sieve (range 1 N)
(set Sieve)
(for I (cdr Sieve)
(when I
(for (S (nth Sieve (* I I)) S (nth (cdr S) I))
(set S) ) ) )
(filter bool Sieve) ) ) |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Rust | Rust | struct City {
name: &'static str,
population: f64,
}
fn main() {
let cities = [
City {
name: "Lagos",
population: 21.0,
},
City {
name: "Cairo",
population: 15.2,
},
City {
name: "Kinshasa-Brazzaville",
... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Scala | Scala | object SearchListOfRecords extends App {
val cities = Vector(
City("Lagos", 21.0e6),
City("Cairo", 15.2e6),
City("Kinshasa-Brazzaville", 11.3e6),
City("Greater Johannesburg", 7.55e6),
City("Mogadishu", 5.85e6),
City("Khartoum-Omdurman", 4.98e6),
City("Dar Es Salaam", 4.7e6),
City("Alex... |
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 ... | #Delphi | Delphi | program Needle;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
var
list: TStringList;
needle: string;
ind: Integer;
begin
list := TStringList.Create;
try
list.Append('triangle');
list.Append('fork');
list.Append('limit');
list.Append('baby');
list.Append('needle');
list.Sort;
... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Ring | Ring |
Eval("nOutput = 5+2*5 " )
See "5+2*5 = " + nOutput + nl
Eval("for x = 1 to 10 see x + nl next")
Eval("func test see 'message from test!' ")
test()
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Ruby | Ruby | a, b = 5, -7
ans = eval "(a * b).abs" # => 35 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Scheme | Scheme | > (define x 37)
> (eval '(+ x 5))
42
> (eval '(+ x 5) (interaction-environment))
42
> (eval '(+ x 5) (scheme-report-environment 5)) ;; provides R5RS definitions
Error: identifier not visible x.
Type (debug) to enter the debugger.
> (display (eval (read)))
(+ 4 5) ;; this is input from the user.
9 |
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
... | #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
var c = Int.primeSieve(1e7, false) // need primes up to 10 million here
var safe = List.filled(35, 0)
var count = 0
var i = 3
while (count < 35) {
if (!c[i] && !c[(i-1)/2]) {
safe[count] = i
count = count + 1
}
i = i + 2
}
System.print("The firs... |
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:
... | #Action.21 | Action! | INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
REAL one,two,four,six
PROC Init()
IntToReal(1,one)
IntToReal(2,two)
IntToReal(4,four)
IntToReal(6,six)
RETURN
PROC Fun=*(REAL POINTER x,y,res)
DEFINE JSR="$20"
DEFINE RTS="$60"
[JSR $00 $00 ;JSR to addre... |
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:
... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure RungeKutta is
type Floaty is digits 15;
type Floaty_Array is array (Natural range <>) of Floaty;
package FIO is new Ada.Text_IO.Float_IO(Floaty); use FIO;
type Derivative is access function(t, y : Floaty) return Flo... |
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... | #Liberty_BASIC | Liberty BASIC |
expression$ = "x^2 - 7"
Print (EvaluateWithX(expression$, 5) - EvaluateWithX(expression$, 3))
End
Function EvaluateWithX(expression$, x)
EvaluateWithX = Eval(expression$)
End Function |
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... | #Lua | Lua |
code = loadstring"return x^2" --this doesn't really need to be input, does it?
val1 = setfenv(code, {x = io.read() + 0})()
val2 = setfenv(code, {x = io.read() + 0})()
print(val2 - val1)
|
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).
... | #Ada | Ada | with Ada.Strings.Unbounded;
private with Ada.Containers.Indefinite_Vectors;
generic
with procedure Print_Line(Indention: Natural; Line: String);
package S_Expr is
function "-"(S: String) return Ada.Strings.Unbounded.Unbounded_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
function "+"(U: ... |
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... | #F.23 | F# |
//Nigel Galloway February 12th., 2018
let RSA n g l = bigint.ModPow(l,n,g)
let encrypt = RSA 65537I 9516311845790656153499716760847001433441357I
let m_in = System.Text.Encoding.ASCII.GetBytes "The magic words are SQUEAMISH OSSIFRAGE"|>Array.chunkBySize 16|>Array.map(Array.fold(fun n g ->(n*256I)+(bigint(int g))) 0I)
... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program rpg64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.in... |
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... | #Action.21 | Action! | TYPE Result=[BYTE success,sum,highCount]
BYTE FUNC GenerateAttrib()
BYTE i,v,min,sum
min=255 sum=0
FOR i=0 TO 3
DO
v=Rand(6)+1
IF v<min THEN
min=v
FI
sum==+v
OD
RETURN (sum-min)
PROC Generate(BYTE ARRAY a BYTE len Result POINTER res)
BYTE i,v,count
res.highCount=0 res.sum=0
F... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #PL.2FI | PL/I | eratos: proc options (main) reorder;
dcl i fixed bin (31);
dcl j fixed bin (31);
dcl n fixed bin (31);
dcl sn fixed bin (31);
dcl hbound builtin;
dcl sqrt builtin;
dcl sysin file;
dcl sysprint file;
get list (n);
sn = sqrt(n);
begin;
dcl primes(n) bit (1) aligned init ((*)((1)'1'b));
i = 2;
... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Scheme | Scheme |
(import (scheme base)
(scheme char)
(scheme write)
(srfi 1) ; lists
(srfi 132)) ; sorting
(define-record-type <places> ; compound data type is a record with two fields
(make-place name population)
place?
(name place-name)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.