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:
... | #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... |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users | Rosetta Code/Rank languages by number of users | Task
Sort most popular programming languages based on the number of users on Rosetta Code.
Show the languages with at least 100 users.
A method to solve the task
Users of a computer programming language X are those referenced in the page:
https://rosettacode.org/wiki/Category:X_User, or preferably:
ht... | #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 ... |
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... | #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)
... |
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... | #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).
... | #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,... |
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 <- r... |
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... | #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[mes... |
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... | #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
... |
http://rosettacode.org/wiki/RPG_attributes_generator | RPG attributes generator | RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three... | #C.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)... |
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... | #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,
... |
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 ... | #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,... | #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 b... |
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... | #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 inpu... | #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!}'
TA... |
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:
... | #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... |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users | Rosetta Code/Rank languages by number of users | Task
Sort most popular programming languages based on the number of users on Rosetta Code.
Show the languages with at least 100 users.
A method to solve the task
Users of a computer programming language X are those referenced in the page:
https://rosettacode.org/wiki/Category:X_User, or preferably:
ht... | #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 = ... |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users | Rosetta Code/Rank languages by number of users | Task
Sort most popular programming languages based on the number of users on Rosetta Code.
Show the languages with at least 100 users.
A method to solve the task
Users of a computer programming language X are those referenced in the page:
https://rosettacode.org/wiki/Category:X_User, or preferably:
ht... | #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
... |
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... | #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... | #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).
... | #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;
... |
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... |
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... | #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... |
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... | #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) = ""
... |
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... | #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
ran... |
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... | #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 ... | #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,... | #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&... |
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... | #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 strin... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #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 ... |
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:
... | #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
... |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_number_of_users | Rosetta Code/Rank languages by number of users | Task
Sort most popular programming languages based on the number of users on Rosetta Code.
Show the languages with at least 100 users.
A method to solve the task
Users of a computer programming language X are those referenced in the page:
https://rosettacode.org/wiki/Category:X_User, or preferably:
ht... | #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"... |
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... | #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... |
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).
... | #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.isAr... |
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 ... |
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... | #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) = @_;
... |
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... | #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 ... |
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... | #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 ... | #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(nee... |
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,... | #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=ca... |
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... | #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
]... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #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... |
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:
... | #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... |
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:
... | #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)... |
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... | #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.Messa... |
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... | #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... | #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... | #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).
... | #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\")"))... |
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", "... |
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... | #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
-- ... |
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... | #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))) #'<))))
(... |
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... | #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 ar... |
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 ... | #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 ... |
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,... | #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::... |
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... | #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)
... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #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 := "nopq... |
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:
... | #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... |
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... | #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-... |
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... | #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... | #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).
... | #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... |
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'),... |
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... | #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
(l... |
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... | #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 ... |
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... | #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 ... |
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... | #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 AP... | #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 Aw... |
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 ... | #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 = sN... |
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,... | #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 n... |
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... | #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 inpu... | #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
... |
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:
... | #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 ... |
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... | #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... |
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... | #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;
... |
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... | #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).
... | #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 ch... |
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags | Rosetta Code/Fix code tags | Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
| #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", "winb... |
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',
'... |
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... | #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 =... |
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... | #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))))
(defin... |
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... | #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.s... |
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... | #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;
... |
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... | #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 AP... | #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, po... |
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 ... | #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;
... |
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,... | #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"~
... |
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... | #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
... |
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 n... | #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... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #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:
... | #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 = ', &
a... |
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... | #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... | #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... |
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... | #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... | #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).
... | #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)")))
(... |
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 := Str... |
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", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.