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/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 }
|
#Common_Lisp
|
Common Lisp
|
(defun runge-kutta (f x y x-end n)
(let ((h (float (/ (- x-end x) n) 1d0))
k1 k2 k3 k4)
(setf x (float x 1d0)
y (float y 1d0))
(cons (cons x y)
(loop for i below n do
(setf k1 (* h (funcall f x y))
k2 (* h (funcall f (+ x (* 0.5d0 h)) (+ y (* 0.5d0 k1))))
k3 (* h (funcall f (+ x (* 0.5d0 h)) (+ y (* 0.5d0 k2))))
k4 (* h (funcall f (+ x h) (+ y k3)))
x (+ x h)
y (+ y (/ (+ k1 k2 k2 k3 k3 k4) 6)))
collect (cons x y)))))
(let ((sol (runge-kutta (lambda (x y) (* x (sqrt y))) 0 1 10 100)))
(loop for n from 0
for (x . y) in sol
when (zerop (mod n 10))
collect (list x y (- y (/ (expt (+ 4 (* x x)) 2) 16)))))
((0.0d0 1.0d0 0.0d0)
(0.9999999999999999d0 1.562499854278108d0 -1.4572189210859676d-7)
(2.0000000000000004d0 3.9999990805207988d0 -9.194792029987298d-7)
(3.0000000000000013d0 10.562497090437557d0 -2.9095624576314094d-6)
(4.000000000000002d0 24.999993765090643d0 -6.234909392333066d-6)
(4.999999999999998d0 52.56248918030259d0 -1.081969734428867d-5)
(5.999999999999995d0 99.9999834054036d0 -1.659459609015812d-5)
(6.999999999999991d0 175.56247648227117d0 -2.3517728038768837d-5)
(7.999999999999988d0 288.9999684347983d0 -3.156520000402452d-5)
(8.999999999999984d0 451.56245927683887d0 -4.072315812209126d-5)
(9.99999999999998d0 675.9999490167083d0 -5.0983286655537086d-5))
|
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.
|
#REXX
|
REXX
|
/*REXX program reads 2 files & displays a ranked list of Rosetta Code languages by users*/
parse arg catFID lanFID outFID . /*obtain optional arguments from the CL*/
call init /*initialize some REXX variables. */
call get /*obtain data from two separate files. */
call eSort #,0 /*sort languages along with members. */
call tSort /* " " that are tied in rank.*/
call eSort #,1 /* " " along with members. */
call out /*create the RC_USER.OUT (output) file.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _= insert(",",_,jc); end; return _
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSort: procedure expose #. @. !tr.; arg N,p2; h= N /*sort: number of members*/
do while h>1; h= h % 2 /*halve number of records*/
do i=1 for N-h; j= i; k= h + i /*sort this part of list.*/
if p2 then do while !tR.k==!tR.j & @.k>@.j /*this uses a hard swap ↓*/
@= @.j; #= !tR.j; @.j= @.k; !tR.j= !tR.k; @.k= @; !tR.k= #
if h>=j then leave; j= j - h; k= k - h
end /*while !tR.k==···*/
else do while #.k<#.j /*this uses a hard swap ↓*/
@= @.j; #= #.j; @.j= @.k; #.j= #.k; @.k= @; #.k= #
if h>=j then leave; j= j - h; k= k - h
end /*while #.k<···*/
end /*i*/ /*hard swaps needed for embedded blanks.*/
end /*while h>1*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
get: langs= 0; call rdr 'languages' /*assign languages ───► L.ααα */
call rdr 'categories' /*append categories ───► catHeap */
#= 0
do j=1 until catHeap=='' /*process the heap of categories. */
parse var catHeap cat.j (sep) catHeap /*get a category from the catHeap. */
parse var cat.j cat.j '<' "(" mems . /*untangle the strange─looking string. */
cat.j= space(cat.j); ?=cat.j; upper ? /*remove any superfluous blanks. */
if ?=='' | \L.? then iterate /*it's blank or it's not a language. */
if pos(',', mems)\==0 then mems= space(translate(mems,,","), 0) /*¬commas.*/
if \datatype(mems, 'W') then iterate /*is the "members" number not numeric? */
#.0= #.0 + mems /*bump the number of members found. */
if u.?\==0 then do; do f=1 for # until [email protected]
end /*f*/
#.f= #.f + mems; iterate j /*languages in different cases.*/
end /* [↑] handle any possible duplicates.*/
u.?= u.? + 1; #= # + 1 /*bump a couple of counters. */
#.#= #.# + mems; @.#= cat.j; @u.#=? /*bump the counter; assign it (upper).*/
end /*j*/
!.=; @tno= '(total) number of' /*array holds indication of TIED langs.*/
call tell right(commas(#), 9) @tno 'languages detected in the category file'
call tell right(commas(langs),9) ' " " " " " " " language "'
call tell right(commas(#.0), 9) @tno 'entries (users of lanugages) detected', , 1
term= 0
return /*don't show any more msgs──►term. [↑] */
/*──────────────────────────────────────────────────────────────────────────────────────*/
init: sep= '█'; L.=0; #.=0; u.=#.; catHeap=; term=1; old.= /*assign some REXX vars*/
if catFID=='' then catFID= "RC_USER.CAT" /*Not specified? Then use the default.*/
if lanFID=='' then lanFID= "RC_USER.LAN" /* " " " " " " */
if outFID=='' then outFID= "RC_USER.OUT" /* " " " " " " */
call tell center('timestamp: ' date() time("Civil"),79,'═'), 2, 1; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
out: w= length( commas(#) ); rank= 0 /* [↓] show by ascending rank of lang.*/
do t=# by -1 for #; rank= rank + 1 /*bump rank of a programming language. */
call tell right('rank:' right(commas(!tR.t), w), 20-1) right(!.t, 7),
right('('commas(#.t) left("entr"s(#.t, 'ies', "y")')', 9), 20) @.t
end /*#*/ /* [↑] S(···) pluralizes a word. */
call tell left('', 27) "☼ end─of─list. ☼", 1, 2; return /*bottom title.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
rdr: arg which 2; igAst= 1 /*ARG uppers WHICH, obtain the 1st char*/
if which=='L' then inFID= lanFID /*use this fileID for the languages. */
if which=='C' then inFID= catFID /* " " " " " categories. */
Uyir= 'உயிர்/Uyir' /*Unicode (in text) name for Uyir */
old.0= '╬£C++' ; new.0= "µC++" /*Unicode ╬£C++ ───► ASCII─8: µC++ */
old.1= 'UC++' ; new.1= "µC++" /*old UC++ ───► ASCII─8: µC++ */
old.2= '╨£╨Ü-' ; new.2= "MK-" /*Unicode ╨£╨Ü─ ───► ASCII-8: MK- */
old.3= 'D├⌐j├á' ; new.3= "Déjà" /*Unicode ├⌐j├á ───► ASCII─8: Déjà */
old.4= 'Cach├⌐' ; new.4= "Caché" /*Unicode Cach├⌐ ───► ASCII─8: Caché */
old.5= '??-61/52' ; new.5= "MK-61/52" /*somewhere past, a mis─translated: MK-*/
old.6= 'F┼ìrmul├ª' ; new.6= 'Fôrmulæ' /*Unicode ───► ASCII─8: Fôrmulæ */
old.7= '╨£iniZinc' ; new.7= 'MiniZinc' /*Unicode ───► ASCII─8: MiniZinc*/
old.8= Uyir ; new.8= 'Uyir' /*Unicode ───► ASCII─8: Uyir */
old.9= 'Perl 6' ; new.9= 'Raku' /* (old name) ───► (new name) */
do recs=0 while lines(inFID) \== 0 /*read a file, a single line at a time.*/
$= translate( linein(inFID), , '9'x) /*handle any stray TAB ('09'x) chars.*/
$$= space($); if $$=='' then iterate /*ignore all blank lines in the file(s)*/
do v=0 while old.v \== '' /*translate Unicode variations of langs*/
if pos(old.v, $$) \==0 then $$= changestr(old.v, $$, new.v)
end /*v*/ /* [↑] handle different lang spellings*/
if igAst then do; igAst= pos(' * ', $)==0; if igAst then iterate; end
if pos('RETRIEVED FROM', translate($$))\==0 then leave /*pseudo End─Of─Data?.*/
if which=='L' then do; if left($$, 1)\=="*" then iterate /*lang ¬legitimate?*/
parse upper var $$ '*' $$ "<"; $$= space($$)
if $$=='' then iterate
$$= $$ 'USER'
L.$$= 1
langs= langs + 1 /*bump # of languages/users found.*/
iterate
end /* [↓] extract computer language name.*/
if left($$, 1)=='*' then $$= sep || space( substr($$, 2) )
catHeap= catHeap $$ /*append to the catHeap (CATegory) heap*/
end /*recs*/
call tell right( commas(recs), 9) 'records read from file: ' inFID
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: do '0'arg(2); call lineout outFID," " ; if term then say ; end
call lineout outFID,arg(1) ; if term then say arg(1)
do '0'arg(3); call lineout outFID," " ; if term then say ; end
return /*show BEFORE blank lines (if any), message, show AFTER blank lines.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
tSort: tied=; r= 0 /*add true rank (tR) ───► the entries. */
do j=# by -1 for #; r= r+1; tR= r; !tR.j= r; jp= j+1; jm= j-1
if tied=='' then pR= r; tied= /*handle when language rank is untied. */
if #.j==#.jp | #.j==#.jm then do; !.j= '[tied]'; tied= !.j; end
if #.j==#.jp then do; tR= pR; !tR.j= pR; end
else pR= r
end /*j*/; return
|
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.
|
#R
|
R
|
evalWithAB <- function(expr, var, a, b) {
env <- new.env() # provide a separate env, so that the choosen
assign(var, a, envir=env) # var name do not collide with symbols inside
# this function (e.g. it could be even "env")
atA <- eval(parse(text=expr), env)
# and then evaluate the expression inside this
# ad hoc env-ironment
assign(var, b, envir=env)
atB <- eval(parse(text=expr), env)
return(atB - atA)
}
print(evalWithAB("2*x+1", "x", 5, 3))
print(evalWithAB("2*y+1", "y", 5, 3))
print(evalWithAB("2*y+1", "x", 5, 3)) # error: object "y" not found
|
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.
|
#Racket
|
Racket
|
#lang racket
(define ns (make-base-namespace))
(define (eval-with-x code a b)
(define (with v) (eval `(let ([x ',v]) ,code) ns))
(- (with b) (with a)))
|
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.2B.2B
|
C++
|
#include <cctype>
#include <iomanip>
#include <iostream>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <variant>
namespace s_expr {
enum class token_type { none, left_paren, right_paren, symbol, string, number };
enum class char_type { left_paren, right_paren, quote, escape, space, other };
enum class parse_state { init, quote, symbol };
struct token {
token_type type = token_type::none;
std::variant<std::string, double> data;
};
char_type get_char_type(char ch) {
switch (ch) {
case '(':
return char_type::left_paren;
case ')':
return char_type::right_paren;
case '"':
return char_type::quote;
case '\\':
return char_type::escape;
}
if (isspace(static_cast<unsigned char>(ch)))
return char_type::space;
return char_type::other;
}
bool parse_number(const std::string& str, token& tok) {
try {
size_t pos = 0;
double num = std::stod(str, &pos);
if (pos == str.size()) {
tok.type = token_type::number;
tok.data = num;
return true;
}
} catch (const std::exception&) {
}
return false;
}
bool get_token(std::istream& in, token& tok) {
char ch;
parse_state state = parse_state::init;
bool escape = false;
std::string str;
token_type type = token_type::none;
while (in.get(ch)) {
char_type ctype = get_char_type(ch);
if (escape) {
ctype = char_type::other;
escape = false;
} else if (ctype == char_type::escape) {
escape = true;
continue;
}
if (state == parse_state::quote) {
if (ctype == char_type::quote) {
type = token_type::string;
break;
}
else
str += ch;
} else if (state == parse_state::symbol) {
if (ctype == char_type::space)
break;
if (ctype != char_type::other) {
in.putback(ch);
break;
}
str += ch;
} else if (ctype == char_type::quote) {
state = parse_state::quote;
} else if (ctype == char_type::other) {
state = parse_state::symbol;
type = token_type::symbol;
str = ch;
} else if (ctype == char_type::left_paren) {
type = token_type::left_paren;
break;
} else if (ctype == char_type::right_paren) {
type = token_type::right_paren;
break;
}
}
if (type == token_type::none) {
if (state == parse_state::quote)
throw std::runtime_error("syntax error: missing quote");
return false;
}
tok.type = type;
if (type == token_type::string)
tok.data = str;
else if (type == token_type::symbol) {
if (!parse_number(str, tok))
tok.data = str;
}
return true;
}
void indent(std::ostream& out, int level) {
for (int i = 0; i < level; ++i)
out << " ";
}
class object {
public:
virtual ~object() {}
virtual void write(std::ostream&) const = 0;
virtual void write_indented(std::ostream& out, int level) const {
indent(out, level);
write(out);
}
};
class string : public object {
public:
explicit string(const std::string& str) : string_(str) {}
void write(std::ostream& out) const { out << std::quoted(string_); }
private:
std::string string_;
};
class symbol : public object {
public:
explicit symbol(const std::string& str) : string_(str) {}
void write(std::ostream& out) const {
for (char ch : string_) {
if (get_char_type(ch) != char_type::other)
out << '\\';
out << ch;
}
}
private:
std::string string_;
};
class number : public object {
public:
explicit number(double num) : number_(num) {}
void write(std::ostream& out) const { out << number_; }
private:
double number_;
};
class list : public object {
public:
void write(std::ostream& out) const;
void write_indented(std::ostream&, int) const;
void append(const std::shared_ptr<object>& ptr) {
list_.push_back(ptr);
}
private:
std::list<std::shared_ptr<object>> list_;
};
void list::write(std::ostream& out) const {
out << "(";
if (!list_.empty()) {
auto i = list_.begin();
(*i)->write(out);
while (++i != list_.end()) {
out << ' ';
(*i)->write(out);
}
}
out << ")";
}
void list::write_indented(std::ostream& out, int level) const {
indent(out, level);
out << "(\n";
if (!list_.empty()) {
for (auto i = list_.begin(); i != list_.end(); ++i) {
(*i)->write_indented(out, level + 1);
out << '\n';
}
}
indent(out, level);
out << ")";
}
class tokenizer {
public:
tokenizer(std::istream& in) : in_(in) {}
bool next() {
if (putback_) {
putback_ = false;
return true;
}
return get_token(in_, current_);
}
const token& current() const {
return current_;
}
void putback() {
putback_ = true;
}
private:
std::istream& in_;
bool putback_ = false;
token current_;
};
std::shared_ptr<object> parse(tokenizer&);
std::shared_ptr<list> parse_list(tokenizer& tok) {
std::shared_ptr<list> lst = std::make_shared<list>();
while (tok.next()) {
if (tok.current().type == token_type::right_paren)
return lst;
else
tok.putback();
lst->append(parse(tok));
}
throw std::runtime_error("syntax error: unclosed list");
}
std::shared_ptr<object> parse(tokenizer& tokenizer) {
if (!tokenizer.next())
return nullptr;
const token& tok = tokenizer.current();
switch (tok.type) {
case token_type::string:
return std::make_shared<string>(std::get<std::string>(tok.data));
case token_type::symbol:
return std::make_shared<symbol>(std::get<std::string>(tok.data));
case token_type::number:
return std::make_shared<number>(std::get<double>(tok.data));
case token_type::left_paren:
return parse_list(tokenizer);
default:
break;
}
throw std::runtime_error("syntax error: unexpected token");
}
} // namespace s_expr
void parse_string(const std::string& str) {
std::istringstream in(str);
s_expr::tokenizer tokenizer(in);
auto exp = s_expr::parse(tokenizer);
if (exp != nullptr) {
exp->write_indented(std::cout, 0);
std::cout << '\n';
}
}
int main(int argc, char** argv) {
std::string test_string =
"((data \"quoted data\" 123 4.5)\n"
" (data (!@# (4.5) \"(more\" \"data)\")))";
if (argc == 2)
test_string = argv[1];
try {
parse_string(test_string);
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
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
|
#Erlang
|
Erlang
|
#! /usr/bin/env escript
-module( fix_code_tags ).
-mode( compile ).
main( _ ) ->
File_lines = loop( io:get_line(""), [] ),
Code_fixed_lines = fix_code_tag( binary:list_to_bin(File_lines) ),
% true = code:add_pathz( "ebin" ),
% ok = find_unimplemented_tasks:init(),
% Dict = dict:from_list( [dict_tuple(X) || X <- rank_languages_by_popularity:rosettacode_languages()],
Dict = dict:from_list( [dict_tuple(X) || X <- ["foo", "bar", "baz"]] ),
{_Dict, All_fixed_lines} = lists:foldl( fun fix_language_tag/2, {Dict, Code_fixed_lines}, dict:fetch_keys(Dict) ),
io:fwrite( "~s", [binary:bin_to_list(All_fixed_lines)] ).
dict_tuple( Language ) -> {binary:list_to_bin(string:to_lower(Language)), binary:list_to_bin(Language)}.
fix_code_tag( Binary ) ->
Avoid_wiki = binary:list_to_bin( [<<"<">>, <<"lang ">>] ),
Code_fixed_lines = binary:replace( Binary, <<"<code ">>, Avoid_wiki, [global] ),
Avoid_wiki_again = binary:list_to_bin( [<<"</">>, <<"lang ">>] ),
binary:replace( Code_fixed_lines, <<"</code>">>, Avoid_wiki_again, [global] ).
fix_language_tag( Language_key, {Dict, Binary} ) ->
Language = fix_language_tag_rosettacode_language( Language_key, dict:find(Language_key, Dict) ),
Language_start_old = binary:list_to_bin( [<<"<">>, Language, <<">">>] ),
Language_start_new = binary:list_to_bin( [<<"<">>, <<"lang ">>, Language, <<">">>] ),
Fixed_lines = binary:replace( Binary, Language_start_old, Language_start_new, [global] ),
Language_stop_old = binary:list_to_bin( [<<"</">>, Language, <<">">>] ),
Language_stop_new = binary:list_to_bin( [<<"</">>, <<"lang>">>] ),
{Dict, binary:replace( Fixed_lines, Language_stop_old, Language_stop_new, [global] )}.
fix_language_tag_rosettacode_language( _Language_key, {ok, Language} ) -> Language;
fix_language_tag_rosettacode_language( Language_key, error ) -> Language_key.
loop( eof, Acc ) -> lists:reverse( Acc );
loop( Line, Acc ) -> loop( io:get_line(""), [Line | Acc] ).
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
toNumPlTxt[s_] := FromDigits[ToCharacterCode[s], 256];
fromNumPlTxt[plTxt_] := FromCharacterCode[IntegerDigits[plTxt, 256]];
enc::longmess = "Message '``' is too long for n = ``.";
enc[n_, _, mess_] /;
toNumPlTxt[mess] >= n := (Message[enc::longmess, mess, n]; $Failed);
enc[n_, e_, mess_] := PowerMod[toNumPlTxt[mess], e, n];
dec[n_, d_, en_] := fromNumPlTxt[PowerMod[en, d, n]];
text = "The cake is a lie!";
n = 9516311845790656153499716760847001433441357;
e = 65537;
d = 5617843187844953170308463622230283376298685;
en = enc[n, e, text];
de = dec[n, d, en];
Print["Text: '" <> text <> "'"];
Print["n = " <> IntegerString[n]];
Print["e = " <> IntegerString[e]];
Print["d = " <> IntegerString[d]];
Print["Numeric plaintext: " <> IntegerString[toNumPlTxt[text]]];
Print["Encoded: " <> IntegerString[en]];
Print["Decoded: '" <> de <> "'"];
|
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.
|
#Nim
|
Nim
|
import strutils, streams, strformat
# nimble install stint
import stint
const messages = ["PPAP", "I have a pen, I have a apple\nUh! Apple-pen!",
"I have a pen, I have pineapple\nUh! Pineapple-pen!",
"Apple-pen, pineapple-pen\nUh! Pen-pineapple-apple-pen\nPen-pineapple-apple-pen\nDance time!", "\a\0"]
const
n = u256("9516311845790656153499716760847001433441357")
e = u256("65537")
d = u256("5617843187844953170308463622230283376298685")
proc pcount(s: string, c: char): int{.inline.} =
for ch in s:
if ch != c:
break
result+=1
func powmodHexStr(s: string, key, divisor: UInt256): string{.inline.} =
toHex(powmod(UInt256.fromHex(s), key, divisor))
proc translate(hexString: string, key, divisor: UInt256,
encrypt = true): string =
var
strm = newStringStream(hexString)
chunk, residue, tempChunk: string
let chunkSize = len(toHex(divisor))
while true:
tempChunk = strm.peekStr(chunkSize-int(encrypt)*3)
if len(chunk) > 0:
if len(tempChunk) == 0:
if encrypt:
result&=powmodHexStr(pcount(chunk, '0').toHex(2)&align(chunk,
chunkSize-3, '0'), key, divisor)
else:
tempChunk = align(powmodHexStr(chunk, key, divisor), chunkSize-1, '0')
residue = tempChunk[2..^1].strip(trailing = false, chars = {'0'})
result&=align(residue, fromHex[int](tempChunk[0..1])+len(residue), '0')
break
result&=align(powmodHexStr(chunk, key, divisor), chunkSize-3+int(
encrypt)*3, '0')
discard strm.readStr(chunkSize-int(encrypt)*3)
chunk = tempChunk
strm.close()
for message in messages:
echo(&"plaintext:\n{message}")
var numPlaintext = message.toHex()
echo(&"numerical plaintext in hex:\n{numPlaintext}")
var ciphertext = translate(numPlaintext, e, n)
echo(&"ciphertext is: \n{ciphertext}")
var deciphertext = translate(ciphertext, d, n, false)
echo(&"deciphered numerical plaintext in hex is:\n{deciphertext}")
echo(&"deciphered plaintext is:\n{parseHexStr(deciphertext)}\n\n")
|
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.2B.2B
|
C++
|
#include <algorithm>
#include <ctime>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
srand(time(0));
unsigned int attributes_total = 0;
unsigned int count = 0;
int attributes[6] = {};
int rolls[4] = {};
while(attributes_total < 75 || count < 2)
{
attributes_total = 0;
count = 0;
for(int attrib = 0; attrib < 6; attrib++)
{
for(int roll = 0; roll < 4; roll++)
{
rolls[roll] = 1 + (rand() % 6);
}
sort(rolls, rolls + 4);
int roll_total = rolls[1] + rolls[2] + rolls[3];
attributes[attrib] = roll_total;
attributes_total += roll_total;
if(roll_total >= 15) count++;
}
}
cout << "Attributes generated : [";
cout << attributes[0] << ", ";
cout << attributes[1] << ", ";
cout << attributes[2] << ", ";
cout << attributes[3] << ", ";
cout << attributes[4] << ", ";
cout << attributes[5];
cout << "]\nTotal: " << attributes_total;
cout << ", Values above 15 : " << count;
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
|
#Prolog
|
Prolog
|
primes(N, L) :- numlist(2, N, Xs),
sieve(Xs, L).
sieve([H|T], [H|X]) :- H2 is H + H,
filter(H, H2, T, R),
sieve(R, X).
sieve([], []).
filter(_, _, [], []).
filter(H, H2, [H1|T], R) :-
( H1 < H2 -> R = [H1|R1], filter(H, H2, T, R1)
; H3 is H2 + H,
( H1 =:= H2 -> filter(H, H3, T, R)
; filter(H, H3, [H1|T], R) ) ).
|
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
|
#Factor
|
Factor
|
: find-index ( seq elt -- i )
'[ _ = ] find drop [ "Not found" throw ] unless* ; inline
: find-last-index ( seq elt -- i )
'[ _ = ] find-last drop [ "Not found" throw ] unless* ; inline
|
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.
|
#Bracmat
|
Bracmat
|
( get-page
= url type
. !arg:(?url.?type)
& sys$(str$("wget -q -O wget.out \"" !url \"))
& get$("wget.out",!type) { Type can be JSN, X ML, HT ML or just ML. }
)
& ( get-langs
= arr lang
. :?arr
& !arg:? (.h2.) ?arg (h2.?) ? { Only analyse part of page between the h2 elements. }
& whl
' ( !arg
: ?
( a
. ?
( title
. @(?:"Category:" ?):?lang
& !lang !arr:?arr
)
?
)
?arg
)
& !arr
)
& ( get-cats
= page langs list count pat li A Z
. !arg:(?page.?langs)
& 0:?list
& whl
' ( !langs:%?lang ?langs
& { Use macro substitution to create a fast pattern. }
' ( ?
(a.? (title.$lang) ?) { $lang is replaced by the actual language. }
?
(.a.)
@(?:? #?count " " ?)
)
: (=?pat)
& ( !page
: ?A
( (li.) ?li (.li.) ?Z
& !li:!pat
)
& !A !Z:?page { Remove found item from page. (Not necessary at all.)}
& !count
| 0 { The language has no examples. }
.
)
\L !lang { Bracmat normalizes a\Lx+b\Ly+a\Lz to a\L(x*z)+b\Ly, so }
+ !list { it's easy to collect categories with the same count. }
: ?list
)
& !list
)
& get-cats
$ ( get-page
$ ( "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000"
. HT,ML
)
. get-langs
$ ( get-page
$ ( "http://rosettacode.org/wiki/Category:Programming_Languages"
. HT ML
)
)
)
: ?cats
& :?list
& whl
' ( !cats:(?count.)\L?tiedcats+?cats
& :?ties
& whl
' ( !tiedcats:@(?:"Category:" ?name)*?tiedcats
& !ties !name:?ties
)
& (!count.!ties) !list:?list
)
& 1:?rank
& whl
' ( !rank:?tiedRank
& !list:(?count.?ties) ?list
& whl
' ( !ties:%?name ?ties
& @(!tiedRank:? [?len) { We want some padding for the highest ranks. }
& @(" ":? [!len ?sp) { Skip blanks up to the length of the rank. }
& out$(str$(!sp !tiedRank ". " !count " - " !name))
& 1+!rank:?rank
)
)
& ;
|
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.
|
#APL
|
APL
|
∇ ret←RLL rll;count
[1] count←∣2-/((1,(2≠/rll),1)×⍳1+⍴rll)~0
[2] ret←(⍕count,¨(1,2≠/rll)/rll)~' '
∇
|
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
|
#360_Assembly
|
360 Assembly
|
ROT13 CSECT
USING ROT13,R15 use calling register
XPRNT CC,L'CC
TR CC,TABLE translate
XPRNT CC,L'CC
TR CC,TABLE translate
XPRNT CC,L'CC
BR R14 return to caller
CC DC CL10'{NOWHERE!}'
TABLE DC CL64' '
* 0123456789ABCDEF
DC CL16' .<(+|' X'4.'
DC CL16' !$*);^' X'5.'
DC CL16'&& ,%_>?' X'6.'
DC CL16'-/ `:#@''="' X'7.'
DC CL16' nopqrstuv ' X'8.'
DC CL16' wxyzabcde ' X'9.'
DC CL16' ~fghijklm [ ' X'A.'
DC CL16' ] ' X'B.'
DC CL16'{NOPQRSTUV ' X'C.'
DC CL16'}WXYZABCDE ' X'D.'
DC CL16'\ FGHIJKLM ' X'E.'
DC CL16'0123456789 ' X'F.'
* 0123456789ABCDEF
YREGS
END ROT13
|
http://rosettacode.org/wiki/Runge-Kutta_method
|
Runge-Kutta method
|
Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
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 }
|
#Crystal
|
Crystal
|
y, t = 1, 0
while t <= 10
k1 = t * Math.sqrt(y)
k2 = (t + 0.05) * Math.sqrt(y + 0.05 * k1)
k3 = (t + 0.05) * Math.sqrt(y + 0.05 * k2)
k4 = (t + 0.1) * Math.sqrt(y + 0.1 * k3)
printf("y(%4.1f)\t= %12.6f \t error: %12.6e\n", t, y, (((t**2 + 4)**2 / 16) - y )) if (t.round - t).abs < 1.0e-5
y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6
t += 0.1
end
|
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.
|
#Stata
|
Stata
|
copy "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" categ.html, replace
import delimited categ.html, delim("@") enc("utf-8") clear
keep if ustrpos(v1,"/wiki/Category:") & ustrpos(v1,"_User")
gen i = ustrpos(v1,"href=")
gen j = ustrpos(v1,char(34),i+1)
gen k = ustrpos(v1,char(34),j+1)
gen s = usubstr(v1,j+7,k-j-7)
replace i = ustrpos(v1,"title=")
replace j = ustrpos(v1,">",i+1)
replace k = ustrpos(v1," User",j+1)
gen lang = usubstr(v1,j+1,k-j)
keep s lang
gen users=.
forval i=1/`c(N)' {
local s
preserve
copy `"https://rosettacode.org/mw/index.php?title=`=s[`i']'&redirect=no"' `i'.html, replace
import delimited `i'.html, delim("@") enc("utf-8") clear
count if ustrpos(v1,"/wiki/User")
local m `r(N)'
restore
replace users=`m' in `i'
erase `i'.html
}
drop s
gsort -users lang
compress
leftalign
list in f/50
save rc_users, replace
|
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.
|
#Wren
|
Wren
|
/* rc_rank_languages_by_number_of_users.wren */
import "./pattern" for Pattern
import "./fmt" for Fmt
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
foreign class Buffer {
construct new() {} // C will allocate buffer of a suitable size
foreign value // returns buffer contents as a string
}
foreign class Curl {
construct easyInit() {}
foreign easySetOpt(opt, param)
foreign easyPerform()
foreign easyCleanup()
}
var curl = Curl.easyInit()
var getContent = Fn.new { |url|
var buffer = Buffer.new()
curl.easySetOpt(CURLOPT_URL, url)
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C
curl.easySetOpt(CURLOPT_WRITEDATA, buffer)
curl.easyPerform()
return buffer.value
}
var p = Pattern.new(" User\">[+1^<]<//a>\u200f\u200e ([#13/d] member~s)")
var url = "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=4000"
var content = getContent.call(url)
var matches = p.findAll(content)
var over100s = []
for (m in matches) {
var numUsers = Num.fromString(m.capsText[1])
if (numUsers >= 100) {
var language = m.capsText[0][0..-6]
over100s.add([language, numUsers])
}
}
over100s.sort { |a, b| a[1] > b[1] }
System.print("Languages with at least 100 users as at 4 January, 2022:")
var rank = 0
var lastScore = 0
var lastRank = 0
for (i in 0...over100s.count) {
var pair = over100s[i]
var eq = " "
rank = i + 1
if (lastScore == pair[1]) {
eq = "="
rank = lastRank
} else {
lastScore = pair[1]
lastRank = rank
}
Fmt.print("$-2d$s $-11s $d", rank, eq, pair[0], pair[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.
|
#Raku
|
Raku
|
use MONKEY-SEE-NO-EVAL;
sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { EVAL $code } }
say eval_with_x('3 * x', 5, 10); # Says "15".
say eval_with_x('3 * x', 5, 10, 50); # Says "105".
|
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.
|
#REBOL
|
REBOL
|
prog: [x * 2]
fn: func [x] [do bind prog 'x]
a: fn 2
b: fn 4
subtract b a
|
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.
|
#Ceylon
|
Ceylon
|
class Symbol(symbol) {
shared String symbol;
string => symbol;
}
abstract class Token()
of DataToken | leftParen | rightParen {}
abstract class DataToken(data)
of StringToken | IntegerToken | FloatToken | SymbolToken
extends Token() {
shared String|Integer|Float|Symbol data;
string => data.string;
}
class StringToken(String data) extends DataToken(data) {}
class IntegerToken(Integer data) extends DataToken(data) {}
class FloatToken(Float data) extends DataToken(data) {}
class SymbolToken(Symbol data) extends DataToken(data) {}
object leftParen extends Token() {
string => "(";
}
object rightParen extends Token() {
string => ")";
}
class Tokens(String input) satisfies {Token*} {
shared actual Iterator<Token> iterator() => object satisfies Iterator<Token> {
variable value index = 0;
shared actual Token|Finished next() {
while(exists nextChar = input[index], nextChar.whitespace) {
index++;
}
if(index >= input.size) {
return finished;
}
assert(exists char = input[index]);
if(char == '(') {
index++;
return leftParen;
}
if(char == ')') {
index++;
return rightParen;
}
if(char == '"') {
value builder = StringBuilder();
while(exists nextChar = input[++index]) {
if(nextChar == '"') {
index++;
break;
}
if(nextChar == '\\') {
if(exists nextNextChar = input[++index]) {
switch(nextNextChar)
case('\\') {
builder.append("\\");
}
case('t') {
builder.append("\t");
}
case('n') {
builder.append("\n");
}
case('"') {
builder.append("\"");
}
else {
throw Exception("unknown escaped character");
}
} else {
throw Exception("unclosed string");
}
} else {
builder.appendCharacter(nextChar);
}
}
return StringToken(builder.string);
}
value builder = StringBuilder();
while(exists nextChar = input[index], !nextChar.whitespace && nextChar != '(' && nextChar != ')') {
builder.appendCharacter(nextChar);
index++;
}
value string = builder.string;
if(is Integer int = Integer.parse(string)) {
return IntegerToken(int);
} else if(is Float float = Float.parse(string)) {
return FloatToken(float);
} else {
return SymbolToken(Symbol(string));
}
}
};
}
abstract class Node() of Atom | Group {}
class Atom(data) extends Node() {
shared String|Integer|Float|Symbol data;
string => data.string;
}
class Group() extends Node() satisfies {Node*} {
shared variable Node[] nodes = [];
string => nodes.string;
shared actual Iterator<Node> iterator() => nodes.iterator();
}
Node buildTree(Tokens tokens) {
[Group, Integer] recursivelyBuild(Token[] tokens, variable Integer index = 0) {
value result = Group();
while(exists token = tokens[index]) {
switch (token)
case (leftParen) {
value [newNode, newIndex] = recursivelyBuild(tokens, index + 1);
index = newIndex;
result.nodes = result.nodes.append([newNode]);
}
case (rightParen) {
return [result, index];
}
else {
result.nodes = result.nodes.append([Atom(token.data)]);
}
index++;
}
return [result, index];
}
value root = recursivelyBuild(tokens.sequence())[0];
return root.first else Group();
}
void prettyPrint(Node node, Integer indentation = 0) {
void paddedPrint(String s) => print(" ".repeat(indentation) + s);
if(is Atom node) {
paddedPrint(node.string);
} else {
paddedPrint("(");
for(n in node.nodes) {
prettyPrint(n, indentation + 2);
}
paddedPrint(")");
}
}
shared void run() {
value tokens = Tokens("""((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))""");
print(tokens);
value tree = buildTree(tokens);
prettyPrint(tree);
}
|
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
|
#F.23
|
F#
|
open System
open System.Text.RegularExpressions
[<EntryPoint>]
let main argv =
let langs = [| "foo"; "foo 2"; "bar"; "baz" |]; // An array of (pseudo) languages we handle
let regexStringAlternationOfLanguageNames = String.Join("|", (Array.map Regex.Escape langs))
let regexForOldLangSyntax =
new Regex(String.Format("""
< # Opening of a tag.
( # Group alternation of 2 cases
( # Group for alternation of 2 cases with a language name
(?<CloseMarker>/) # Might be a closing tag,
| # Or
code\s # an old <code ...> tag
)? # End of alternation; optional
\b(?<Lang>{0})\b # Followed by the captured Language alternation
| # Or
(?<CloseMarker>/code)# An old </code> end tag
) # End of group
> # The final tag closing
""", regexStringAlternationOfLanguageNames),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.ExplicitCapture)
let replaceEvaluator (m : Match) =
if m.Groups.Item("CloseMarker").Length > 0 then "</" + "lang>"
else "<lang " + m.Groups.Item("Lang").Value + ">"
printfn "%s" (regexForOldLangSyntax.Replace(Console.In.ReadToEnd(), replaceEvaluator))
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 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.
|
#PARI.2FGP
|
PARI/GP
|
stigid(V,b)=subst(Pol(V),'x,b); \\ inverse function digits(...)
n = 9516311845790656153499716760847001433441357;
e = 65537;
d = 5617843187844953170308463622230283376298685;
text = "Rosetta Code"
inttext = stigid(Vecsmall(text),256) \\ message as an integer
encoded = lift(Mod(inttext, n) ^ e) \\ encrypted message
decoded = lift(Mod(encoded, n) ^ d) \\ decrypted message
message = Strchr(digits(decoded, 256)) \\ readable message
|
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.
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
RPGGEN
set attr = $lb("") ; empty list to start
write "Rules:",!,"1.) Total of 6 attributes must be at least 75.",!,"2.) At least two scores must be 15 or more.",!
; loop until valid result
do {
; loop through 6 attributes
for i = 1:1:6 {
set (low, dice, keep) = ""
; roll 4 dice each time
for j = 1:1:4 {
set roll = $r(6) + 1
set dice = dice + roll
if (roll < low) || (low = "") {
set low = roll
}
} ; 4 dice rolls per attribute
set keep = (dice - low)
set $list(attr,i) = keep
} ; 6 attributes
; loop the ending list
set (tot,bigs) = 0
for i = 1:1:$listlength(attr) {
set cur = $listget(attr,i)
set tot = tot + cur
if (cur >= 15) {
set bigs = bigs + 1
}
}
; analyze results
write !,"Scores: "_$lts(attr)
set result = $select((tot < 75) && (bigs < 2):0,tot < 75:1,bigs < 2:2,1:3)
write !,?5,$case(result,
0:"Total "_tot_" too small and not enough attributes ("_bigs_") >= 15.",
1:"Total "_tot_" too small.",
2:"Need 2 or more attributes >= 15, only have "_bigs_".",
3:"Total "_tot_" and "_bigs_ " attributes >=15 are sufficient.")
} while (result '= 3)
quit
|
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.
|
#CLU
|
CLU
|
% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
% pclu -merge $CLUHOME/lib/misc.lib -compile rpg_gen.clu
% Seed the random number generator with the current time
init_rng = proc ()
d: date := now()
seed: int := ((d.hour*60) + d.minute)*60 + d.second
random$seed(seed)
end init_rng
character = cluster is generate
rep = null
% Roll a die
roll_die = proc () returns (int)
return (1 + random$next(6))
end roll_die
% Roll four dice and get the sum of the highest three rolls
roll_four_times = proc () returns (int)
lowest: int := 7 % higher than any dice roll
sum: int := 0
for i: int in int$from_to(1,4) do
roll: int := roll_die()
sum := sum + roll
if roll < lowest then lowest := roll end
end
return (sum - lowest)
end roll_four_times
% Try to generate a character by rolling six values
try_generate = proc () returns (sequence[int])
rolls: sequence[int] := sequence[int]$[]
for i: int in int$from_to(1,6) do
rolls := sequence[int]$addh(rolls, roll_four_times())
end
return (rolls)
end try_generate
% See if a character is valid
valid = proc (c: sequence[int]) returns (bool)
total: int := 0
at_least_15: int := 0
for i: int in sequence[int]$elements(c) do
total := total + i
if i >= 15 then at_least_15 := at_least_15 + 1 end
end
return (total >= 75 & at_least_15 >= 2)
end valid
% Generate a character
generate = proc () returns (sequence[int])
while true do
c: sequence[int] := try_generate()
if valid(c) then return(c) end
end
end generate
end character
% Generate a character and display the six values
start_up = proc ()
po: stream := stream$primary_output()
init_rng()
hero: sequence[int] := character$generate()
for stat: int in sequence[int]$elements(hero) do
stream$putright(po, int$unparse(stat), 4)
end
end start_up
|
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
|
#PureBasic
|
PureBasic
|
For n=2 To Sqr(lim)
If Nums(n)=0
m=n*n
While m<=lim
Nums(m)=1
m+n
Wend
EndIf
Next n
|
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
|
#Forth
|
Forth
|
include lib/row.4th
create haystack
," Zig" ," Zag" ," Wally" ," Ronald" ," Bush" ," Krusty" ," Charlie"
," Bush" ," Boz" ," Zag" NULL ,
does>
dup >r 1 string-key row 2>r type 2r> ." is "
if r> - ." at " . else r> drop drop ." not found" then cr
;
s" Washington" haystack s" Bush" haystack
|
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
|
Rosetta Code/Rank languages by popularity
|
Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http://www.rosettacode.org/w/api.php?action=query&"
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000";
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
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.
|
#AppleScript
|
AppleScript
|
------------------ RUN-LENGTH ENCODING -----------------
-- encode :: String -> String
on encode(s)
script go
on |λ|(cs)
if {} ≠ cs then
set c to text 1 of cs
set {chunk, residue} to span(eq(c), rest of cs)
(c & (1 + (length of chunk)) as string) & |λ|(residue)
else
""
end if
end |λ|
end script
|λ|(characters of s) of go
end encode
-- decode :: String -> String
on decode(s)
script go
on |λ|(cs)
if {} ≠ cs then
set {ds, residue} to span(my isDigit, rest of cs)
set n to (ds as string) as integer
replicate(n, item 1 of cs) & |λ|(residue)
else
""
end if
end |λ|
end script
|λ|(characters of s) of go
end decode
--------------------------- TEST -------------------------
on run
set src to ¬
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
set encoded to encode(src)
set decoded to decode(encoded)
unlines({encoded, decoded, src = decoded})
end run
-------------------- GENERIC FUNCTIONS -------------------
-- eq :: a -> a -> Bool
on eq(a)
-- True if a and b are equivalent in terms
-- of the AppleScript (=) operator.
script go
on |λ|(b)
a = b
end |λ|
end script
end eq
-- isDigit :: Char -> Bool
on isDigit(c)
set n to (id of c)
48 ≤ n and 57 ≥ n
end isDigit
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> String -> String
on replicate(n, s)
-- Egyptian multiplication - progressively doubling a list,
-- appending stages of doubling to an accumulator where needed
-- for binary assembly of a target length
script p
on |λ|({n})
n ≤ 1
end |λ|
end script
script f
on |λ|({n, dbl, out})
if (n mod 2) > 0 then
set d to out & dbl
else
set d to out
end if
{n div 2, dbl & dbl, d}
end |λ|
end script
set xs to |until|(p, f, {n, s, ""})
item 2 of xs & item 3 of xs
end replicate
-- span :: (a -> Bool) -> [a] -> ([a], [a])
on span(p, xs)
-- The longest (possibly empty) prefix of xs
-- that contains only elements satisfying p,
-- tupled with the remainder of xs.
-- span(p, xs) eq (takeWhile(p, xs), dropWhile(p, xs))
script go
property mp : mReturn(p)
on |λ|(vs)
if {} ≠ vs then
set x to item 1 of vs
if |λ|(x) of mp then
set {ys, zs} to |λ|(rest of vs)
{{x} & ys, zs}
else
{{}, vs}
end if
else
{{}, {}}
end if
end |λ|
end script
|λ|(xs) of go
end span
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set v to x
set mp to mReturn(p)
set mf to mReturn(f)
repeat until mp's |λ|(v)
set v to mf's |λ|(v)
end repeat
v
end |until|
|
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
|
#6502_Assembly
|
6502 Assembly
|
buffer = $fa ; or anywhere in zero page that's good
maxpage = $95 ; if non-terminated that's bad
org $1900
.rot13
stx buffer
sty buffer+1
ldy #0
beq readit
.loop cmp #$7b ; high range
bcs next ; >= {
cmp #$41 ; low range
bcc next ; < A
cmp #$4e
bcc add13 ; < N
cmp #$5b
bcc sub13set ; < [
cmp #$61
bcc next ; < a
cmp #$6e
bcs sub13 ; >= n
.add13 adc #13 ; we only get here via bcc; so clc not needed
bne storeit
.sub13set sec ; because we got here via bcc; so sec is needed
.sub13 sbc #13 ; we can get here via bcs; so sec not needed
.storeit sta (buffer),y
.next iny
bne readit
ldx buffer+1
cpx maxpage
beq done
inx
stx buffer+1
.readit lda (buffer),y ; quit on ascii 0
bne loop
.done rts
.end
save "rot-13", rot13, 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 }
|
#D
|
D
|
import std.stdio, std.math, std.typecons;
alias FP = real;
alias FPs = Typedef!(FP[101]);
void runge(in FP function(in FP, in FP)
pure nothrow @safe @nogc yp_func,
ref FPs t, ref FPs y, in FP dt) pure nothrow @safe @nogc {
foreach (immutable n; 0 .. t.length - 1) {
immutable FP
dy1 = dt * yp_func(t[n], y[n]),
dy2 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy1 / 2.0),
dy3 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy2 / 2.0),
dy4 = dt * yp_func(t[n] + dt, y[n] + dy3);
t[n + 1] = t[n] + dt;
y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0;
}
}
FP calc_err(in FP t, in FP calc) pure nothrow @safe @nogc {
immutable FP actual = (t ^^ 2 + 4.0) ^^ 2 / 16.0;
return abs(actual - calc);
}
void main() {
enum FP dt = 0.10;
FPs t_arr, y_arr;
t_arr[0] = 0.0;
y_arr[0] = 1.0;
runge((t, y) => t * y.sqrt, t_arr, y_arr, dt);
foreach (immutable i; 0 .. t_arr.length)
if (i % 10 == 0)
writefln("y(%.1f) = %.8f Error: %.6g",
t_arr[i], y_arr[i],
calc_err(t_arr[i], y_arr[i]));
}
|
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.
|
#zkl
|
zkl
|
const MIN_USERS=60;
var [const] CURL=Import("zklCurl"), YAJL=Import("zklYAJL")[0];
fcn rsGet{
continueValue,r,curl := "",List, CURL();
do{ // eg 5 times
page:=("http://rosettacode.org/mw/api.php?action=query"
"&generator=categorymembers&prop=categoryinfo"
"&gcmtitle=Category%%3ALanguage%%20users"
"&rawcontinue=&format=json&gcmlimit=350"
"%s").fmt(continueValue);
page=curl.get(page);
page=page[0].del(0,page[1]); // get rid of HTML header
json:=YAJL().write(page).close();
json["query"]["pages"].pump(r.append,'wrap(x){ x=x[1];
//("2708",Dictionary(title:Category:C User,...,categoryinfo:D(pages:373,size:373,...)))
// or title:SmartBASIC
if((pgs:=x.find("categoryinfo")) and (pgs=pgs.find("pages")) and
pgs>=MIN_USERS)
return(pgs,x["title"].replace("Category:","").replace(" User",""));
return(Void.Skip);
});
if(continueValue=json.find("query-continue",""))
continueValue=String("&gcmcontinue=",
continueValue["categorymembers"]["gcmcontinue"]);
}while(continueValue);
r
}
allLangs:=rsGet();
allLangs=allLangs.sort(fcn(a,b){ a[0]>b[0] });
println("========== ",Time.Date.prettyDay()," ==========");
foreach n,pgnm in ([1..].zip(allLangs))
{ println("#%3d with %4s users: %s".fmt(n,pgnm.xplode())) }
|
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.
|
#REXX
|
REXX
|
/*REXX program demonstrates a run─time evaluation of an expression (entered at run─time)*/
say '──────── enter the 1st expression to be evaluated:'
parse pull x /*obtain an expression from the console*/
y.1= x /*save the provided expression for X. */
say
say '──────── enter the 2nd expression to be evaluated:'
parse pull x /*obtain an expression from the console*/
y.2= x /*save the provided expression for X. */
say
say '──────── 1st expression entered is: ' y.1
say '──────── 2nd expression entered is: ' y.2
say
interpret 'say "──────── value of the difference is: "' y.2 "-" '('y.1")" /* ◄─────┐ */
/* │ */
/* │ */
/*subtract 1st exp. from the 2nd──►──┘ */
drop x /*X var. is no longer a global variable*/
exit 0 /*stick a fork in it, we're all done. */
|
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.
|
#CoffeeScript
|
CoffeeScript
|
# This code works with Lisp-like s-expressions.
#
# We lex tokens then do recursive descent on the tokens
# to build our data structures.
sexp = (data) ->
# Convert a JS data structure to a string s-expression. A sexier version
# would remove quotes around strings that don't need them.
s = ''
if Array.isArray data
children = (sexp elem for elem in data).join ' '
'(' + children + ')'
else
return JSON.stringify data
parse_sexp = (sexp) ->
tokens = lex_sexp sexp
i = 0
_parse_list = ->
i += 1
arr = []
while i < tokens.length and tokens[i].type != ')'
arr.push _parse()
if i < tokens.length
i += 1
else
throw Error "missing end paren"
arr
_guess_type = (word) ->
# This is crude, doesn't handle all forms of floats.
if word.match /^\d+\.\d+$/
parseFloat(word)
else if word.match /^\d+/
parseInt(word)
else
word
_parse_word = ->
token = tokens[i]
i += 1
if token.type == 'string'
token.word
else
_guess_type token.word
_parse = ->
return undefined unless i < tokens.length
token = tokens[i]
if token.type == '('
_parse_list()
else
_parse_word()
exp = _parse()
throw Error "premature termination" if i < tokens.length
exp
lex_sexp = (sexp) ->
is_whitespace = (c) -> c in [' ', '\t', '\n']
i = 0
tokens = []
test = (f) ->
return false unless i < sexp.length
f(sexp[i])
eat_char = (c) ->
tokens.push
type: c
i += 1
eat_whitespace = ->
i += 1
while test is_whitespace
i += 1
eat_word = ->
token = c
i += 1
word_char = (c) ->
c != ')' and !is_whitespace c
while test word_char
token += sexp[i]
i += 1
tokens.push
type: "word"
word: token
eat_quoted_word = ->
start = i
i += 1
token = ''
while test ((c) -> c != '"')
if sexp[i] == '\\'
i += 1
throw Error("escaping error") unless i < sexp.length
token += sexp[i]
i += 1
if test ((c) -> c == '"')
tokens.push
type: "string"
word: token
i += 1
else
throw Error("end quote missing #{sexp.substring(start, i)}")
while i < sexp.length
c = sexp[i]
if c == '(' or c == ')'
eat_char c
else if is_whitespace c
eat_whitespace()
else if c == '"'
eat_quoted_word()
else
eat_word()
tokens
do ->
input = """
((data "quoted data with escaped \\"" 123 4.5 "14")
(data (!@# (4.5) "(more" "data)")))
"""
console.log "input:\n#{input}\n"
output = parse_sexp(input)
pp = (data) -> JSON.stringify data, null, ' '
console.log "output:\n#{pp output}\n"
console.log "round trip:\n#{sexp output}\n"
|
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
|
#Go
|
Go
|
package main
import "fmt"
import "io/ioutil"
import "log"
import "os"
import "regexp"
import "strings"
func main() {
err := fix()
if err != nil {
log.Fatalln(err)
}
}
func fix() (err error) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
out, err := Lang(string(buf))
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func Lang(in string) (out string, err error) {
reg := regexp.MustCompile("<[^>]+>")
out = reg.ReplaceAllStringFunc(in, repl)
return out, nil
}
func repl(in string) (out string) {
if in == "</code>" {
// Change </code> to </ lang>
return "</"+"lang>"
}
// mid is the content in between '<' and '>'.
mid := in[1 : len(in)-1]
// thanks, random lua guy
var langs = []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",
}
for _, lang := range langs {
if mid == lang {
// Change <%s> to <lang %s>
return fmt.Sprintf("<lang %s>", lang)
}
if strings.HasPrefix(mid, "/") {
if mid[len("/"):] == lang {
// Change </%s> to </ lang>
return "</"+"lang>"
}
}
if strings.HasPrefix(mid, "code ") {
if mid[len("code "):] == lang {
// Change <code %s> to <lang %s>
return fmt.Sprintf("<lang %s>", lang)
}
}
}
return in
}
|
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.
|
#Perl
|
Perl
|
use bigint;
$n = 9516311845790656153499716760847001433441357;
$e = 65537;
$d = 5617843187844953170308463622230283376298685;
package Message {
my @alphabet;
push @alphabet, $_ for 'A' .. 'Z', ' ';
my $rad = +@alphabet;
$code{$alphabet[$_]} = $_ for 0..$rad-1;
sub encode {
my($t) = @_;
my $cnt = my $sum = 0;
for (split '', reverse $t) {
$sum += $code{$_} * $rad**$cnt;
$cnt++;
}
$sum;
}
sub decode {
my($n) = @_;
my(@i);
while () {
push @i, $n % $rad;
last if $n < $rad;
$n = int $n / $rad;
}
reverse join '', @alphabet[@i];
}
sub expmod {
my($a, $b, $n) = @_;
my $c = 1;
do {
($c *= $a) %= $n if $b % 2;
($a *= $a) %= $n;
} while ($b = int $b/2);
$c;
}
}
my $secret_message = "ROSETTA CODE";
$numeric_message = Message::encode $secret_message;
$numeric_cipher = Message::expmod $numeric_message, $e, $n;
$text_cipher = Message::decode $numeric_cipher;
$numeric_cipher2 = Message::encode $text_cipher;
$numeric_message2 = Message::expmod $numeric_cipher2, $d, $n;
$secret_message2 = Message::decode $numeric_message2;
print <<"EOT";
Secret message is $secret_message
Secret message in integer form is $numeric_message
After exponentiation with public exponent we get: $numeric_cipher
This turns into the string $text_cipher
If we re-encode it in integer form we get $numeric_cipher2
After exponentiation with SECRET exponent we get: $numeric_message2
This turns into the string $secret_message2
EOT
|
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.
|
#Commodore_BASIC
|
Commodore BASIC
|
100 rem rpg character roller
110 rem rosetta code - commodore basic
120 dim di(3):rem dice
130 dim at(5),at$(5):rem attributes as follows:
140 at$(0)="Strength"
150 at$(1)="Dexterity"
160 at$(2)="Constitution"
170 at$(3)="Intelligence"
180 at$(4)="Wisdom"
190 at$(5)="Charisma"
200 pt=0:sa=0:rem points total and number of strong attributes (15+)
210 print chr$(147);chr$(14);chr$(29);chr$(17);"Rolling..."
220 for ai=0 to 5:rem attribute index
230 for i=0 to 3:di(i)=int(rnd(.)*6)+1:next i
240 gosub 450
250 dt=0:rem dice total
260 for i=0 to 2:dt=dt+di(i):next i:rem take top 3
270 at(ai)=dt:pt=pt+dt
280 if dt>=15 then sa=sa+1
290 next ai
300 if pt<75 or sa<2 then goto 200
310 print chr$(147);"Character Attributes:"
320 print
330 for ai=0 to 5
340 print spc(13-len(at$(ai)));at$(ai);":";tab(14);at(ai)
350 next ai
360 print
370 print " Total:";tab(14);pt
380 print
390 print "Do you accept? ";
400 get k$:if k$<>"y" and k$<>"n" then 400
410 print k$
420 if k$="n" then goto 200
430 print:print "Excellent. Good luck on your adventure!"
440 end
450 rem "sort" dice - really just put smallest one last
460 for x=0 to 2
470 if di(x)<di(x+1) then t=di(x):di(x)=di(x+1):di(x+1)=t
480 next x
490 return
|
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
|
#Python
|
Python
|
def eratosthenes2(n):
multiples = set()
for i in range(2, n+1):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
print(list(eratosthenes2(100)))
|
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
|
#Fortran
|
Fortran
|
program main
implicit none
character(len=7),dimension(10) :: haystack = [ &
'Zig ',&
'Zag ',&
'Wally ',&
'Ronald ',&
'Bush ',&
'Krusty ',&
'Charlie',&
'Bush ',&
'Boz ',&
'Zag ']
call find_needle('Charlie')
call find_needle('Bush')
contains
subroutine find_needle(needle)
implicit none
character(len=*),intent(in) :: needle
integer :: i
do i=1,size(haystack)
if (needle==haystack(i)) then
write(*,'(A,I4)') trim(needle)//' found at index:',i
return
end if
end do
write(*,'(A)') 'Error: '//trim(needle)//' not found.'
end subroutine find_needle
end program main
|
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.
|
#C.23
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json");
string get2 = new WebClient().DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000");
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
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.
|
#Arturo
|
Arturo
|
runlengthEncode: function [s][
join map chunk split s => [&] 'x ->
(to :string size x) ++ first x
]
runlengthDecode: function [s][
result: new ""
loop (chunk split s 'x -> positive? size match x {/\d+/}) [a,b] ->
'result ++ repeat first b to :integer join to [:string] a
return result
]
str: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
encoded: runlengthEncode str
print ["encoded:" encoded]
decoded: runlengthDecode encoded
print ["decoded:" decoded]
if decoded=str -> print "\nSuccess!"
|
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
|
#ACL2
|
ACL2
|
(include-book "arithmetic-3/top" :dir :system)
(defun char-btn (c low high)
(and (char>= c low)
(char<= c high)))
(defun rot-13-cs (cs)
(cond ((endp cs) nil)
((or (char-btn (first cs) #\a #\m)
(char-btn (first cs) #\A #\M))
(cons (code-char (+ (char-code (first cs)) 13))
(rot-13-cs (rest cs))))
((or (char-btn (first cs) #\n #\z)
(char-btn (first cs) #\N #\Z))
(cons (code-char (- (char-code (first cs)) 13))
(rot-13-cs (rest cs))))
(t (cons (first cs) (rot-13-cs (rest cs))))))
(defun rot-13 (s)
(coerce (rot-13-cs (coerce s 'list)) 'string))
|
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 }
|
#Dart
|
Dart
|
import 'dart:math' as Math;
num RungeKutta4(Function f, num t, num y, num dt){
num k1 = dt * f(t,y);
num k2 = dt * f(t+0.5*dt, y + 0.5*k1);
num k3 = dt * f(t+0.5*dt, y + 0.5*k2);
num k4 = dt * f(t + dt, y + k3);
return y + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
}
void main(){
num t = 0;
num dt = 0.1;
num tf = 10;
num totalPoints = ((tf-t)/dt).floor()+1;
num y = 1;
Function f = (num t, num y) => t * Math.sqrt(y);
Function actual = (num t) => (1/16) * (t*t+4)*(t*t+4);
for (num i = 0; i <= totalPoints; i++){
num relativeError = (actual(t) - y)/actual(t);
if (i%10 == 0){
print('y(${t.round().toStringAsPrecision(3)}) = ${y.toStringAsPrecision(11)} Error = ${relativeError.toStringAsPrecision(11)}');
}
y = RungeKutta4(f, t, y, dt);
t += dt;
}
}
|
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 }
|
#EDSAC_order_code
|
EDSAC order code
|
[Demo of EDSAC library subroutine G1: Runge-Kutta solution of differential equations.
Full description is in Wilkes, Wheeler & Gill, 1951 edn, pages 32-34, 86-87, 132-134.
Before using G1, we need to fix n, m, a, b, c, d, as defined in WWG pages 86-87:
n = number of equations (2 for the Rosetta Code example).
2^m = multiplier for the hy', as large as possible without causing numeric overflow;
with the scaling chosen here, m = 5.
Variables y are stored in n consecutive long locations, the last of which is aD.
Scaled derivatives (2^m)hy' in n consecutive long locations, the last of which is bD.
G1 uses working variables in n consecutive long locations, the last of which is cD.
d = address of user-supplied auxiliary subroutine, which calculates the (2^m)hy'.
For convenience, keep G1 and its storage together. Start at (say) 400 and place:
variables y at 400D, 402D;
scaled derivatives at 404D, 406D;
workspace for G1 at 408D, 410D;
G1 itself at 412.
If the base address is placed in location 51 at load time, all the above
addresses can be accessed via the G parameter:]
T 51 K
P 400 F
[Now set up the 6 preset parameters specified in WWG:]
T 45 K
P 2#G [H parameter: P a D]
P 4 F [N parameter: P 2n F]
P 4 F [M parameter: P (b-a) F, or V (2048-a+b) F if a > b]
P 4 F [& parameter: P (c-b) F, or V (2048-b+c) F if b > c]
P 8 F [L parameter: P 2^(m-2) F]
P 300 F [X parameter: P d F]
[For other addresses in the program we can optionally use some more parameters:]
T 52 K
P 120 F [A parameter: main routine]
P 56 F [B parameter: print subroutine P1 from EDSAC library]
P 350 F [C parameter: constants for Rosetta code example]
P 78 F [V parameter: square root subroutine]
[Library subroutine to read constants; runs at load time and is then overwritten.
R5, for decimal fractions, seems to be unavailable (lost?), so the values are
here read in as 35-bit integers (i.e. times 2^34) by R2.
Values are: 0.001, initial value of y
(2^23)/(10^7) and 25/(2^10) for use in calculations
0.5/(10^9) for rounding to 9 d.p. (print routine P1 doesn't do this)]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
T#C
17179869F14411518808F419430400F9#
TZ
[Library subroutine M3; prints header at load time and is then overwritten.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*SCALED!FOR!EDSAC@&!!TIME!!!!!!!!!Y!VIA!RK!!!!!Y!DIRECT@&
....PK [end text with some blank tape]
[Runge-Kutta: auxiliary subroutine to calculate (2^m)*h*(dy1/dt) and (2^m)*h*(dy2/dt)
from y1, y2, where y1 is the function y in Rosetta Code (but scaled) and y2 = t.
For the Rosetta code example we're using m = 5, h = 2^(-7)]
E25K TX GK
A3F T20@ [set up return as usual]
H2#G V2#G TD [acc := t^2, temp store in 0D]
H#G VD LD YF TD [y1 times t^2, shift left, round, temp store in 0D]
H2#C VD YF T4D [times (2^23)/(10^7), round, to 4D for square root]
[14] A14@ GV A4D T4#G [call square root, result in 4D, copy to (2^m)hy']
A21@ T6#G [1/4, i.e. (2^m)h with m and h as above, to (2^m)ht']
[20] ZF [overwritten by jump back to caller]
[21] RF [constant 1/4]
[Main routine, with two subroutines in the same address block as the main routine.]
E25K TA GK
[0] #F [figures shift on teleprinter]
[1] MF [decimal point (in figures mode)]
[2] !F @F &F [space, carriage return, line feed,]
[5] K4096F [null char]
[6] P100F [constant: nr of Runge-Kutta steps (in address field)]
[7] PF [negative count of Runge-Kutta steps]
[8] P10F [constant: number of steps between printed values]
[9] PF [negative count of steps between printed values]
[Enter with acc = 0]
[10] O@ [set teleprinter to figures]
S6@ T7@ [init negative count of R-K steps]
S8@ T9@ [init negative count of print steps]
[Before using library subroutine G1, clear its working registers (WWG page 33)]
T8#G T10#G
[Set up initial values of y1 and y2 (where y2 = t)]
A#C T#G [load 0.001 from constants section, store in y1]
T2#G [y2 = t = 0]
[20] A20@ G40@ [call subroutine to print initial values]
[Loop round Runge-Kutta steps]
[22] TF A23@ G12G [clear accumulator, call G1 for Runge-Kutta step]
A9@ A2F U9@ [update negative print count]
G33@ [skip printing if not reached 0]
S8@ T9@ [reset negative print count]
A31@ G40@ [call subroutine to print values]
[33] TF [clear accumulator]
A7@ A2F U7@ [increment negative count of Runge-Kutta steps]
G22@ [loop till count = 0]
O5@ ZF [flush teleprinter buffer; stop]
[Subroutine to print y1 as calculated (1) by Runge-Kutta (2) direct from formula]
[40] A3F T71@ [set up return as usual]
A2#G TD [latest t (= y2) from Runge-Kutta, to 0D for printing]
[44] A44@ G72@ [call subroutine to print t]
O2@ O2@ [followed by 2 spaces]
A#G TD [latest y1 from Runge-Kutta, to 0D for printing]
[50] A50@ G72@ [call subroutine to print y1]
O2@ O2@ [followed by 2 spaces]
A 4#C [load constant 25/(2^10)]
H2#G V2#G TD [add t^2, temp store result in 0D]
HD VD LD YF TD [square, shift 1 left, round, result to 0D]
H2#C VD YF TD [times (2^23)/(10^7), round, to 0D for printing]
[67] A67@ G72@ [call subroutine to print y]
O3@ O4@ [print CR, LF]
[71] ZF [overwritten by jump back to caller]
[Second-level subroutine to print number in 0D to 9 decimal places]
[72] A3F T82@ [set up return as usual]
AD A6#C TD [load number, add decimal rounding, to 0D for printing]
O81@ O1@ [print '0.' since P1 doesn't do so]
A79@ GB [call library subroutine P1 for printing]
[81] P9F [parameter for P1, 9 decimals]
[82] ZF [overwritten by jump back to caller]
[Library subroutine G1 for Runge-Kutta process. 66 locations, even address.]
E25K T12G
GKT4#ZH682DT6#ZPNT12#Z!1405DT14#ZTHT16#ZT2HTZA3FT61@A31@G63@&FT6ZPN
T8ZMMO&H4@A20@E23@T14ZAHT16ZA2HT18ZH12#@S12#@T12#@E28@H4#@T4DUFS38@
A25@T38@S6#@A16#@U46#@A8@U37@A9@U55@A24@T39@ZFR1057#@ZFYFU6DV6DRLYF
UDZFZFADLDADLLS6DN4DYFZFA46#@S14#@G29@A65@S11@ZFA35@U65@GXZF
[Replacement for library routine S2 (square root). 38 locations, even address.
Advantages: More accurate for small values of the argument.
Calculates sqrt(0) without going into an infinite loop.
Disadvantages: Longer and slower than S2 (calculates one bit at a time).]
E25K TV
GKA3FT31@A4DG32@A33@T36#@T4DA33@RDU34#@RDS4DS33@A36#@G22@T36#@A4DS34#@
T4DA36#@A33@G25@TFA36#@S33@A36#@T36#@A34#@RDYFG9@ZFZFK4096FPFPFPFPF
[Library subroutine P1 - print a single positive number. 21 locations.
Prints number in 0D to n places of decimals, where
n is specified by 'P n F' pseudo-order after subroutine call.]
E25K TB
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Define entry point in main routine]
E25K TA GK
E10Z PF [enter at relative address 10 with accumulator = 0]
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Ada
|
Ada
|
with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line;
with Ada.Containers.Vectors;
use Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
use Aws, Ada.Strings.Unbounded, Input_Sources.Strings;
use Ada.Text_IO, Ada.Command_Line;
procedure Not_Coded is
package Members_Vectors is new Ada.Containers.Vectors (
Index_Type => Positive,
Element_Type => Unbounded_String);
use Members_Vectors;
All_Tasks, Language_Members : Vector;
procedure Get_Vector (Category : in String; Mbr_Vector : in out Vector) is
Reader : Tree_Reader;
Doc : Document;
List : Node_List;
N : Node;
A : Attr;
Page : Aws.Response.Data;
S : Messages.Status_Code;
-- Query has cmlimit value of 100, so we need 5 calls to
-- retrieve the complete list of Programming_category
Uri_Xml : constant String :=
"http://rosettacode.org/mw/api.php?action=query&list=categorymembers"
&
"&format=xml&cmlimit=100&cmtitle=Category:";
Cmcontinue : Unbounded_String := Null_Unbounded_String;
begin
loop
Page :=
Aws.Client.Get (Uri_Xml & Category & (To_String (Cmcontinue)));
S := Response.Status_Code (Page);
if S not in Messages.Success then
Put_Line
("Unable to retrieve data => Status Code :" &
Image (S) &
" Reason :" &
Reason_Phrase (S));
raise Connection_Error;
end if;
declare
Xml : constant String := Message_Body (Page);
Source : String_Input;
begin
Open
(Xml'Unrestricted_Access,
Unicode.Ces.Utf8.Utf8_Encoding,
Source);
Parse (Reader, Source);
Close (Source);
end;
Doc := Get_Tree (Reader);
List := Get_Elements_By_Tag_Name (Doc, "cm");
for Index in 1 .. Length (List) loop
N := Item (List, Index - 1);
A := Get_Named_Item (Attributes (N), "title");
Members_Vectors.Append
(Mbr_Vector,
To_Unbounded_String (Value (A)));
end loop;
Free (List);
List := Get_Elements_By_Tag_Name (Doc, "query-continue");
if Length (List) = 0 then
-- we are done
Free (List);
Free (Reader);
exit;
end if;
N := First_Child (Item (List, 0));
A := Get_Named_Item (Attributes (N), "cmcontinue");
Cmcontinue :=
To_Unbounded_String
("&cmcontinue=" & Aws.Url.Encode (Value (A)));
Free (List);
Free (Reader);
end loop;
end Get_Vector;
procedure Quick_Diff (From : in out Vector; Substract : in Vector) is
Beginning, Position : Extended_Index;
begin
-- take adavantage that both lists are already sorted
Beginning := First_Index (From);
for I in First_Index (Substract) .. Last_Index (Substract) loop
Position :=
Find_Index
(Container => From,
Item => Members_Vectors.Element (Substract, I),
Index => Beginning);
if not (Position = No_Index) then
Delete (From, Position);
Beginning := Position;
end if;
end loop;
end Quick_Diff;
begin
if Argument_Count = 0 then
Put_Line ("Can't process : No language given!");
return;
else
Get_Vector (Argument (1), Language_Members);
end if;
Get_Vector ("Programming_Tasks", All_Tasks);
Quick_Diff (All_Tasks, Language_Members);
for I in First_Index (All_Tasks) .. Last_Index (All_Tasks) loop
Put_Line (To_String (Members_Vectors.Element (All_Tasks, I)));
end loop;
Put_Line
("Numbers of tasks not implemented :=" &
Integer'Image (Last_Index ((All_Tasks))));
end Not_Coded;
|
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.
|
#Ring
|
Ring
|
expression = "return pow(x,2) - 7"
one = evalwithx(expression, 1.2)
two = evalwithx(expression, 3.4)
see "one = " + one + nl + "two = " + two + nl
func evalwithx expr, x
return eval(expr)
|
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.
|
#Ruby
|
Ruby
|
def bind_x_to_value(x)
binding
end
def eval_with_x(code, a, b)
eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a))
end
puts eval_with_x('2 ** x', 3, 5) # Prints "24"
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#Scala
|
Scala
|
object Eval extends App {
def evalWithX(expr: String, a: Double, b: Double)=
{val x = b; eval(expr)} - {val x = a; eval(expr)}
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).
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.
|
#Common_Lisp
|
Common Lisp
|
CL-USER> (read-from-string "((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))")
((DATA "quoted data" 123 4.5) (DATA (!@# (4.5) "[more" "data]")))
65
CL-USER> (caar *) ;;The first element from the first sublist is DATA
DATA
CL-USER> (eval (read-from-string "(concatenate 'string \"foo\" \"bar\")")) ;;An example with evaluation
"foobar"
CL-USER>
|
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
|
#J
|
J
|
require 'printf strings files'
langs=. <;._1 LF -.~ noun define NB. replace with real lang strings
foo bar
baz
)
|
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
|
#Java
|
Java
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FixCodeTags
{
public static void main(String[] args)
{
String sourcefile=args[0];
String convertedfile=args[1];
convert(sourcefile,convertedfile);
}
static String[] 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"};
static void convert(String sourcefile,String convertedfile)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(sourcefile));
//String buffer to store contents of the file
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<languages.length;i++)
{
String lang=languages[i];
line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
line=line.replaceAll("</"+lang+">", "</"+"lang>");
line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
line=line.replaceAll("</code>", "</"+"lang>");
}
sb.append(line);
}
br.close();
FileWriter fw=new FileWriter(new File(convertedfile));
//Write entire string buffer into the file
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
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.
|
#Phix
|
Phix
|
without javascript_semantics
include builtins/mpfr.e
mpz n = mpz_init("9516311845790656153499716760847001433441357"),
e = mpz_init("65537"),
d = mpz_init("5617843187844953170308463622230283376298685"),
pt = mpz_init(),
ct = mpz_init()
string plaintext = "Rossetta Code" -- matches C/zkl
-- "Rosetta Code" -- matches D/FreeBasic/Go/Icon/J/Kotlin/Seed7.
mpz_import(pt, length(plaintext), 1, 1, 0, 0, plaintext)
if mpz_cmp(pt, n)>0 then ?9/0 end if
mpz_powm(ct, pt, e, n);
printf(1,"Encoded: %s\n", {mpz_get_str(ct)})
mpz_powm(pt, ct, d, n);
printf(1,"Decoded: %s\n", {mpz_get_str(pt)})
integer size =floor((mpz_sizeinbase(pt,2)+7)/8)
atom pMem = allocate(size,true)
integer count = mpz_export(pMem, 1, 1, 0, 0, pt)
if count>size then ?9/0 end if
printf(1,"As String: %s\n", {peek({pMem,count})})
{pt, ct, n, e, d} = mpz_free({pt, ct, n, e, d})
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defpackage :rpg-generator
(:use :cl)
(:export :generate))
(in-package :rpg-generator)
(defun sufficient-scores-p (scores)
(and (>= (apply #'+ scores) 75)
(>= (count-if #'(lambda (n) (>= n 15)) scores) 2)))
(defun gen-score ()
(apply #'+ (rest (sort (loop repeat 4 collect (1+ (random 6))) #'<))))
(defun generate ()
(loop for scores = (loop repeat 6 collect (gen-score))
until (sufficient-scores-p scores)
finally (format t "Scores: ~A~%" scores)
(format t "Total: ~A~%" (apply #'+ scores))
(format t ">= 15: ~A~%" (count-if (lambda (n) (>= n 15)) scores))
(return scores)))
|
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
|
#Quackery
|
Quackery
|
[ dup 1
[ 2dup > while
+ 1 >>
2dup / again ]
drop nip ] is sqrt ( n --> n )
[ stack [ 3 ~ ] constant ] is primes ( --> s )
( If a number is prime, the corresponding bit on the
number on the primes ancillary stack is set.
Initially all the bits are set except for 0 and 1,
which are not prime numbers by definition. )
[ bit ~
primes take & primes put ] is -composite ( n --> )
[ bit primes share & 0 != ] is isprime ( n --> b )
[ dup sqrt times
[ i^ 1+
dup isprime if
[ dup 2 **
[ dup -composite
over +
rot 2dup >
dip unrot until ]
drop ]
drop ]
drop ] is eratosthenes ( n --> )
100 eratosthenes
100 times [ i^ isprime if [ i^ echo sp ] ]
|
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
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64
Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
index = i '' first occurrence
Return True
End If
Next
index = LBound(s) - 1 '' outside array
Return False
End Function
Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
Dim maxIndex As Integer = LBound(s) - 1 '' outside array
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
maxIndex = i
End If
Next
If maxIndex > LBound(s) - 1 Then
index = maxIndex '' last occurrence
Return True
Else
Return False
End If
End Function
Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"}
Dim As Integer index
Dim As Boolean found
For i As Integer = 1 To 4
found = tryFindString(haystack(), needle(i), index)
If found Then
Print needle(i); " found first at index"; index
Else
Print needle(i); " is not present"
End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
Print needle(4); " found last at index"; index
Else
Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep
|
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.
|
#C.2B.2B
|
C++
|
#include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort { //sorting programming languages according to frequency
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
//setting up an io service , with templated subelements for resolver and query
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
//looking for an endpoint the socket will be able to connect to
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
//we send a request
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
//send the request
boost::asio::write( socket , request ) ;
//we receive the response analyzing every line and storing the programming language
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
//using the wrong regex produces incorrect sorting!!
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ; //holds language and number of examples
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;//we have to erase the string buffer for the next read
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
//we sort the vector entries , see the struct above
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
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.
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % key := rle_encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
MsgBox % rle_decode(key)
rle_encode(message)
{
StringLeft, previous, message, 1
StringRight, last, message, 1
message .= Asc(Chr(last)+1)
count = 0
Loop, Parse, message
{
If (previous == A_LoopField)
count +=1
Else
{
output .= previous . count
previous := A_LoopField
count = 1
}
}
Return output
}
rle_decode(message)
{
pos = 1
While, item := RegExMatch(message, "\D", char, pos)
{
digpos := RegExMatch(message, "\d+", dig, item)
Loop, % dig
output .= char
pos := digpos
}
Return output
}
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Command_Line; use Ada.Command_Line;
procedure Rot_13 is
From_Sequence : Character_Sequence := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result_Sequence : Character_Sequence := "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM";
Rot_13_Mapping : Character_Mapping := To_Mapping(From_Sequence, Result_Sequence);
In_Char : Character;
Stdio : Stream_Access := Stream(Ada.Text_IO.Standard_Input);
Stdout : Stream_Access := Stream(Ada.Text_Io.Standard_Output);
Input : Ada.Text_Io.File_Type;
begin
if Argument_Count > 0 then
for I in 1..Argument_Count loop
begin
Ada.Text_Io.Open(File => Input, Mode => Ada.Text_Io.In_File, Name => Argument(I));
Stdio := Stream(Input);
while not Ada.Text_Io.End_Of_File(Input) loop
In_Char :=Character'Input(Stdio);
Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));
end loop;
Ada.Text_IO.Close(Input);
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => "File " & Argument(I) & " is not a file.");
when Ada.Text_Io.Status_Error =>
Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => "File " & Argument(I) & " is already opened.");
end;
end loop;
else
while not Ada.Text_Io.End_Of_File loop
In_Char :=Character'Input(Stdio);
Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));
end loop;
end if;
end Rot_13;
|
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 }
|
#ERRE
|
ERRE
|
PROGRAM RUNGE_KUTTA
CONST DELTA_T=0.1
FUNCTION Y1(T,Y)
Y1=T*SQR(Y)
END FUNCTION
BEGIN
Y=1.0
FOR I%=0 TO 100 DO
T=I%*DELTA_T
IF T=INT(T) THEN ! print every tenth
ACTUAL=((T^2+4)^2)/16 ! exact solution
PRINT("Y(";T;")=";Y;TAB(20);"Error=";ACTUAL-Y)
END IF
K1=Y1(T,Y)
K2=Y1(T+DELTA_T/2,Y+DELTA_T/2*K1)
K3=Y1(T+DELTA_T/2,Y+DELTA_T/2*K2)
K4=Y1(T+DELTA_T,Y+DELTA_T*K3)
Y+=DELTA_T*(K1+2*(K2+K3)+K4)/6
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#AutoHotkey
|
AutoHotkey
|
#NoEnv ; do not resolve environment variables (speed)
#SingleInstance force ; allow only one instance
SetBatchLines, -1 ; set to highest script speed
SetControlDelay, 0 ; set delay between control commands to lowest
; additional label, for clarity only
AutoExec:
Gui, Add, DDL, x10 y10 w270 r20 vlngStr ; add drop-down list
Gui, Add, Button, x290 y10 gShowLng, Show Unimplemented ; add button
Gui, Add, ListView, x10 y36 w400 h300 vcatLst gOnLV, Unimplemented ; add listview
Gui, Add, StatusBar, vsbStr, ; add statusbar
Gui, Show, , RosettaCode unimplemented list ; show the gui
allLng := getList("lng") ; get a list of all available languages
selectStr = Select language... ; set selection string for ddl
GuiControl, , LngStr, |%selectStr%||%allLng% ; set the ddl to new contents
SB_SetIcon("user32.dll", 5) ; change statusbar icon
SB_SetText("Done loading languages. Select from menu.") ; change statusbar text
Return ; end of the autoexec section. Script waits for input.
; subroutine for language list in ddl update
ShowLng:
Gui, Submit, NoHide ; refresh all gui variables
If (lngStr != selectStr) ; if the current selected language is not the selection string
{
SB_SetIcon("user32.dll", 2) ; set statusbar icon to exclamation
SB_SetText("Loading unimplemented tasks... Please wait.") ; set statusbar text
allTsk := getList("tsk") ; get a list of all tasks
allThis := getList(lngStr) ; get a list of all done tasks for this language
Loop, Parse, allTsk, | ; parse the list of all tasks
{
If !InStr(allThis,A_LoopField) ; if the current task is not found in the list of all tasks
notImpl .= A_LoopField . "|" ; add the current field to the notImpl variable
allTskCnt := A_Index ; save the index for final count
}
StringTrimRight, notImpl, notImpl, 1 ; remove last delimiter
LV_Delete() ; emty the listview
GuiControl, -Redraw, catLst ; set the listview to not redraw while adding (speed)
Loop, Parse, notImpl, | ; parse the list of not implemented tasks
{
LV_Add("", A_LoopField) ; add them to the listview, field by field
notImplCnt := A_Index ; save the index for final count
}
GuiControl, +Redraw, catLst ; set the listview back to normal
SB_SetIcon("user32.dll", 5) ; change statusbar icon to information
SB_SetText("There are " . notImplCnt . " of " . allTskCnt
. " tasks unimplemented. Double-click task to open in browser.") ; set the statusbar text
notImpl = ; empty the notImpl variable
notImplCnt = 0 ; set the count back to 0
}
Return
; subroutine for action on listview
OnLV:
If (A_GuiEvent = "DoubleClick") ; if the listview was double-clicked
{
LV_GetText(rowTxt, A_EventInfo) ; get the text of the clicked row
rowTxt := Enc_Uri(rowTxt) ; uri-encode the text
StringReplace, rowTxt, rowTxt, `%20, _, All ; replace all space-encodings with underscores
Run % "http://rosettacode.org/wiki/" . rowTxt ; run the resulting link in the default browser
}
Return
; generic function to gather list
getList(category)
{
fileName = temp.xml ; set temp-file name
If (category = "lng") ; if the category received is lng
{
category = Programming_Languages ; set the category
fileName = lng.xml ; set temp-file name
IfExist, %fileName% ; if the file already exists
{
FileGetTime, modTime, %fileName% ; get the last modified time
EnvSub, modTime, %A_Now%, days ; get the difference between now and last modified time in days
If (modTime < 3) ; if the result is less than 3
Goto, GetFileNoDL ; go to function-internal subroutine to parse
}
SB_SetIcon("user32.dll", 2) ; set statusbar icon
SB_SetText("Loading languages... Please wait.") ; set statusbar text
}
If (category = "tsk") ; if the category received is tsk
category = Programming_Tasks ; set the category
getFile: ; function-internal subroutine for getting a file and parsing it
; construct the url
url := "http://www.rosettacode.org/w/api.php?action=query&list="
. "categorymembers&cmtitle=Category:" . category
. "&cmlimit=500&format=xml" . doContinue
UrlDownloadToFile, %url%, %fileName% ; download the url
getFileNoDL: ; function-internal subroutine for parsing a file
FileRead, data, %fileName% ; read file into variable
pos = 1 ; set while-loop counter
rxp = title="(.*?)" ; set regular expression
While (pos := RegExMatch(data, rxp, title, pos)) ; get the contents of the title fields one-by-one
{
If InStr(title1, "Category:") ; if the contents contain Category:
StringTrimLeft, title1, title1, 9 ; remove that from the contents
StringReplace, title1, title1, |, `|, All ; escape all containing delimiters
title1 := Dec_XML(UTF82Ansi(title1)) ; convert to ansi first and then decode html entities
allTitles .= title1 . "|" ; add this title to list
pos++ ; increment counter
}
rxp = cmcontinue="(.*?)" ; set regular expression
If RegExMatch(data, rxp, next) ; when found
{
doContinue = &cmcontinue=%next1% ; set continuation string to add to url
Goto getFile ; go to function-internal subroutine to redownload and parse
}
StringTrimRight, allTitles, allTitles, 1 ; remove last delimiter from result
Return allTitles ; return result
}
; function to convert html entities to ansi equivalents
Dec_XML(str)
{
Loop
If RegexMatch(str, "S)(&#(\d+);)", dec)
StringReplace, str, str, %dec1%, % Chr(dec2), All
Else If RegexMatch(str, "Si)(&#x([\da-f]+);)", hex)
StringReplace, str, str, %hex1%, % Chr("0x" . hex2), All
Else
Break
StringReplace, str, str, , %A_Space%, All
StringReplace, str, str, ", ", All
StringReplace, str, str, ', ', All
StringReplace, str, str, <, <, All
StringReplace, str, str, >, >, All
StringReplace, str, str, &, &, All
return, str
}
; function to uri-encode input string
Enc_Uri(str)
{
f = %A_FormatInteger%
SetFormat, Integer, Hex
If RegExMatch(str, "^\w+:/{0,2}", pr)
StringTrimLeft, str, str, StrLen(pr)
StringReplace, str, str, `%, `%25, All
Loop
If RegExMatch(str, "i)[^\w\.~%/:]", char)
StringReplace, str, str, %char%, % "%" . SubStr(Asc(char),3), All
Else Break
SetFormat, Integer, %f%
Return, pr . str
}
; function to convert unicode to ansi text
UTF82Ansi(zString)
{
Ansi2Unicode(zString, wString, 65001)
Unicode2Ansi(wString, sString, 0)
Return sString
}
; helper function for unicode to ansi function
Ansi2Unicode(ByRef sString, ByRef wString, CP = 0)
{
nSize := DllCall("MultiByteToWideChar", "Uint", CP
, "Uint", 0, "Uint", &sString, "int", -1
, "Uint", 0, "int", 0)
VarSetCapacity(wString, nSize * 2)
DllCall("MultiByteToWideChar"
, "Uint", CP, "Uint", 0, "Uint", &sString, "int", -1
, "Uint", &wString, "int", nSize)
}
; helper function for unicode to ansi function
Unicode2Ansi(ByRef wString, ByRef sString, CP = 0)
{
nSize := DllCall("WideCharToMultiByte"
, "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1
, "Uint", 0, "int", 0, "Uint", 0, "Uint", 0)
VarSetCapacity(sString, nSize)
DllCall("WideCharToMultiByte"
, "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1
, "str", sString, "int", nSize, "Uint", 0, "Uint", 0)
}
; subroutine called when user closes the gui
GuiClose:
ExitApp ; exit the script
Return
|
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.
|
#Scheme
|
Scheme
|
(define (eval-with-x prog a b)
(let ((at-a (eval `(let ((x ',a)) ,prog)))
(at-b (eval `(let ((x ',b)) ,prog))))
(- at-b at-a)))
|
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.
|
#Sidef
|
Sidef
|
func eval_with_x(code, x, y) {
var f = eval(code);
x = y;
eval(code) - f;
}
say eval_with_x(x: 3, y: 5, code: '2 ** x'); # => 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.
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
const MAXDEPTH := 256; # Maximum depth (used for stack sizes)
const MAXSTR := 256; # Maximum string length
# Type markers
const T_ATOM := 1;
const T_STRING := 2;
const T_NUMBER := 3;
const T_LIST := 4;
# Value union
record SVal is
number @at(0): int32;
string @at(0): [uint8]; # also used for atoms
list @at(0): [SExp];
end record;
# Holds a linked list of items
record SExp is
type: uint8;
next: [SExp];
val: SVal;
end record;
# Free an S-Expression
sub FreeSExp(exp: [SExp]) is
var stack: [SExp][MAXDEPTH];
stack[0] := exp;
var sp: @indexof stack := 1;
while sp > 0 loop
sp := sp - 1;
exp := stack[sp];
while exp != 0 as [SExp] loop
var next := exp.next;
case exp.type is
when T_ATOM:
Free(exp.val.string);
when T_STRING:
Free(exp.val.string);
when T_LIST:
stack[sp] := exp.val.list;
sp := sp + 1;
end case;
Free(exp as [uint8]);
exp := next;
end loop;
end loop;
end sub;
# Build an S-Expression
sub ParseSExp(in: [uint8]): (out: [SExp]) is
out := 0 as [SExp];
sub SkipSpace() is
while ([in] != 0) and ([in] <= 32) loop
in := @next in;
end loop;
end sub;
sub AtomEnd(): (space: [uint8]) is
space := in;
while ([space] > 32)
and ([space] != '(')
and ([space] != ')') loop
space := @next space;
end loop;
end sub;
record Stk is
start: [SExp];
cur: [SExp];
end record;
var strbuf: uint8[MAXSTR];
var stridx: @indexof strbuf := 0;
var item: [SExp];
var stack: Stk[MAXDEPTH];
var sp: @indexof stack := 0;
stack[0].start := 0 as [SExp];
stack[0].cur := 0 as [SExp];
sub Store(item: [SExp]) is
if stack[sp].start == 0 as [SExp] then
stack[sp].start := item;
end if;
if stack[sp].cur != 0 as [SExp] then
stack[sp].cur.next := item;
end if;
stack[sp].cur := item;
end sub;
# called on error to clean up memory
sub FreeAll() is
loop
FreeSExp(stack[sp].start);
stack[sp].start := 0;
if sp == 0 then break; end if;
sp := sp - 1;
end loop;
end sub;
loop
SkipSpace();
case [in] is
when 0: break;
when '"':
var escape: uint8 := 0;
stridx := 0;
loop
in := @next in;
if [in] == 0 then break;
elseif escape == 1 then
strbuf[stridx] := [in];
stridx := stridx + 1;
escape := 0;
elseif [in] == '\\' then escape := 1;
elseif [in] == '"' then break;
else
strbuf[stridx] := [in];
stridx := stridx + 1;
end if;
end loop;
if [in] == 0 then
# missing _"_
FreeAll();
return;
end if;
in := @next in;
strbuf[stridx] := 0;
stridx := stridx + 1;
item := Alloc(@bytesof SExp) as [SExp];
item.type := T_STRING;
item.val.string := Alloc(stridx as intptr);
CopyString(&strbuf[0], item.val.string);
Store(item);
when '(':
in := @next in;
sp := sp + 1;
stack[sp].start := 0 as [SExp];
stack[sp].cur := 0 as [SExp];
when ')':
in := @next in;
if sp == 0 then
# stack underflow, error
FreeAll();
return;
else
item := Alloc(@bytesof SExp) as [SExp];
item.type := T_LIST;
item.val.list := stack[sp].start;
sp := sp - 1;
Store(item);
end if;
when else:
var aend := AtomEnd();
item := Alloc(@bytesof SExp) as [SExp];
# if this is a valid integer number then store as number
var ptr: [uint8];
(item.val.number, ptr) := AToI(in);
if ptr == aend then
# a number was parsed and the whole atom consumed
item.type := T_NUMBER;
else
# not a valid integer number, store as atom
item.type := T_ATOM;
var length := aend - in;
item.val.string := Alloc(length + 1);
MemCopy(in, length, item.val.string);
[item.val.string + length] := 0;
end if;
in := aend;
Store(item);
end case;
end loop;
if sp != 0 then
# unterminated list!
FreeAll();
return;
else
# return start of list
out := stack[0].start;
end if;
end sub;
# Prettyprint an S-Expression with types
sub prettyprint(sexp: [SExp]) is
sub PrintNum(n: int32) is
var buf: uint8[16];
[IToA(n, 10, &buf[0])] := 0;
print(&buf[0]);
end sub;
sub PrintQuoteStr(s: [uint8]) is
print_char('"');
while [s] != 0 loop
if [s] == '"' or [s] == '\\' then
print_char('\\');
end if;
print_char([s]);
s := @next s;
end loop;
print_char('"');
end sub;
var stack: [SExp][MAXDEPTH];
var sp: @indexof stack := 1;
stack[0] := sexp;
sub Indent(n: @indexof stack) is
while n > 0 loop
print(" ");
n := n - 1;
end loop;
end sub;
loop
sp := sp - 1;
while stack[sp] != 0 as [SExp] loop
Indent(sp);
case stack[sp].type is
when T_ATOM:
print(stack[sp].val.string);
print(" :: Atom");
stack[sp] := stack[sp].next;
when T_STRING:
PrintQuoteStr(stack[sp].val.string);
print(" :: String");
stack[sp] := stack[sp].next;
when T_NUMBER:
PrintNum(stack[sp].val.number);
print(" :: Number");
stack[sp] := stack[sp].next;
when T_LIST:
print_char('(');
sp := sp + 1;
stack[sp] := stack[sp-1].val.list;
stack[sp-1] := stack[sp-1].next;
end case;
print_nl();
end loop;
if sp == 0 then
break;
end if;
Indent(sp-1);
print_char(')');
print_nl();
end loop;
end sub;
var str := "((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))";
print("Input:\n");
print(str);
print_nl();
print("Parsed:\n");
prettyprint(ParseSExp(str));
print_nl();
|
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
|
#JavaScript
|
JavaScript
|
var langs = ['foo', 'bar', 'baz']; // real list of langs goes here
var end_tag = '</'+'lang>';
var line;
while (line = readline()) {
line = line.replace(new RegExp('</code>', 'gi'), end_tag);
for (var i = 0; i < langs.length; i++)
line = line.replace(new RegExp('<(?:code )?(' + langs[i] + ')>', 'gi'), '<lang $1>')
.replace(new RegExp('</' + langs[i] + '>', 'gi'), end_tag);
print(line);
}
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the 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.
|
#PicoLisp
|
PicoLisp
|
### This is a copy of "lib/rsa.l" ###
# Generate long random number
(de longRand (N)
(use (R D)
(while (=0 (setq R (abs (rand)))))
(until (> R N)
(unless (=0 (setq D (abs (rand))))
(setq R (* R D)) ) )
(% R N) ) )
# X power Y modulus N
(de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
# Probabilistic prime check
(de prime? (N)
(and
(> N 1)
(bit? 1 N)
(let (Q (dec N) K 0)
(until (bit? 1 Q)
(setq
Q (>> 1 Q)
K (inc K) ) )
(do 50
(NIL (_prim? N Q K))
T ) ) ) )
# (Knuth Vol.2, p.379)
(de _prim? (N Q K)
(use (X J Y)
(while (> 2 (setq X (longRand N))))
(setq
J 0
Y (**Mod X Q N) )
(loop
(T
(or
(and (=0 J) (= 1 Y))
(= Y (dec N)) )
T )
(T
(or
(and (> J 0) (= 1 Y))
(<= K (inc 'J)) )
NIL )
(setq Y (% (* Y Y) N)) ) ) )
# Find a prime number with `Len' digits
(de prime (Len)
(let P (longRand (** 10 (*/ Len 2 3)))
(unless (bit? 1 P)
(inc 'P) )
(until (prime? P) # P: Prime number of size 2/3 Len
(inc 'P 2) )
# R: Random number of size 1/3 Len
(let (R (longRand (** 10 (/ Len 3))) K (+ R (% (- P R) 3)))
(when (bit? 1 K)
(inc 'K 3) )
(until (prime? (setq R (inc (* K P))))
(inc 'K 6) )
R ) ) )
# Generate RSA key
(de rsaKey (N) #> (Encrypt . Decrypt)
(let (P (prime (*/ N 5 10)) Q (prime (*/ N 6 10)))
(cons
(* P Q)
(/
(inc (* 2 (dec P) (dec Q)))
3 ) ) ) )
# Encrypt a list of characters
(de encrypt (Key Lst)
(let Siz (>> 1 (size Key))
(make
(while Lst
(let N (char (pop 'Lst))
(while (> Siz (size N))
(setq N (>> -16 N))
(inc 'N (char (pop 'Lst))) )
(link (**Mod N 3 Key)) ) ) ) ) )
# Decrypt a list of numbers
(de decrypt (Keys Lst)
(mapcan
'((N)
(let Res NIL
(setq N (**Mod N (cdr Keys) (car Keys)))
(until (=0 N)
(push 'Res (char (& `(dec (** 2 16)) N)))
(setq N (>> 16 N)) )
Res ) )
Lst ) )
### End of "lib/rsa.l" ###
# Generate 100-digit keys (private . public)
: (setq Keys (rsaKey 100))
-> (14394597526321726957429995133376978449624406217727317004742182671030....
# Encrypt
: (setq CryptText
(encrypt (car Keys)
(chop "The quick brown fox jumped over the lazy dog's back") ) )
-> (72521958974980041245760752728037044798830723189142175108602418861716...
# Decrypt
: (pack (decrypt Keys CryptText))
-> "The quick brown fox jumped over the lazy dog's back"
|
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.
|
#PowerShell
|
PowerShell
|
$n = [BigInt]::Parse("9516311845790656153499716760847001433441357")
$e = [BigInt]::new(65537)
$d = [BigInt]::Parse("5617843187844953170308463622230283376298685")
$plaintextstring = "Hello, Rosetta!"
$plaintext = [Text.ASCIIEncoding]::ASCII.GetBytes($plaintextstring)
[BigInt]$pt = [BigInt]::new($plaintext)
if ($n -lt $pt) {throw "`$n = $n < $pt = `$pt"}
$ct = [BigInt]::ModPow($pt, $e, $n)
"Encoded: $ct"
$dc = [BigInt]::ModPow($ct, $d, $n)
"Decoded: $dc"
$decoded = [Text.ASCIIEncoding]::ASCII.GetString($dc.ToByteArray())
"As ASCII: $decoded"
|
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.
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
include "argv.coh";
# There is no random number generator in the standard library (yet?)
# There is also no canonical source of randomness, and indeed,
# on some target platforms (like CP/M) there is no guaranteed
# source of randomness at all. Therefore, I implement the "X ABC"
# random number generator, and ask for a seed on the command line.
record RandState is
x @at(0): uint8;
a @at(1): uint8;
b @at(2): uint8;
c @at(3): uint8;
end record;
sub RandByte(s: [RandState]): (r: uint8) is
s.x := s.x + 1;
s.a := s.a ^ s.c ^ s.x;
s.b := s.b + s.a;
s.c := s.c + (s.b >> 1) ^ s.a;
r := s.c;
end sub;
# Roll a d6
typedef D6 is int(1, 6);
sub Roll(s: [RandState]): (r: D6) is
var x: uint8;
loop
x := RandByte(s) & 7;
if x < 6 then break; end if;
end loop;
r := x + 1;
end sub;
# Roll 4 D6es and get the sum of the 3 highest
sub Roll4(s: [RandState]): (r: uint8) is
r := 0;
var lowest: uint8 := 0;
var n: uint8 := 4;
while n > 0 loop
var roll := Roll(s);
r := r + roll;
if lowest > roll then
lowest := roll;
end if;
n := n - 1;
end loop;
r := r - lowest;
end sub;
# Read random seed from command line
var randState: RandState;
ArgvInit();
var argmt := ArgvNext();
if argmt == (0 as [uint8]) then
print("Please give random seed on command line.\n");
ExitWithError();
end if;
([&randState as [int32]], argmt) := AToI(argmt);
var total: uint8;
var attrs: uint8[6];
var i: @indexof attrs;
loop
var at15: uint8 := 0;
i := 0;
total := 0;
# generate 6 attributes
while i < 6 loop
attrs[i] := Roll4(&randState);
total := total + attrs[i];
# count how many are higher than or equal to 15
if attrs[i] >= 15 then
at15 := at15 + 1;
end if;
i := i + 1;
end loop;
# if the requirements are met, then stop
if total >= 75 and at15 >= 2 then
break;
end if;
end loop;
# Show the generated values
print("Attributes: ");
i := 0;
while i < 6 loop
print_i8(attrs[i]);
print_char(' ');
i := i + 1;
end loop;
print("\nTotal: ");
print_i8(total);
print_nl();
|
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
|
#R
|
R
|
sieve <- function(n) {
if (n < 2) integer(0)
else {
primes <- rep(T, n)
primes[[1]] <- F
for(i in seq(sqrt(n))) {
if(primes[[i]]) {
primes[seq(i * i, n, i)] <- F
}
}
which(primes)
}
}
sieve(1000)
|
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
|
Rosetta Code/Count examples
|
task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Ada
|
Ada
|
with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8;
with Ada.Strings.Unbounded, Ada.Strings.Fixed, Ada.Text_IO, Ada.Command_Line;
with Ada.Containers.Vectors;
use Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url;
use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs;
use Aws, Ada.Strings.Unbounded, Ada.Strings.Fixed, Input_Sources.Strings;
use Ada.Text_IO, Ada.Command_Line;
procedure Count_Examples is
package Members_Vectors is new Ada.Containers.Vectors (
Index_Type => Positive,
Element_Type => Unbounded_String);
use Members_Vectors;
Exemples : Vector;
Nbr_Lg, Total : Natural := 0;
procedure Get_Vector (Category : in String; Mbr_Vector : in out Vector) is
Reader : Tree_Reader;
Doc : Document;
List : Node_List;
N : Node;
A : Attr;
Page : Aws.Response.Data;
Uri_Xml : constant String :=
"http://rosettacode.org/mw/api.php?action=query&list=categorymembers"
&
"&format=xml&cmlimit=500&cmtitle=Category:";
begin
Page := Client.Get (Uri_Xml & Category);
if Response.Status_Code (Page) not in Messages.Success then
raise Client.Connection_Error;
end if;
declare
Xml : constant String := Message_Body (Page);
Source : String_Input;
begin
Open
(Xml'Unrestricted_Access,
Unicode.Ces.Utf8.Utf8_Encoding,
Source);
Parse (Reader, Source);
Close (Source);
end;
Doc := Get_Tree (Reader);
List := Get_Elements_By_Tag_Name (Doc, "cm");
for Index in 1 .. Length (List) loop
N := Item (List, Index - 1);
A := Get_Named_Item (Attributes (N), "title");
Append (Mbr_Vector, To_Unbounded_String (Value (A)));
end loop;
Free (List);
Free (Reader);
end Get_Vector;
function Scan_Page (Title : String) return Natural is
Page : Aws.Response.Data;
File : Aws.Resources.File_Type;
Buffer : String (1 .. 1024);
Languages, Position, Last : Natural := 0;
begin
Page :=
Client.Get
("http://rosettacode.org/mw/index.php?title=" &
Aws.Url.Encode (Title) &
"&action=raw");
Response.Message_Body (Page, File);
while not End_Of_File (File) loop
Resources.Get_Line (File, Buffer, Last);
Position :=
Index
(Source => Buffer (Buffer'First .. Last),
Pattern => "=={{header|");
if Position > 0 then
Languages := Languages + 1;
end if;
end loop;
Close (File);
return Languages;
end Scan_Page;
begin
Get_Vector ("Programming_Tasks", Exemples);
for I in First_Index (Exemples) .. Last_Index (Exemples) loop
declare
Title : constant String :=
To_String (Members_Vectors.Element (Exemples, I));
begin
Nbr_Lg := Scan_Page (Title);
Total := Total + Nbr_Lg;
Put_Line (Title & " :" & Integer'Image (Nbr_Lg) & " exemples.");
end;
end loop;
Put_Line ("Total :" & Integer'Image (Total) & " exemples.");
end Count_Examples;
|
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
|
#Gambas
|
Gambas
|
Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short
For siCount = 0 To sHaystack.Max
If sNeedle = sHaystack[siCount] Then
sOutPut = sNeedle & " found at index " & Str(siCount)
Break
End If
Next
Print sOutput
End
|
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.
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
Class Utils.Net.RosettaCode [ Abstract ]
{
ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop As %Integer = 10) As %Status
{
// check input parameters
If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 {
Quit $$$ERROR($$$GeneralError, "Invalid host name.")
}
// create http request and get page
Set req=##class(%Net.HttpRequest).%New()
Set req.Server=pHost
Do req.Get(pPath)
// create xml stream with doc type
Set xml=##class(%Stream.GlobalCharacter).%New()
Set sc=xml.WriteLine("<!DOCTYPE doc_type [")
Set sc=xml.WriteLine($Char(9)_"<!ENTITY nbsp ' '>")
Set sc=xml.WriteLine($Char(9)_"<!ENTITY amp '&'>")
Set sc=xml.WriteLine("]>")
// copy xhtml stream to xml stream
Set xhtml=req.HttpResponse.Data
Set xhtml.LineTerminator=$Char(10)
While 'xhtml.AtEnd {
Set line=xhtml.ReadLine()
If line["!DOCTYPE" Continue
If line["<g:plusone></g:plusone>" {
Continue
Set line="<g:plusone xmlns:g='http://base.google.com/ns/1.0'></g:plusone>"
}
Set sc=xml.WriteLine(line)
}
// create an instance of an %XML.XPATH.Document
Set sc=##class(%XML.XPATH.Document).CreateFromStream(xml, .xdoc)
If $$$ISERR(sc) Quit sc
// evaluate following 'XPath' expression
Set sc=xdoc.EvaluateExpression("//div[@id='bodyContent']//li", "a[contains(@href, '/Category:')]/ancestor::li", .res)
// iterate through list elements
Set array=##class(%ArrayOfDataTypes).%New()
Do {
Set dom=res.GetNext(.key)
If '$IsObject(dom) Quit
// get language name and members
Set lang=""
While dom.Read() {
If 'dom.HasValue Continue
If lang="" {
If $Locate(dom.Value, "User|Tasks|Omit|attention|operations|Solutions by") Quit
Set lang=dom.Value Continue
}
If dom.Value["members" {
Set members=+$ZStrip(dom.Value, "<>P")
Set list=array.GetAt(members)
Set $List(list, $ListLength(list)+1)=lang
Set sc=array.SetAt(list, members)
Quit
}
}
} While key'=""
If array.Count()=0 Quit $$$ERROR($$$GeneralError, "No languages found.")
// show top entries
Write "Top "_pTop_" Languages (as at "_$ZDate($HoroLog, 2)_"):", !
For count=1:1:pTop {
Set members=array.GetPrevious(.key)
If key="" Quit
Write $Justify(count, 3), ". ", key, " - ", $ListToString(members, ", "), !
}
// finished
Quit $$$OK
}
}
|
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.
|
#AWK
|
AWK
|
BEGIN {
FS=""
}
/^[^0-9]+$/ {
cp = $1; j = 0
for(i=1; i <= NF; i++) {
if ( $i == cp ) {
j++;
} else {
printf("%d%c", j, cp)
j = 1
}
cp = $i
}
printf("%d%c", j, cp)
}
|
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
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
CHAR c;
on logical file end(stand in, (REF FILE f)BOOL: (stop; SKIP));
on line end(stand in, (REF FILE f)BOOL: (print(new line); FALSE));
DO
read(c);
IF c >= "A" AND c <= "M" OR c >= "a" AND c <= "m" THEN
c := REPR(ABS c + 13)
ELIF c >= "N" AND c <= "Z" OR c >= "n" AND c <= "z" THEN
c := REPR(ABS c - 13)
FI;
print(c)
OD
END # rot13 #
|
http://rosettacode.org/wiki/Runge-Kutta_method
|
Runge-Kutta method
|
Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
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 }
|
#F.23
|
F#
|
open System
let y'(t,y) = t * sqrt(y)
let RungeKutta4 t0 y0 t_max dt =
let dy1(t,y) = dt * y'(t,y)
let dy2(t,y) = dt * y'(t+dt/2.0, y+dy1(t,y)/2.0)
let dy3(t,y) = dt * y'(t+dt/2.0, y+dy2(t,y)/2.0)
let dy4(t,y) = dt * y'(t+dt, y+dy3(t,y))
(t0,y0) |> Seq.unfold (fun (t,y) ->
if ( t <= t_max) then Some((t,y), (Math.Round(t+dt, 6), y + ( dy1(t,y) + 2.0*dy2(t,y) + 2.0*dy3(t,y) + dy4(t,y))/6.0))
else None
)
let y_exact t = (pown (pown t 2 + 4.0) 2)/16.0
RungeKutta4 0.0 1.0 10.0 0.1
|> Seq.filter (fun (t,y) -> t % 1.0 = 0.0 )
|> Seq.iter (fun (t,y) -> Console.WriteLine("y({0})={1}\t(relative error:{2})", t, y, (y / y_exact(t))-1.0) )
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net;
class Program {
static List<string> GetTitlesFromCategory(string category) {
string searchQueryFormat = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:{0}&format=json{1}";
List<string> results = new List<string>();
string cmcontinue = string.Empty;
do {
string cmContinueKeyValue;
//append continue variable as needed
if (cmcontinue.Length > 0)
cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue);
else
cmContinueKeyValue = String.Empty;
//execute query
string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);
string content = new WebClient().DownloadString(query);
results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));
//detect if more results are available
cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value;
} while (cmcontinue.Length > 0);
return results;
}
static string[] GetUnimplementedTasksFromLanguage(string language) {
List<string> alltasks = GetTitlesFromCategory("Programming_Tasks");
List<string> lang = GetTitlesFromCategory(language);
return alltasks.Where(x => !lang.Contains(x)).ToArray();
}
static void Main(string[] args) {
string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);
foreach (string i in unimpl) Console.WriteLine(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 Eval.
Dynamic variable names is a similar task.
|
#Simula
|
Simula
|
BEGIN
CLASS ENV;
BEGIN
CLASS ITEM(N, X); TEXT N; REAL X;
BEGIN
REF(ITEM) NEXT; NEXT :- HEAD; HEAD :- THIS ITEM;
END ITEM;
REF(ITEM) HEAD;
REF(ITEM) PROCEDURE LOOKUP(V); TEXT V;
BEGIN
REF(ITEM) I; BOOLEAN FOUND; I :- HEAD;
WHILE NOT FOUND DO
IF I == NONE OR ELSE I.N = V
THEN FOUND := TRUE
ELSE I :- I.NEXT;
LOOKUP :- I;
END LOOKUP;
REF(ENV) PROCEDURE SET(V, X); TEXT V; REAL X;
BEGIN
REF(ITEM) I; I :- LOOKUP(V);
IF I == NONE THEN I :- NEW ITEM(V, X) ELSE I.X := X;
SET :- THIS ENV;
END SET;
REAL PROCEDURE GET(V); TEXT V;
GET := LOOKUP(V).X;
END ENV;
CLASS EXPR(EV); REF(ENV) EV;
BEGIN
REAL PROCEDURE POP;
BEGIN
IF STACKPOS > 0 THEN
BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END;
END POP;
PROCEDURE PUSH(NEWTOP); REAL NEWTOP;
BEGIN
STACK(STACKPOS) := NEWTOP;
STACKPOS := STACKPOS + 1;
END PUSH;
REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR;
BEGIN
REAL X, Y; X := POP; Y := POP;
IF OPERATOR = '+' THEN PUSH(Y + X)
ELSE IF OPERATOR = '-' THEN PUSH(Y - X)
ELSE IF OPERATOR = '*' THEN PUSH(Y * X)
ELSE IF OPERATOR = '/' THEN BEGIN
IF X = 0 THEN
BEGIN
EVALUATEDERR :- "DIV BY ZERO";
GOTO ERR;
END;
PUSH(Y / X);
END
ELSE IF OPERATOR = '^' THEN PUSH(Y ** X)
ELSE
BEGIN
EVALUATEDERR :- "UNKNOWN OPERATOR";
GOTO ERR;
END
END CALC;
PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH;
BEGIN
IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT;
END READCHAR;
PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH;
BEGIN
WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO
READCHAR(CH);
END SKIPWHITESPACE;
PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR;
BEGIN
CHARACTER OPERATOR;
REAL NUMBR;
BOOLEAN NEGATIVE;
SKIPWHITESPACE(CH);
IF OP = EXPRESSION THEN
BEGIN
NEGATIVE := FALSE;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
IF CH = '-' THEN NEGATIVE := NOT NEGATIVE;
READCHAR(CH);
END;
BUSYBOX(TERM, ERR);
IF NEGATIVE THEN
BEGIN
NUMBR := POP; PUSH(0 - NUMBR);
END;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR);
END;
END
ELSE IF OP = TERM THEN
BEGIN
BUSYBOX(FACTOR, ERR);
WHILE (CH = '*') OR (CH = '/') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR)
END
END
ELSE IF OP = FACTOR THEN
BEGIN
BUSYBOX(POWER, ERR);
WHILE CH = '^' DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(POWER, ERR); CALC(OPERATOR, ERR)
END
END
ELSE IF OP = POWER THEN
BEGIN
IF (CH = '+') OR (CH = '-') THEN
BUSYBOX(EXPRESSION, ERR)
ELSE IF (CH >= '0') AND (CH <= '9') THEN
BUSYBOX(NUMBER, ERR)
ELSE IF (CH >= 'A') AND (CH <= 'Z') THEN
BUSYBOX(VARIABLE, ERR)
ELSE IF CH = '(' THEN
BEGIN
READCHAR(CH);
BUSYBOX(EXPRESSION, ERR);
IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR;
END
ELSE GOTO ERR;
END
ELSE IF OP = VARIABLE THEN
BEGIN
TEXT VARNAM;
VARNAM :- BLANKS(32);
WHILE (CH >= 'A') AND (CH <= 'Z')
OR (CH >= '0') AND (CH <= '9') DO
BEGIN
VARNAM.PUTCHAR(CH);
READCHAR(CH);
END;
PUSH(EV.GET(VARNAM.STRIP));
END
ELSE IF OP = NUMBER THEN
BEGIN
NUMBR := 0;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH);
END;
IF CH = '.' THEN
BEGIN
REAL FAKTOR;
READCHAR(CH);
FAKTOR := 10;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR;
FAKTOR := 10 * FAKTOR;
READCHAR(CH);
END;
END;
PUSH(NUMBR);
END;
SKIPWHITESPACE(CH);
END BUSYBOX;
BOOLEAN PROCEDURE EVAL(INP); TEXT INP;
BEGIN
EVALUATEDERR :- NOTEXT;
STACKPOS := 0;
T :- COPY(INP.STRIP);
READCHAR(CH);
BUSYBOX(EXPRESSION, ERRORLABEL);
IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN
BEGIN
EVALUATED := POP;
EVAL := TRUE;
GOTO NOERRORLABEL;
END;
ERRORLABEL:
EVAL := FALSE;
IF EVALUATEDERR = NOTEXT THEN
EVALUATEDERR :- "INVALID EXPRESSION: " & INP;
NOERRORLABEL:
END EVAL;
REAL PROCEDURE RESULT;
RESULT := EVALUATED;
TEXT PROCEDURE ERR;
ERR :- EVALUATEDERR;
INTEGER EXPRESSION, TERM, FACTOR, POWER, NUMBER, VARIABLE;
CHARACTER TAB, LF, CR, SPACE, EOT, CH;
REAL ARRAY STACK(0:31);
INTEGER STACKPOS;
REAL EVALUATED;
TEXT EVALUATEDERR, T;
EXPRESSION := 1;
TERM := 2;
FACTOR := 3;
POWER := 4;
NUMBER := 5;
VARIABLE := 6;
TAB := CHAR(9);
LF := CHAR(10);
CR := CHAR(13);
SPACE := CHAR(32);
EOT := CHAR(0);
END EXPR;
REF(EXPR) EXA, EXB;
EXA :- NEW EXPR(NEW ENV.SET("X", 3));
EXB :- NEW EXPR(NEW ENV.SET("X", 5));
IF EXA.EVAL("2 ^ X") THEN
BEGIN
IF EXB.EVAL("2 ^ X")
THEN OUTFIX(EXB.RESULT - EXA.RESULT, 3, 10)
ELSE OUTTEXT(EXB.ERR)
END ELSE OUTTEXT(EXA.ERR);
OUTIMAGE;
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.
|
#SNOBOL4
|
SNOBOL4
|
compiled = code(' define("triple(x)") :(a);triple triple = 3 * x :(return)') :<compiled>
a x = 1
first = triple(x)
x = 3
output = triple(x) - first
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.
|
#D
|
D
|
import std.stdio, std.conv, std.algorithm, std.variant, std.uni,
std.functional, std.string;
alias Sexp = Variant;
struct Symbol {
private string name;
string toString() @safe const pure nothrow { return name; }
}
Sexp parseSexp(string txt) @safe pure /*nothrow*/ {
static bool isIdentChar(in char c) @safe pure nothrow {
return c.isAlpha || "0123456789!@#-".representation.canFind(c);
}
size_t pos = 0;
Sexp _parse() /*nothrow*/ {
auto i = pos + 1;
scope (exit)
pos = i;
if (txt[pos] == '"') {
while (txt[i] != '"' && i < txt.length)
i++;
i++;
return Sexp(txt[pos + 1 .. i - 1]);
} else if (txt[pos].isNumber) {
while (txt[i].isNumber && i < txt.length)
i++;
if (txt[i] == '.') {
i++;
while (txt[i].isNumber && i < txt.length)
i++;
auto aux = txt[pos .. i]; //
return aux.parse!double.Sexp;
}
auto aux = txt[pos .. i]; //
return aux.parse!ulong.Sexp;
} else if (isIdentChar(txt[pos])) {
while (isIdentChar(txt[i]) && i < txt.length)
i++;
return Sexp(Symbol(txt[pos .. i]));
} else if (txt[pos] == '(') {
Sexp[] lst;
while (txt[i] != ')') {
while (txt[i].isWhite)
i++;
pos = i;
lst ~= _parse;
i = pos;
while (txt[i].isWhite)
i++;
}
i = pos + 1;
return Sexp(lst);
}
return Sexp(null);
}
txt = txt.find!(not!isWhite);
return _parse;
}
void writeSexp(Sexp expr) {
if (expr.type == typeid(string)) {
write('"', expr, '"');
} else if (expr.type == typeid(Sexp[])) {
'('.write;
auto arr = expr.get!(Sexp[]);
foreach (immutable i, e; arr) {
e.writeSexp;
if (i + 1 < arr.length)
' '.write;
}
')'.write;
} else {
expr.write;
}
}
void main() {
auto pTest = `((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))`.parseSexp;
writeln("Parsed: ", pTest);
"Printed: ".write;
pTest.writeSexp;
}
|
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
|
#Julia
|
Julia
|
function fixtags(text::AbstractString)
langs = ["ada", "cpp-qt", "pascal", "lscript", "z80", "visualprolog",
"html4strict", "cil", "objc", "asm", "progress", "teraterm", "hq9plus",
"genero", "tsql", "email", "pic16", "tcl", "apt_sources", "io", "apache",
"vhdl", "avisynth", "winbatch", "vbnet", "ini", "scilab", "ocaml-brief",
"sas", "actionscript3", "qbasic", "perl", "bnf", "cobol", "powershell",
"php", "kixtart", "visualfoxpro", "mirc", "make", "javascript", "cpp",
"sdlbasic", "cadlisp", "php-brief", "rails", "verilog", "xml", "csharp",
"actionscript", "nsis", "bash", "typoscript", "freebasic", "dot",
"applescript", "haskell", "dos", "oracle8", "cfdg", "glsl", "lotusscript",
"mpasm", "latex", "sql", "klonec", "ruby", "ocaml", "smarty", "python",
"oracle11", "caddcl", "robots", "groovy", "smalltalk", "diff", "fortran",
"cfm", "lua", "modula3", "vb", "autoit", "java", "text", "scala",
"lotusformulas", "pixelbender", "reg", "_div", "whitespace", "providex",
"asp", "css", "lolcode", "lisp", "inno", "mysql", "plsql", "matlab",
"oobas", "vim", "delphi", "xorg_conf", "gml", "prolog", "bf", "per",
"scheme", "mxml", "d", "basic4gl", "m68k", "gnuplot", "idl", "abap",
"intercal", "c_mac", "thinbasic", "java5", "xpp", "boo", "klonecpp",
"blitzbasic", "eiffel", "povray", "c", "gettext"]
slang = "/lang"
code = "code"
for l in langs
text = replace(text, "<$l>","<lang $l>")
text = replace(text, "</$l>", "<$slang>")
end
text = replace(text, Regex("(?s)<$code (.+?)>(.*?)</$code>"), "<lang \\1>\\2<$slang>")
end
const txt = readstring(ARGS[1])
println(fixtags(txt))
|
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
|
#Lua
|
Lua
|
--thanks, random python guy
langs = {'ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog',
'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus',
'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache',
'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief',
'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell',
'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp',
'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp',
'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot',
'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript',
'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python',
'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran',
'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala',
'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex',
'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab',
'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per',
'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap',
'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp',
'blitzbasic', 'eiffel', 'povray', 'c', 'gettext'}
for line in io.lines() do
for i, v in ipairs(langs) do
line = line:gsub("<" .. v .. ">", "<lang " .. v .. ">")
line = line:gsub("<code " .. v .. ">", "<lang " .. v .. ">")
line = line:gsub("</" .. v .. ">", "</" .. "lang>") --the weird concatenation is to prevent the markup from breaking
line = line:gsub("</" .. "code>", "</" .. "lang>")
end
print(line)
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.
|
#Python
|
Python
|
import binascii
n = 9516311845790656153499716760847001433441357 # p*q = modulus
e = 65537
d = 5617843187844953170308463622230283376298685
message='Rosetta Code!'
print('message ', message)
hex_data = binascii.hexlify(message.encode())
print('hex data ', hex_data)
plain_text = int(hex_data, 16)
print('plain text integer ', plain_text)
if plain_text > n:
raise Exception('plain text too large for key')
encrypted_text = pow(plain_text, e, n)
print('encrypted text integer ', encrypted_text)
decrypted_text = pow(encrypted_text, d, n)
print('decrypted text integer ', decrypted_text)
print('message ', binascii.unhexlify(hex(decrypted_text)[2:]).decode()) # [2:] slicing, to strip the 0x part
|
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.
|
#Racket
|
Racket
|
#lang racket
(require math/number-theory)
(define-logger rsa)
(current-logger rsa-logger)
;; -| STRING TO NUMBER MAPPING |----------------------------------------------------------------------
(define (bytes->number B) ; We'll need our data in numerical form ..
(for/fold ((rv 0)) ((b B)) (+ b (* rv 256))))
(define (number->bytes N) ; .. and back again
(define (inr n b) (if (zero? n) b (inr (quotient n 256) (bytes-append (bytes (modulo n 256)) b))))
(inr N (bytes)))
;; -| RSA PUBLIC / PRIVATE FUNCTIONS |----------------------------------------------------------------
;; The basic definitions... pretty well lifted from the text book!
(define ((C e n) p)
;; Just do the arithmetic to demonstrate RSA...
;; breaking large messages into blocks is something for another day.
(unless (< p n) (raise-argument-error 'C (format "(and/c integer? (</c ~a))" n) p))
(modular-expt p e n))
(define ((P d n) c)
(modular-expt c d n))
;; -| RSA KEY GENERATION |----------------------------------------------------------------------------
;; Key generation
;; Full description of the steps can be found on Wikipedia
(define (RSA-keyset function-base-name)
(log-info "RSA-keyset: ~s" function-base-name)
(define max-k 4294967087)
;; I'm guessing this RNG is about as cryptographically strong as replacing spaces with tabs.
(define (big-random n-rolls)
(for/fold ((rv 1)) ((roll (in-range n-rolls 0 -1))) (+ (* rv (add1 max-k)) 1 (random max-k))))
(define (big-random-prime)
(define start-number (big-random (/ 1024 32)))
(log-debug "got large (possibly non-prime) number, finding next prime")
(next-prime (match start-number ((? odd? o) o) ((app add1 e) e))))
;; [1] Choose two distinct prime numbers p and q.
(log-debug "generating p")
(define p (big-random-prime))
(log-debug "p generated")
(log-debug "generating q")
(define q (big-random-prime))
(log-debug "q generated")
(log-info "primes generated")
;; [2] Compute n = pq.
(define n (* p q))
;; [3] Compute φ(n) = φ(p)φ(q) = (p − 1)(q − 1) = n - (p + q -1),
;; where φ is Euler's totient function.
(define φ (- n (+ p q -1)))
;; [4] Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e., e and φ(n) are
;; coprime. ... most commonly 2^16 + 1 = 65,537 ...
(define e (+ (expt 2 16) 1))
;; [5] Determine d as d ≡ e−1 (mod φ(n)); i.e., d is the multiplicative inverse of e (modulo φ(n)).
(log-debug "generating d")
(define d (modular-inverse e φ))
(log-info "d generated")
(values n e d))
;; -| GIVE A USABLE SET OF PRIVATE STUFF TO A USER |--------------------------------------------------
;; six values: the public (encrypt) function (numeric)
;; the private (decrypt) function (numeric)
;; the public (encrypt) function (bytes)
;; the private (decrypt) function (bytes)
;; private (list n e d)
;; public (list n e)
(define (RSA-key-pack #:function-base-name function-base-name)
(define (rnm-fn f s) (procedure-rename f (string->symbol (format "~a-~a" function-base-name s))))
(define-values (n e d) (RSA-keyset function-base-name))
(define my-C (rnm-fn (C e n) "C"))
(define my-P (rnm-fn (P d n) "P"))
(define my-encrypt (rnm-fn (compose number->bytes my-C bytes->number) "encrypt"))
(define my-decrypt (rnm-fn (compose number->bytes my-P bytes->number) "decrypt"))
(values my-C my-P my-encrypt my-decrypt (list n e d) (list n e)))
;; -| HEREON IS JUST A LOAD OF CHATTY DEMOS |---------------------------------------------------------
(define (narrated-encrypt-bytes C who plain-text)
(define plain-n (bytes->number plain-text))
(define cypher-n (C plain-n))
(define cypher-text (number->bytes cypher-n))
(printf #<<EOS
~a wants to send plain text: ~s
as number: ~s
cyphered number: ~s
sent by ~a over the public interwebs:
~s
...
EOS
who plain-text plain-n cypher-n who cypher-text)
cypher-text)
(define (narrated-decrypt-bytes P who cypher-text)
(define cypher-n (bytes->number cypher-text))
(define plain-n (P cypher-n))
(define plain-text (number->bytes plain-n))
(printf #<<EOS
...
~s
received by ~a
as number: ~s
decyphered (with P) number: ~s
decyphered text:
~s
EOS
cypher-text who cypher-n plain-n plain-text)
plain-text)
;; ENCRYPT AND DECRYPT A MESSAGE WITH THE e.g. KEYS
(define-values (given-n given-e given-d)
(values 9516311845790656153499716760847001433441357
65537
5617843187844953170308463622230283376298685))
;; Get the keys specific RSA functions
(for ((message-text (list #"hello world" #"TOP SECRET!")))
(define Bobs-public-function (C given-e given-n))
(define Bobs-private-function (P given-d given-n))
(define cypher-text (narrated-encrypt-bytes Bobs-public-function "Alice" message-text))
(define plain-text (narrated-decrypt-bytes Bobs-private-function "Bob" cypher-text))
plain-text)
;; Demonstrate with larger keys.
;; (And include a free recap on digital signatures, too)
(define-values (A-pub-C A-pvt-P A-pub-encrypt A-pvt-decrypt A-pvt-keys A-pub-keys)
(RSA-key-pack #:function-base-name 'Alice))
(define-values (B-pub-C B-pvt-P B-pub-encrypt B-pvt-decrypt B-pvt-keys B-pub-keys)
(RSA-key-pack #:function-base-name 'Bob))
;; Since p and q are random, it is possible that message' = "message modulo {A,B}-key-n" will be too
;; big for "message' modulo {B,A}-key-n", if that happens then I run the program again until it
;; works. Strictly, we need blocking of the signed message -- which is not yet implemented.
(let* ((plain-A-to-B #"Dear Bob, meet you in Lymm at 1200, Alice")
(signed-A-to-B (A-pvt-decrypt plain-A-to-B))
(unsigned-A-to-B (A-pub-encrypt signed-A-to-B))
(crypt-signed-A-to-B (B-pub-encrypt signed-A-to-B))
(decrypt-signed-A-to-B (B-pvt-decrypt crypt-signed-A-to-B))
(decrypt-verified-B (A-pub-encrypt decrypt-signed-A-to-B)))
(printf
#<<EOS
Alice wants to send ~s to Bob.
She "encrypts" with her private "decryption" key.
(A-prv msg) -> ~s
Only she could have done this (only she has the her private key data) -- so this is a signature on the
message. Anyone can verify the signature by "decrypting" the message with the public "encryption" key.
(A-pub (A-prv msg)) -> ~s
But anyone is able to do this, so there is no privacy here.
Everyone knows that it can only be Alice at Lymm at noon, but this message is for Bob's eyes only.
We need to encrypt this with his public key:
(B-pub (A-prv msg)) -> ~s
Which is what gets posted to alt.chat.secret-rendezvous
Bob decrypts this to get the signed message from Alice:
(B-prv (B-pub (A-prv msg))) -> ~s
And verifies Alice's signature:
(A-pub (B-prv (B-pub (A-prv msg)))) -> ~s
Alice genuinely sent the message.
And nobody else (on a.c.s-r, at least) has read it.
KEYS:
Alice's full set: ~s
Bob's full set: ~s
EOS
plain-A-to-B signed-A-to-B unsigned-A-to-B crypt-signed-A-to-B decrypt-signed-A-to-B
decrypt-verified-B A-pvt-keys B-pvt-keys))
|
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.
|
#Crystal
|
Crystal
|
def roll_stat
dices = Array(Int32).new(4) { rand(1..6) }
dices.sum - dices.min
end
def roll_character
loop do
stats = Array(Int32).new(6) { roll_stat }
return stats if stats.sum >= 75 && stats.count(&.>=(15)) >= 2
end
end
10.times do
stats = roll_character
puts "stats: #{stats}, sum is #{stats.sum}"
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.
|
#Delphi
|
Delphi
|
program RPG_Attributes_Generator;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections;
type
TListOfInt = class(TList<Integer>)
public
function Sum: Integer;
function FindAll(func: Tfunc<Integer, Boolean>): TListOfInt;
function Join(const sep: string): string;
end;
{ TListOfInt }
function TListOfInt.FindAll(func: Tfunc<Integer, Boolean>): TListOfInt;
var
Item: Integer;
begin
Result := TListOfInt.Create;
if Assigned(func) then
for Item in self do
if func(Item) then
Result.Add(Item);
end;
function TListOfInt.Join(const sep: string): string;
var
Item: Integer;
begin
Result := '';
for Item in self do
if Result.IsEmpty then
Result := Item.ToString
else
Result := Result + sep + Item.ToString;
end;
function TListOfInt.Sum: Integer;
var
Item: Integer;
begin
Result := 0;
for Item in self do
Inc(Result, Item);
end;
function GetThree(n: integer): TListOfInt;
var
i: Integer;
begin
Randomize;
Result := TListOfInt.Create;
for i := 0 to 3 do
Result.Add(Random(n) + 1);
Result.Sort;
Result.Delete(0);
end;
function GetSix(): TListOfInt;
var
i: Integer;
tmp: TListOfInt;
begin
Result := TListOfInt.Create;
for i := 0 to 5 do
begin
tmp := GetThree(6);
Result.Add(tmp.Sum);
tmp.Free;
end;
end;
const
GOOD_STR: array[Boolean] of string = ('low', 'good');
SUCCESS_STR: array[Boolean] of string = ('failure', 'success');
var
good: Boolean;
gs, hvcList: TListOfInt;
gss, hvc: Integer;
begin
good := false;
repeat
gs := GetSix();
gss := gs.Sum;
hvcList := gs.FindAll(
function(x: Integer): Boolean
begin
result := x > 14;
end);
hvc := hvcList.Count;
hvcList.Free;
Write(Format('Attribs: %s, sum=%d, (%s sum, high vals=%d)', [gs.Join(', '),
gss, GOOD_STR[gss >= 75], hvc]));
good := (gss >= 75) and (hvc > 1);
Writeln(' - ', SUCCESS_STR[good]);
gs.Free;
until good;
Readln;
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
|
#Racket
|
Racket
|
#lang racket
(define (sieve n)
(define non-primes '())
(define primes '())
(for ([i (in-range 2 (add1 n))])
(unless (member i non-primes)
(set! primes (cons i primes))
(for ([j (in-range (* i i) (add1 n) i)])
(set! non-primes (cons j non-primes)))))
(reverse primes))
(sieve 100)
|
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
|
Rosetta Code/Count examples
|
task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#AutoHotkey
|
AutoHotkey
|
UrlDownloadToFile
, http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml
, tasks.xml
FileRead, tasks, tasks.xml
pos = 0
quote = " ; "
regtitle := "<cm.*?title=" . quote . "(.*?)" . quote
While, pos := RegExMatch(tasks, regtitle, title, pos + 1)
{
UrlDownloadToFile
, % "http://www.rosettacode.org/w/index.php?title=" . title1 . "&action=raw"
, task.xml
FileRead, task, task.xml
RegExReplace(task, "\{\{header\|", "", count)
current := title1 . ": " . count . " examples.`n"
output .= current
TrayTip, current, % current
}
MsgBox % output
Return
|
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
|
#GAP
|
GAP
|
# First position is built-in
haystack := Eratosthenes(10000);;
needle := 8999;;
Position(haystack, needle);
# 1117
LastPosition := function(L, x)
local old, new;
old := 0;
new := 0;
while new <> fail do
new := Position(L, x, old);
if new <> fail then
old := new;
fi;
od;
return old;
end;
a := Shuffle(List([1 .. 100], x -> x mod 10));
# [ 0, 2, 4, 5, 3, 1, 0, 4, 8, 8, 2, 7, 6, 3, 3, 6, 4, 4, 3, 0, 7, 1, 8, 7, 2, 4, 7, 9, 4, 9, 4, 5, 9, 9, 6, 7, 8, 2, 3,
# 5, 1, 5, 4, 2, 0, 9, 6, 1, 1, 2, 2, 0, 5, 7, 6, 8, 8, 3, 1, 9, 5, 1, 9, 6, 8, 9, 2, 0, 6, 2, 1, 6, 1, 1, 2, 5, 3, 3,
# 0, 3, 5, 7, 5, 4, 6, 8, 0, 9, 8, 3, 7, 8, 0, 4, 9, 7, 0, 6, 5, 7 ]
Position(a, 0);
# 1
LastPosition(a, 0);
# 97
|
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.
|
#D
|
D
|
void main() {
import std.stdio, std.algorithm, std.conv, std.array, std.regex,
std.typecons, std.net.curl;
immutable r1 = `"title":"Category:([^"]+)"`;
const languages = get("www.rosettacode.org/w/api.php?action=query"~
"&list=categorymembers&cmtitle=Category:Pro"~
"gramming_Languages&cmlimit=500&format=json")
.matchAll(r1).map!q{ a[1].dup }.array;
auto pairs = get("www.rosettacode.org/w/index.php?" ~
"title=Special:Categories&limit=5000")
.matchAll(`title="Category:([^"]+)">[^<]+` ~
`</a>[^(]+\((\d+) members\)`)
.filter!(m => languages.canFind(m[1]))
.map!(m => tuple(m[2].to!uint, m[1].dup));
foreach (i, res; pairs.array.sort!q{a > b}.release)
writefln("%3d. %3d - %s", i + 1, res[]);
}
|
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.
|
#BaCon
|
BaCon
|
FUNCTION Rle_Encode$(txt$)
LOCAL result$, c$ = LEFT$(txt$, 1)
LOCAL total = 1
FOR x = 2 TO LEN(txt$)
IF c$ = MID$(txt$, x, 1) THEN
INCR total
ELSE
result$ = result$ & STR$(total) & c$
c$ = MID$(txt$, x, 1)
total = 1
END IF
NEXT
RETURN result$ & STR$(total) & c$
END FUNCTION
FUNCTION Rle_Decode$(txt$)
LOCAL nr$, result$
FOR x = 1 TO LEN(txt$)
IF REGEX(MID$(txt$, x, 1), "[[:digit:]]") THEN
nr$ = nr$ & MID$(txt$, x, 1)
ELSE
result$ = result$ & FILL$(VAL(nr$), ASC(MID$(txt$, x, 1)))
nr$ = ""
END IF
NEXT
RETURN result$
END FUNCTION
rle_data$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
PRINT "RLEData: ", rle_data$
encoded$ = Rle_Encode$(rle_data$)
PRINT "Encoded: ", encoded$
PRINT "Decoded: ", Rle_Decode$(encoded$)
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#11l
|
11l
|
F polar(r, theta)
R r * (cos(theta) + sin(theta) * 1i)
F croots(n)
R (0 .< n).map(k -> polar(1, 2 * k * math:pi / @n))
L(nr) 2..10
print(nr‘ ’croots(nr))
|
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
|
Roots of a quadratic function
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle non-real roots, but it need not check that
a
≠
0
{\displaystyle a\neq 0}
.
The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic.
The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other.
In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with
a
=
1
{\displaystyle a=1}
,
b
=
−
10
5
{\displaystyle b=-10^{5}}
, and
c
=
1
{\displaystyle c=1}
.
(For double-precision floats, set
b
=
−
10
9
{\displaystyle b=-10^{9}}
.)
Consider the following implementation in Ada:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Quadratic_Equation is
type Roots is array (1..2) of Float;
function Solve (A, B, C : Float) return Roots is
SD : constant Float := sqrt (B**2 - 4.0 * A * C);
AA : constant Float := 2.0 * A;
begin
return ((- B + SD) / AA, (- B - SD) / AA);
end Solve;
R : constant Roots := Solve (1.0, -10.0E5, 1.0);
begin
Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2)));
end Quadratic_Equation;
Output:
X1 = 1.00000E+06 X2 = 0.00000E+00
As we can see, the second root has lost all significant figures. The right answer is that X2 is about
10
−
6
{\displaystyle 10^{-6}}
. The naive method is numerically unstable.
Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters
q
=
a
c
/
b
{\displaystyle q={\sqrt {ac}}/b}
and
f
=
1
/
2
+
1
−
4
q
2
/
2
{\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2}
and the two roots of the quardratic are:
−
b
a
f
{\displaystyle {\frac {-b}{a}}f}
and
−
c
b
f
{\displaystyle {\frac {-c}{bf}}}
Task: do it better. This means that given
a
=
1
{\displaystyle a=1}
,
b
=
−
10
9
{\displaystyle b=-10^{9}}
, and
c
=
1
{\displaystyle c=1}
, both of the roots your program returns should be greater than
10
−
11
{\displaystyle 10^{-11}}
. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle
b
=
−
10
6
{\displaystyle b=-10^{6}}
. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of
"What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
|
#11l
|
11l
|
F quad_roots(a, b, c)
V sqd = Complex(b^2 - 4*a*c) ^ 0.5
R ((-b + sqd) / (2 * a),
(-b - sqd) / (2 * a))
V testcases = [(3.0, 4.0, 4 / 3),
(3.0, 2.0, -1.0),
(3.0, 2.0, 1.0),
(1.0, -1e9, 1.0),
(1.0, -1e100, 1.0)]
L(a, b, c) testcases
V (r1, r2) = quad_roots(a, b, c)
print(r1, end' ‘ ’)
print(r2)
|
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
|
#APL
|
APL
|
r1 ← ⎕UCS ∘ {+/⍵,13×(⍵≥65)∧(⍵<78),(-(⍵≥78)∧(⍵≤90)),(⍵≥97)∧(⍵<110),(-(⍵≥110)∧(⍵≤122))} ∘ ⎕UCS
rot13 ← { r1 ¨ ⍵ }
|
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 }
|
#Fortran
|
Fortran
|
program rungekutta
implicit none
integer, parameter :: dp = kind(1d0)
real(dp) :: t, dt, tstart, tstop
real(dp) :: y, k1, k2, k3, k4
tstart = 0.0d0
tstop = 10.0d0
dt = 0.1d0
y = 1.0d0
t = tstart
write (6, '(a,f4.1,a,f12.8,a,es13.6)') 'y(', t, ') = ', y, ' error = ', &
abs(y-(t**2+4)**2/16)
do while (t < tstop)
k1 = dt*f(t, y)
k2 = dt*f(t+dt/2, y+k1/2)
k3 = dt*f(t+dt/2, y+k2/2)
k4 = dt*f(t+dt, y+k3)
y = y+(k1+2*(k2+k3)+k4)/6
t = t+dt
if (abs(nint(t)-t) <= 1d-12) then
write (6, '(a,f4.1,a,f12.8,a,es13.6)') 'y(', t, ') = ', y, ' error = ', &
abs(y-(t**2+4)**2/16)
end if
end do
contains
function f(t,y)
real(dp), intent(in) :: t, y
real(dp) :: f
f = t*sqrt(y)
end function f
end program rungekutta
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Clojure
|
Clojure
|
(require
'[clojure.xml :as xml]
'[clojure.set :as set]
'[clojure.string :as string])
(import '[java.net URLEncoder])
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#E
|
E
|
#!/usr/bin/env rune
# NOTE: This program will not work in released E, because TermL is an
# imperfect superset of JSON in that version: it does not accept "\/".
# If you build E from the latest source in SVN then it will work.
#
# Usage: rosettacode-cat-subtract.e [<lang e>]
#
# Prints a list of tasks which have not been completed in the language.
# If unspecified, the default language is E.
pragma.syntax("0.9")
pragma.enable("accumulator")
def termParser := <import:org.quasiliteral.term.makeTermParser>
def jURLEncoder := <unsafe:java.net.makeURLEncoder>
def urlEncode(text) {
return jURLEncoder.encode(text, "UTF-8")
}
/** Convert JSON-as-term-tree to the corresponding natural E data structures. */
def jsonTermToData(term) {
switch (term) {
# JSON object to E map
match term`{@assocs*}` {
return accum [].asMap() for term`@{key :String}: @valueJson` in assocs {
_.with(key, jsonTermToData(valueJson))
}
}
# JSON array to E list
match term`[@elements*]` {
return accum [] for elem in elements { _.with(jsonTermToData(elem)) }
}
# Literals just need to be coerced
match lit :any[String, int, float64] {
return lit
}
# Doesn't support true/false/null, but we don't need that for this application.
}
}
def fetchCategoryAccum(name, membersSoFar :Set, extraArgs) {
stderr.println(`Fetching Category:$name $extraArgs...`)
def categoryAPIResource := <http>[`//rosettacode.org/w/api.php?` +
`action=query&list=categorymembers&cmtitle=Category:${urlEncode(name)}&` +
`format=json&cmlimit=500&cmprop=title$extraArgs`]
def members :=
when (def responseJSON := categoryAPIResource <- getTwine()) -> {
# stderr.println(`Fetched Category:$name $extraArgs, parsing...`)
def response := jsonTermToData(termParser(responseJSON))
# stderr.println(`Parsed Category:$name $extraArgs response, extracting data...`)
def [
"query" => ["categorymembers" => records],
"query-continue" => continueData := null
] := response
def members := accum membersSoFar for record in records { _.with(record["title"]) }
switch (continueData) {
match ==null {
stderr.println(`Got all ${members.size()} for Category:$name.`)
members
}
match ["categorymembers" => ["cmcontinue" => continueParam]] {
stderr.println(`Fetched ${members.size()} members for Category:$name...`)
fetchCategoryAccum(name, members, `&cmcontinue=` + urlEncode(continueParam))
}
}
} catch p { throw(p) }
return members
}
def fetchCategory(name) {
return fetchCategoryAccum(name, [].asSet(), "")
}
# Interpret program arguments
def lang := switch (interp.getArgs()) {
match [lang] { lang }
match [] { "E" }
}
# Fetch categories
when (def allTasks := fetchCategory("Programming_Tasks"),
def doneTasks := fetchCategory(lang),
def omitTasks := fetchCategory(lang + "/Omit")
) -> {
# Compute difference and report
def notDoneTasks := allTasks &! (doneTasks | omitTasks)
println()
println("\n".rjoin(notDoneTasks.getElements().sort()))
} catch p {
# Whoops, something went wrong
stderr.println(`$p${p.eStack()}`)
}
|
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.
|
#Tcl
|
Tcl
|
proc eval_twice {func a b} {
set x $a
set 1st [expr $func]
set x $b
set 2nd [expr $func]
expr {$2nd - $1st}
}
puts [eval_twice {2 ** $x} 3 5] ;# ==> 24
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#TI-89_BASIC
|
TI-89 BASIC
|
evalx(prog, a, b)
Func
Local x,eresult1,eresult2
a→x
expr(prog)→eresult1
b→x
expr(prog)→eresult2
Return eresult2-eresult1
EndFunc
■ evalx("ℯ^x", 0., 1)
1.71828
|
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.
|
#EchoLisp
|
EchoLisp
|
(define input-string #'((data "quoted data" 123 4.5)\n(data (!@# (4.5) "(more" "data)")))'#)
input-string
→ "((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))"
(define s-expr (read-from-string input-string))
s-expr
→ ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))
(first s-expr)
→ (data "quoted data" 123 4.5)
(first(first s-expr))
→ data
(first(rest s-expr))
→ (data (!@# (4.5) "(more" "data)"))
|
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
|
#Maple
|
Maple
|
#Used <#/lang> to desensitize wiki
txt := FileTools[Text][ReadFile]("C:/Users/username/Desktop/text.txt"):
#langs should be a real list of programming languages
langs := ['foo', 'bar', 'baz', 'barf'];
for lan in langs do
txt := StringTools:-SubstituteAll(txt, cat("<", lan, ">"), cat ("<lang ", lan, ">")):
txt := StringTools:-SubstituteAll(txt, cat("</", lan, ">"), "<#/lang>"):
txt := StringTools:-SubstituteAll(txt, cat("<code ", lan, ">"), cat ("<lang ", lan, ">")):
txt := StringTools:-SubstituteAll(txt, "</code>", "<#/lang>"):
end do;
print(txt);
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
StringReplace[Import["wikisource.txt"],
{"</"~~Shortest[__]~~">"->"
|
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
|
#Nim
|
Nim
|
import re, strutils
const
Langs = ["ada", "cpp-qt", "pascal", "lscript", "z80", "visualprolog",
"html4strict", "cil", "objc", "asm", "progress", "teraterm", "hq9plus",
"genero", "tsql", "email", "pic16", "tcl", "apt_sources", "io", "apache",
"vhdl", "avisynth", "winbatch", "vbnet", "ini", "scilab", "ocaml-brief",
"sas", "actionscript3", "qbasic", "perl", "bnf", "cobol", "powershell",
"php", "kixtart", "visualfoxpro", "mirc", "make", "javascript", "cpp",
"sdlbasic", "cadlisp", "php-brief", "rails", "verilog", "xml", "csharp",
"actionscript", "nsis", "bash", "typoscript", "freebasic", "dot",
"applescript", "haskell", "dos", "oracle8", "cfdg", "glsl", "lotusscript",
"mpasm", "latex", "sql", "klonec", "ruby", "ocaml", "smarty", "python",
"oracle11", "caddcl", "robots", "groovy", "smalltalk", "diff", "fortran",
"cfm", "lua", "modula3", "vb", "autoit", "java", "text", "scala",
"lotusformulas", "pixelbender", "reg", "_div", "whitespace", "providex",
"asp", "css", "lolcode", "lisp", "inno", "mysql", "plsql", "matlab",
"oobas", "vim", "delphi", "xorg_conf", "gml", "prolog", "bf", "per",
"scheme", "mxml", "d", "basic4gl", "m68k", "gnuplot", "idl", "abap",
"intercal", "c_mac", "thinbasic", "java5", "xpp", "boo", "klonecpp",
"blitzbasic", "eiffel", "povray", "c", "gettext"]
var text = stdin.readAll()
for lang in Langs:
text = text.replace("<$#>" % lang, "<lang $#>" % lang)
text = text.replace("</$#>" % lang, "
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.