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/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.
|
#Raku
|
Raku
|
constant $n = 9516311845790656153499716760847001433441357;
constant $e = 65537;
constant $d = 5617843187844953170308463622230283376298685;
my $secret-message = "ROSETTA CODE";
package Message {
my @alphabet = slip('A' .. 'Z'), ' ';
my $rad = +@alphabet;
my %code = @alphabet Z=> 0 .. *;
subset Text of Str where /^^ @alphabet+ $$/;
our sub encode(Text $t) {
[+] %code{$t.flip.comb} Z* (1, $rad, $rad*$rad ... *);
}
our sub decode(Int $n is copy) {
@alphabet[
gather loop {
take $n % $rad;
last if $n < $rad;
$n div= $rad;
}
].join.flip;
}
}
use Test;
plan 1;
say "Secret message is $secret-message";
say "Secret message in integer form is $_" given
my $numeric-message = Message::encode $secret-message;
say "After exponentiation with public exponent we get: $_" given
my $numeric-cipher = expmod $numeric-message, $e, $n;
say "This turns into the string $_" given
my $text-cipher = Message::decode $numeric-cipher;
say "If we re-encode it in integer form we get $_" given
my $numeric-cipher2 = Message::encode $text-cipher;
say "After exponentiation with SECRET exponent we get: $_" given
my $numeric-message2 = expmod $numeric-cipher2, $d, $n;
say "This turns into the string $_" given
my $secret-message2 = Message::decode $numeric-message2;
is $secret-message, $secret-message2, "the message has been correctly decrypted";
|
http://rosettacode.org/wiki/RPG_attributes_generator
|
RPG attributes generator
|
RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
The total of all character attributes must be at least 75.
At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
Task
Write a program that:
Generates 4 random, whole values between 1 and 6.
Saves the sum of the 3 largest values.
Generates a total of 6 values this way.
Displays the total, and all 6 values once finished.
The order in which each value was generated must be preserved.
The total of all 6 values must be at least 75.
At least 2 of the values must be 15 or more.
|
#Dyalect
|
Dyalect
|
func getThree(n) {
var g3 = []
for i in 0..33 {
g3.Add(rnd(max: n) + 1)
}
g3.Sort()
g3.RemoveAt(0)
g3
}
func getSix() {
var g6 = []
for i in 0..5 {
g6.Add(getThree(6).Sum())
}
g6
}
func Array.Sum() {
var acc = 0
for x in this {
acc += x
}
acc
}
func Array.FindAll(pred) {
for x in this when pred(x) {
yield x
}
}
var good = false
while !good {
var gs = getSix()
var gss = gs.Sum()
var hvc = gs.FindAll(x => x > 14).Length()
print("attribs: \(gs), sum=\(gss), ", terminator: "")
let gl = gss >= 75 ? "good" : "low"
print("(\(gl) sum, high vals=\(hvc))", terminator: "")
good = gs.Sum() >= 75 && hvc > 1
print(" - " + (good ? "success" : "failure"))
}
|
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.
|
#EasyLang
|
EasyLang
|
len v[] 6
repeat
vsum = 0
vmin = 0
for i range 6
val = 0
min = 6
for j range 4
h = random 6 + 1
val += h
if h < min
min = h
.
.
val -= min
v[i] = val
if val >= 15
vmin += 1
.
vsum += val
.
until vsum >= 75 and vmin >= 2
.
print "Attributes: " & " " & v[]
print "Total: " & " " & vsum
|
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
|
#Raku
|
Raku
|
sub sieve( Int $limit ) {
my @is-prime = False, False, slip True xx $limit - 1;
gather for @is-prime.kv -> $number, $is-prime {
if $is-prime {
take $number;
loop (my $s = $number**2; $s <= $limit; $s += $number) {
@is-prime[$s] = False;
}
}
}
}
(sieve 100).join(",").say;
|
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
|
#BBC_BASIC
|
BBC BASIC
|
VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF
special$ = "+()'"
url$ = "http://www.rosettacode.org/w/api.php?action=query" + \
\ "&list=categorymembers&cmtitle=Category:Programming_Tasks" + \
\ "&cmlimit=500&format=xml"
file$ = @tmp$ + "tasks.xml"
SYS UDTF, 0, url$, file$, 0, 0 TO fail%
IF fail% ERROR 100, "File download failed (tasks)"
Total% = 0
file% = OPENIN(file$)
WHILE NOT EOF#file%
a$ = GET$#file%
i% = 0
REPEAT
i% = INSTR(a$, "title=", i%+1)
IF i% THEN
j% = INSTR(a$, ">", i%)
title$ = MID$(a$, i%+7, j%-i%-10)
REM Replace HTML codes:
REPEAT
k% = INSTR(title$, "&")
IF k% THEN
l% = INSTR(title$, ";", k%)
title$ = LEFT$(title$,k%-1) + \
\ FNhtml(MID$(title$,k%,l%-k%+1)) + MID$(title$,l%+1)
ENDIF
UNTIL k% = 0
t$ = title$
REM Substitute characters not allowed in a URL:
FOR s% = 1 TO LEN(special$)
REPEAT
s$ = MID$(special$, s%, 1)
k% = INSTR(t$, s$)
IF k% t$ = LEFT$(t$,k%-1) + "%" + STR$~ASCs$ + MID$(t$,k%+1)
UNTIL k% = 0
NEXT
url$ = "http://www.rosettacode.org/w/index.php?title=" + t$ + \
\ "&action=raw"
file$ = @tmp$ + "title.htm"
SYS UDTF, 0, url$, file$, 0, 0 TO fail%
IF fail% ERROR 100, "File download failed " + t$
examples% = 0
task% = OPENIN(file$)
WHILE NOT EOF#task%
IF INSTR(GET$#task%, "=={{header|") examples% += 1
ENDWHILE
CLOSE #task%
Total% += examples%
PRINT title$ ": " ; examples% " examples."
ENDIF
UNTIL i% = 0
i% = INSTR(a$, "cmcontinue=")
IF i% THEN
CLOSE #file%
j% = INSTR(a$, """", i%+1)
k% = INSTR(a$, """", j%+1)
url$ = "http://www.rosettacode.org/w/api.php?action=query" + \
\ "&list=categorymembers&cmtitle=Category:Programming_Tasks" + \
\ "&cmlimit=500&format=xml&cmcontinue=" + MID$(a$,j%+1,k%-j%)
REPEAT
i% = INSTR(url$, "|")
IF i% url$ = LEFT$(url$,i%-1) + "%7C" + MID$(url$,i%+1)
UNTIL i% = 0
file$ = @tmp$ + "tasks.xml"
SYS UDTF, 0, url$, file$, 0, 0 TO fail%
IF fail% ERROR 100, "File download failed (continue)"
file% = OPENIN(file$)
ENDIF
ENDWHILE
CLOSE #file%
PRINT ' "Total: " ; Total% " examples."
END
DEF FNhtml(h$)
IF LEFT$(h$,2) = "&#" THEN = CHR$(VALMID$(h$,3))
CASE h$ OF
WHEN """: = """"
ENDCASE
= h$
|
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
|
#Bracmat
|
Bracmat
|
( ( get-page
=
. sys$(str$("wget -q -O wget.out \"" !arg \"))
& get$("wget.out",HT ML)
)
& get-page$"http://rosettacode.org/wiki/Category:Programming_Tasks"
: ? (table.?) ?tasklist (.table.) ?
& 0:?list
& whl
' ( !tasklist
: ?
( a
. (href.@(?:"/wiki/" ?href)) (title.?title)
& get-page$(str$("http://rosettacode.org/wiki/" !href))
: ?task
& 0:?cnt
& whl
' ( !task
: ?
( (span.(class.mw-headline) (id.?))
?span
(.span.)
?task
& !span
: ?
( a
. (href.@(?:"/wiki/Category:" ?))
(title.@(?:"Category:" ?))
)
@
(.a.)
?
)
& 1+!cnt:?cnt
)
& (!cnt.!title)+!list:?list
)
?tasklist
)
& lst$(list,taskfreq,NEW)
)
|
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
|
#Go
|
Go
|
package main
var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty",
"Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant",
"television", "soap", "methamphetamine", "severed cat heads", "foo",
"bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo",
"bar", "thud", "grunt", "foo", "bar", "bletch", "foo", "bar", "fum",
"fred", "jim", "sheila", "barney", "flarp", "zxc", "spqr", ";wombat",
"shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo",
"bar", "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo",
"pluto", "paperino", "aap", "noot", "mies", "oogle", "foogle", "boogle",
"zork", "gork", "bork", "sodium", "phosphorous", "californium",
"copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper",
"helium", "sulfur"}
|
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.
|
#Delphi
|
Delphi
|
program Rank_languages_by_popularity;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
IdHttp,
IdBaseComponent,
IdComponent,
IdIOHandler,
IdIOHandlerSocket,
IdIOHandlerStack,
IdSSL,
IdSSLOpenSSL,
System.RegularExpressions,
System.Generics.Collections,
System.Generics.Defaults;
const
AURL = 'https://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000';
UserAgent =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36';
type
TPair = record
Language: string;
Users: Integer;
constructor Create(lang, user: string);
end;
TPairs = TList<TPair>;
{ TPair }
constructor TPair.Create(lang, user: string);
begin
Language := lang;
Users := StrToIntDef(user, 0);
end;
function GetFullCode: string;
begin
with TIdHttp.create(nil) do
begin
HandleRedirects := True;
Request.UserAgent := UserAgent;
IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
Result := Get(AURL);
IOHandler.Free;
Free;
end;
end;
function GetList(const Code: string): TPairs;
var
RegularExpression: TRegEx;
Match: TMatch;
language, users: string;
begin
Result := TPairs.Create;
RegularExpression.Create('>(?<LANG>[^<,;]*)<\/a>.. \((?<USERS>[,\d]*)');
Match := RegularExpression.Match(Code);
while Match.Success do
begin
users := Match.Groups.Item['USERS'].Value.Replace(',', '');
language := Match.Groups.Item['LANG'].Value;
Result.Add(TPair.Create(language, users));
Match := Match.NextMatch;
end;
end;
procedure Sort(List: TPairs);
begin
List.Sort(TComparer<TPair>.Construct(
function(const Left, Right: TPair): Integer
begin
result := Right.Users - Left.Users;
if result = 0 then
result := CompareText(Left.Language, Right.Language);
end));
end;
function SumUsers(List: TPairs): Cardinal;
var
p: TPair;
begin
Result := 0;
for p in List do
begin
Inc(Result, p.Users);
end;
end;
var
Data: TStringList;
Code, line: string;
List: TPairs;
i: Integer;
begin
Data := TStringList.Create;
Writeln('Downloading code...');
Code := GetFullCode;
data.Clear;
List := GetList(Code);
Sort(List);
Writeln('Total languages: ', List.Count);
Writeln('Total Users: ', SumUsers(List));
Writeln('Top 10:'#10);
for i := 0 to List.Count - 1 do
begin
line := Format('%5dth %5d %s', [i + 1, List[i].users, List[i].language]);
Data.Add(line);
if i < 10 then
Writeln(line);
end;
Data.SaveToFile('Rank.txt');
List.Free;
Data.Free;
Readln;
end.
|
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.
|
#BASIC
|
BASIC
|
DECLARE FUNCTION RLDecode$ (i AS STRING)
DECLARE FUNCTION RLEncode$ (i AS STRING)
DIM initial AS STRING, encoded AS STRING, decoded AS STRING
INPUT "Type something: ", initial
encoded = RLEncode(initial)
decoded = RLDecode(encoded)
PRINT initial
PRINT encoded
PRINT decoded
FUNCTION RLDecode$ (i AS STRING)
DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING
FOR Loop0 = 1 TO LEN(i)
m = MID$(i, Loop0, 1)
SELECT CASE m
CASE "0" TO "9"
rCount = rCount + m
CASE ELSE
IF LEN(rCount) THEN
outP = outP + STRING$(VAL(rCount), m)
rCount = ""
ELSE
outP = outP + m
END IF
END SELECT
NEXT
RLDecode$ = outP
END FUNCTION
FUNCTION RLEncode$ (i AS STRING)
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM Loop0 AS LONG, rCount AS LONG
tmp1 = MID$(i, 1, 1)
tmp2 = tmp1
rCount = 1
FOR Loop0 = 2 TO LEN(i)
tmp1 = MID$(i, Loop0, 1)
IF tmp1 <> tmp2 THEN
outP = outP + LTRIM$(RTRIM$(STR$(rCount))) + tmp2
tmp2 = tmp1
rCount = 1
ELSE
rCount = rCount + 1
END IF
NEXT
outP = outP + LTRIM$(RTRIM$(STR$(rCount)))
outP = outP + tmp2
RLEncode$ = outP
END FUNCTION
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;
procedure Roots_Of_Unity is
Root : Complex;
begin
for N in 2..10 loop
Put_Line ("N =" & Integer'Image (N));
for K in 0..N - 1 loop
Root :=
Compose_From_Polar
( Modulus => 1.0,
Argument => Float (K),
Cycle => Float (N)
);
-- Output
Put (" k =" & Integer'Image (K) & ", ");
if Re (Root) < 0.0 then
Put ("-");
else
Put ("+");
end if;
Put (abs Re (Root), Fore => 1, Exp => 0);
if Im (Root) < 0.0 then
Put ("-");
else
Put ("+");
end if;
Put (abs Im (Root), Fore => 1, Exp => 0);
Put_Line ("i");
end loop;
end loop;
end Roots_Of_Unity;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
FORMAT complex fmt=$g(-6,4)"⊥"g(-6,4)$;
FOR root FROM 2 TO 10 DO
printf(($g(4)$,root));
FOR n FROM 0 TO root-1 DO
printf(($xf(complex fmt)$,complex exp( 0 I 2*pi*n/root)))
OD;
printf($l$)
OD
|
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.
|
#Ada
|
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);
X : Float;
begin
if B < 0.0 then
X := (- B + SD) / (2.0 * A);
return (X, C / (A * X));
else
X := (- B - SD) / (2.0 * A);
return (C / (A * X), X);
end if;
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;
|
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
|
#AppleScript
|
AppleScript
|
to rot13(textString)
do shell script "tr a-zA-Z n-za-mN-ZA-M <<<" & quoted form of textString
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 }
|
#FreeBASIC
|
FreeBASIC
|
' version 03-10-2015
' compile with: fbc -s console
' translation of BBC BASIC
Dim As Double y = 1, t, actual, k1, k2, k3, k4
Print
For i As Integer = 0 To 100
t = i / 10
If t = Int(t) Then
actual = ((t ^ 2 + 4) ^ 2) / 16
Print "y("; Str(t); ") ="; y ; Tab(27); "Error = "; actual - y
End If
k1 = t * Sqr(y)
k2 = (t + 0.05) * Sqr(y + 0.05 * k1)
k3 = (t + 0.05) * Sqr(y + 0.05 * k2)
k4 = (t + 0.10) * Sqr(y + 0.10 * k3)
y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6
Next i
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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 Wiki's API documentation at, API:Query
|
#Erlang
|
Erlang
|
-module( find_unimplemented_tasks ).
-include_lib( "xmerl/include/xmerl.hrl" ).
-export( [init_http/0, per_language/1, rosetta_code_list_of/1] ).
init_http() ->
application:start( inets ).
per_language( Language ) ->
ok = init_http(),
Tasks = rosetta_code_list_of( "Programming_Tasks" ),
Uninplemented = Tasks -- rosetta_code_list_of( Language ),
io:fwrite( "Unimplemented total: ~p~n", [erlang:length(Uninplemented)] ),
[io:fwrite("~p~n", [X]) || X <- Uninplemented].
rosetta_code_list_of( Category ) ->
URL = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmlimit=500&format=xml&cmtitle=Category:"
++ Category,
title_contents( URL, "", [] ).
title_contents( URL, Continue, Acc ) ->
{ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( URL ++ Continue ),
{XML, _} = xmerl_scan:string( Body ),
News = xml_selection( "title", XML ),
New_continue = title_contents_url_continue( xml_selection("cmcontinue", XML) ),
title_contents_continue( URL, New_continue, Acc ++ News ).
title_contents_continue( _URL, "", Acc ) -> Acc;
title_contents_continue( URL, Continue, Acc ) -> title_contents( URL, Continue, Acc ).
title_contents_url_continue( [] ) -> "";
title_contents_url_continue( [Continue | _] ) -> "&cmcontinue=" ++ Continue.
xml_selection( Selection, XML ) ->
[lists:map( fun xml_8211/1, X) || #xmlAttribute{value=X} <- xmerl_xpath:string("//@" ++ Selection, XML)].
xml_8211( 8211 ) -> $-;
xml_8211( 924 ) -> $\s;
xml_8211( 1050 ) -> $\s;
xml_8211( 1052 ) -> $\s;
xml_8211( Character ) -> Character.
|
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.
|
#Transd
|
Transd
|
#lang transd
MainModule: {
code: "(+ 5 x)",
_start: (lambda (textout
(- (to-Int (with x 100 (snd (eval code))))
(to-Int (with x 1 (snd (eval code)))))
))
}
|
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.
|
#TXR
|
TXR
|
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
(- (eval ^(let ((x ,x1)) ,code-fragment))
(eval ^(let ((x ,x0)) ,code-fragment))))
(eval-subtract-for-two-values-of-x 1 2) ;; yields -4.67077427047161
|
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.
|
#F.23
|
F#
|
module SExpr
(* This module is a very simple port of the OCaml version to F# (F-Sharp) *)
(* The original OCaml setatment is comment out and the F# statement(s) follow *)
(* Port performed by Bob Elward 23 Feb 2020 *)
(* The .Net standard would use "+" and not "^" for string concatenation *)
(* I kept the "^" to be compatable with the "ml" standard *)
(* The line below eliminates the warning/suggestion to use "+" *)
#nowarn "62"
(** This module is a very simple parsing library for S-expressions. *)
(* Copyright (C) 2009 Florent Monnier, released under MIT license. *)
(* modified to match the task description *)
(* Code obtained from: https://rosettacode.org/wiki/S-Expressions#OCaml *)
(* Note: The type below defines the grammar for this S-Expression (S-Expr).
An S-Expr is either an Atom or an S-Expr
*)
open System.Text
open System.IO
open System
type sexpr = Atom of string | Expr of sexpr list
type state =
| Parse_root of sexpr list
| Parse_content of sexpr list
| Parse_word of StringBuilder * sexpr list
| Parse_string of bool * StringBuilder * sexpr list
let parse pop_char =
let rec aux st =
match pop_char() with
| None ->
begin match st with
| Parse_root sl -> (List.rev sl)
| Parse_content _
| Parse_word _
| Parse_string _ ->
failwith "Parsing error: content not closed by parenthesis"
end
| Some c ->
match c with
| '(' ->
begin match st with
| Parse_root sl ->
let this = aux(Parse_content []) in
aux(Parse_root((Expr this)::sl))
| Parse_content sl ->
let this = aux(Parse_content []) in
aux(Parse_content((Expr this)::sl))
| Parse_word(w, sl) ->
let this = aux(Parse_content []) in
(* aux(Parse_content((Expr this)::Atom(Buffer.contents w)::sl)) *)
aux(Parse_content((Expr this)::Atom(w.ToString())::sl))
| Parse_string(_, s, sl) ->
//Buffer.add_char s c;
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
end
| ')' ->
begin match st with
| Parse_root sl ->
failwith "Parsing error: closing parenthesis without openning"
| Parse_content sl -> (List.rev sl)
(* | Parse_word(w, sl) -> List.rev(Atom(Buffer.contents w)::sl) *)
| Parse_word(w, sl) -> List.rev(Atom(w.ToString())::sl)
| Parse_string(_, s, sl) ->
(* Buffer.add_char s c; *)
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
end
| ' ' | '\n' | '\r' | '\t' ->
begin match st with
| Parse_root sl -> aux(Parse_root sl)
| Parse_content sl -> aux(Parse_content sl)
(* | Parse_word(w, sl) -> aux(Parse_content(Atom(Buffer.contents w)::sl)) *)
| Parse_word(w, sl) -> aux(Parse_content(Atom(w.ToString())::sl))
| Parse_string(_, s, sl) ->
//Buffer.add_char s c;
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
end
| '"' ->
(* '"' *)
begin match st with
| Parse_root _ -> failwith "Parse error: double quote at root level"
| Parse_content sl ->
(* let s = Buffer.create 74 in *)
let s = StringBuilder(74) in
aux(Parse_string(false, s, sl))
| Parse_word(w, sl) ->
(* let s = Buffer.create 74 in *)
let s = StringBuilder(74) in
(* aux(Parse_string(false, s, Atom(Buffer.contents w)::sl)) *)
aux(Parse_string(false, s, Atom(w.ToString())::sl))
| Parse_string(true, s, sl) ->
(* Buffer.add_char s c; *)
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
| Parse_string(false, s, sl) ->
(* aux(Parse_content(Atom(Buffer.contents s)::sl)) *)
aux(Parse_content(Atom(s.ToString())::sl))
end
| '\\' ->
begin match st with
| Parse_string(true, s, sl) ->
(* Buffer.add_char s c; *)
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
| Parse_string(false, s, sl) ->
aux(Parse_string(true, s, sl))
| _ ->
failwith "Parsing error: escape character in wrong place"
end
| _ ->
begin match st with
| Parse_root _ ->
failwith(Printf.sprintf "Parsing error: char '%c' at root level" c)
| Parse_content sl ->
(* let w = Buffer.create 16 in *)
let w = StringBuilder(16) in
(* Buffer.add_char w c; *)
w.Append(c) |> ignore;
aux(Parse_word(w, sl))
| Parse_word(w, sl) ->
(* Buffer.add_char w c; *)
w.Append(c) |> ignore;
aux(Parse_word(w, sl))
| Parse_string(_, s, sl) ->
(* Buffer.add_char s c; *)
s.Append(c) |> ignore;
aux(Parse_string(false, s, sl))
end
in
aux (Parse_root [])
let string_pop_char str =
let len = String.length str in
let i = ref(-1) in
(function () -> incr i; if !i >= len then None else Some(str.[!i]))
let parse_string str =
parse (string_pop_char str)
(*
let ic_pop_char ic =
(function () ->
try Some(input_char ic)
with End_of_file -> (None))
*)
let ic_pop_char (ic:TextReader) =
(function () -> try Some(Convert.ToChar(ic.Read()))
with _End_of_file -> (None)
)
let parse_ic ic =
parse (ic_pop_char ic)
let parse_file filename =
(* let ic = open_in filename in *)
let ic = File.OpenText filename in
let res = parse_ic ic in
(* close_in ic; *)
ic.Close();
(res)
let quote s =
"\"" ^ s ^ "\""
let needs_quote s =
(* List.exists (String.contains s) [' '; '\n'; '\r'; '\t'; '('; ')'] *)
List.exists (fun elem -> (String.exists (fun c -> c = elem) s)) [' '; '\n'; '\r'; '\t'; '('; ')']
let protect s =
(* There is no need to "escape" .Net strings the framework takes care of this *)
(* let s = String.escaped s in *)
if needs_quote s then quote s else s
let string_of_sexpr s =
let rec aux acc = function
| (Atom tag)::tl -> aux ((protect tag)::acc) tl
| (Expr e)::tl ->
let s =
"(" ^
(String.concat " " (aux [] e))
^ ")"
in
aux (s::acc) tl
| [] -> (List.rev acc)
in
String.concat " " (aux [] s)
let print_sexpr s =
(* print_endline (string_of_sexpr s) *)
printfn "%s" (string_of_sexpr s)
let string_of_sexpr_indent s =
let rec aux i acc = function
| (Atom tag)::tl -> aux i ((protect tag)::acc) tl
| (Expr e)::tl ->
let s =
(*
"\n" ^ (String.make i ' ') ^ "(" ^
(String.concat " " (aux (succ i) [] e))
^ ")"
*)
"\n" ^ (String.replicate i " ") ^ "(" ^
(String.concat " " (aux (i + 1) [] e))
^ ")"
in
aux i (s::acc) tl
| [] -> (List.rev acc)
in
String.concat "\n" (aux 0 [] s)
let print_sexpr_indent s =
(* print_endline (string_of_sexpr_indent s) *)
printfn "%s" (string_of_sexpr_indent s)
|
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
|
#OCaml
|
OCaml
|
#load "str.cma"
let langs =
Str.split (Str.regexp " ")
"actionscript ada algol68 amigae applescript autohotkey awk bash basic \
befunge bf c cfm cobol cpp csharp d delphi e eiffel factor false forth \
fortran fsharp haskell haxe j java javascript lisaac lisp logo lua m4 \
mathematica maxscript modula3 moo objc ocaml octave oz pascal perl \
raku php pike pop11 powershell prolog python qbasic r rebol ruby \
scala scheme slate smalltalk tcl ti89b vbnet vedit"
let read_in ic =
let buf = Buffer.create 16384
and tmp = String.create 4096 in
let rec aux() =
let bytes = input ic tmp 0 4096 in
if bytes > 0 then begin
Buffer.add_substring buf tmp 0 bytes;
aux()
end
in
(try aux() with End_of_file -> ());
(Buffer.contents buf)
let repl pat tpl str =
let reg = Str.regexp_string_case_fold pat in
let str = Str.global_replace reg tpl str in
(str)
(* change <%s> to <lang %s> *)
let repl1 lang str =
let pat = "<" ^ lang ^ ">"
and tpl = "<lang " ^ lang ^ ">" in
(repl pat tpl str)
(* change </%s> to </la\ng> *)
let repl2 lang str =
let pat = "</" ^ lang ^ ">"
and tpl = "</lang"^">" in
(repl pat tpl str)
(* change <code %s> to <lang %s> *)
let repl3 lang str =
let pat = "<code " ^ lang ^ ">"
and tpl = "<lang " ^ lang ^ ">" in
(repl pat tpl str)
(* change </code> to </la\ng> *)
let repl4 lang str =
let pat = "</code>"
and tpl = "</lang"^">" in
(repl pat tpl str)
let () =
print_string (
List.fold_left (fun str lang ->
(repl4 lang (repl3 lang (repl2 lang (repl1 lang str))))
) (read_in stdin) langs)
|
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.
|
#Ruby
|
Ruby
|
#!/usr/bin/ruby
require 'openssl' # for mod_exp only
require 'prime'
def rsa_encode blocks, e, n
blocks.map{|b| b.to_bn.mod_exp(e, n).to_i}
end
def rsa_decode ciphers, d, n
rsa_encode ciphers, d, n
end
# all numbers in blocks have to be < modulus, or information is lost
# for secure encryption only use big modulus and blocksizes
def text_to_blocks text, blocksize=64 # 1 hex = 4 bit => default is 256bit
text.each_byte.reduce(""){|acc,b| acc << b.to_s(16).rjust(2, "0")} # convert text to hex (preserving leading 0 chars)
.each_char.each_slice(blocksize).to_a # slice hexnumbers in pieces of blocksize
.map{|a| a.join("").to_i(16)} # convert each slice into internal number
end
def blocks_to_text blocks
blocks.map{|d| d.to_s(16)}.join("") # join all blocks into one hex-string
.each_char.each_slice(2).to_a # group into pairs
.map{|s| s.join("").to_i(16)} # number from 2 hexdigits is byte
.flatten.pack("C*") # pack bytes into ruby-string
.force_encoding(Encoding::default_external) # reset encoding
end
def generate_keys p1, p2
n = p1 * p2
t = (p1 - 1) * (p2 - 1)
e = 2.step.each do |i|
break i if i.gcd(t) == 1
end
d = 1.step.each do |i|
break i if (i * e) % t == 1
end
return e, d, n
end
p1, p2 = Prime.take(100).last(2)
public_key, private_key, modulus =
generate_keys p1, p2
print "Message: "
message = gets
blocks = text_to_blocks message, 4 # very small primes
print "Numbers: "; p blocks
encoded = rsa_encode(blocks, public_key, modulus)
print "Encrypted as: "; p encoded
decoded = rsa_decode(encoded, private_key, modulus)
print "Decrypted to: "; p decoded
final = blocks_to_text(decoded)
print "Decrypted Message: "; puts final
|
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.
|
#Factor
|
Factor
|
USING: combinators.short-circuit dice formatting io kernel math
math.statistics qw sequences ;
IN: rosetta-code.rpg-attributes-generator
CONSTANT: stat-names qw{ Str Dex Con Int Wis Cha }
: attribute ( -- n )
4 [ ROLL: 1d6 ] replicate 3 <iota> kth-largests sum ;
: stats ( -- seq ) 6 [ attribute ] replicate ;
: valid-stats? ( seq -- ? )
{ [ [ 15 >= ] count 2 >= ] [ sum 75 >= ] } 1&& ;
: generate-valid-stats ( -- seq )
stats [ dup valid-stats? ] [ drop stats ] until ;
: stats-info ( seq -- )
[ sum ] [ [ 15 >= ] count ] bi
"Total: %d\n# of attributes >= 15: %d\n" printf ;
: main ( -- )
generate-valid-stats dup stat-names swap
[ "%s: %d\n" printf ] 2each nl stats-info ;
MAIN: main
|
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.
|
#FreeBASIC
|
FreeBASIC
|
#define min(a, b) iif(a < b, a, b)
function d6() as integer
'simulates a marked regular hexahedron coming to rest on a plane
return 1+int(rnd*6)
end function
function roll_stat() as integer
'rolls four dice, returns the sum of the three highest
dim as integer a=d6(), b=d6(), c=d6(), d=d6()
return a + b + c + d - min( min(a, b), min(c, d) )
end function
dim as string*3 statnames(1 to 6) = {"STR", "CON", "DEX", "INT", "WIS", "CHA"}
dim as integer stat(1 to 6), n15, sum
dim as boolean acceptable = false
randomize timer
do
sum = 0
n15 = 0
for i as integer = 1 to 6
stat(i) = roll_stat()
sum = sum + stat(i)
if stat(i)>=15 then n15 += 1
next i
if sum>=75 and n15 >=2 then acceptable = true
loop until acceptable
for i as integer = 1 to 6
print using "&: ##";statnames(i);stat(i)
next i
print "--------"
print using "TOT: ##";sum
|
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
|
#RATFOR
|
RATFOR
|
program prime
#
define(true,1)
define(false,0)
#
integer loop,loop2,limit,k,primes,count
integer isprime(1000)
limit = 1000
count = 0
for (loop=1; loop<=limit; loop=loop+1)
{
isprime(loop) = true
}
isprime(1) = false
for (loop=2; loop<=limit; loop=loop+1)
{
if (isprime(loop) == true)
{
count = count + 1
for (loop2=loop*loop; loop2 <= limit; loop2=loop2+loop)
{
isprime(loop2) = false
}
}
}
write(*,*)
write(*,101) count
101 format('There are ',I12,' primes.')
count = 0
for (loop=1; loop<=limit; loop=loop+1)
if (isprime(loop) == true)
{
Count = count + 1
write(*,'(I6,$)')loop
if (mod(count,10) == 0) write(*,*)
}
write(*,*)
end
|
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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net;
class Task {
private string _task;
private int _examples;
public Task(string task, int examples) {
_task = task;
_examples = examples;
}
public string Name {
get { return _task; }
}
public int Examples {
get { return _examples; }
}
public override string ToString() {
return String.Format("{0}: {1} examples.", this._task, this._examples);
}
}
class Program {
static List<string> GetTitlesFromCategory(string category, WebClient wc) {
string content = wc.DownloadString(
String.Format("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:{0}&cmlimit=500&format=json", category)
);
return new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value.Replace("\\/", "/")).ToList();
}
static string GetSourceCodeFromPage(string page, WebClient wc) {
return wc.DownloadString(
String.Format("http://www.rosettacode.org/w/index.php?title={0}&action=raw", page)
);
}
static void Main(string[] args) {
WebClient wc = new WebClient();
List<Task> tasks = new List<Task>();
List<string> tasknames = GetTitlesFromCategory("Programming_Tasks", wc);
foreach (string task in tasknames) {
string content = GetSourceCodeFromPage(task, wc);
int count = new Regex("=={{header", RegexOptions.IgnoreCase).Matches(content).Count;
Task t = new Task(task, count);
Console.WriteLine(t);
tasks.Add(t);
}
Console.WriteLine("\nTotal: {0} examples.", tasks.Select(x => x.Examples).Sum());
}
}
|
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
|
#Groovy
|
Groovy
|
def haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
def needles = ["Washington","Bush","Wally"]
needles.each { needle ->
def index = haystack.indexOf(needle)
def lastindex = haystack.lastIndexOf(needle)
if (index < 0) {
assert lastindex < 0
println needle + " is not in haystack"
} else {
println "First index: " + index + " " + needle
println "Last index: " + lastindex + " " + needle
}
}
|
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.
|
#Erlang
|
Erlang
|
-module( rank_languages_by_popularity ).
-export( [task/0] ).
-record( print_fold, {place=0, place_step=1, previous_count=0} ).
task() ->
ok = find_unimplemented_tasks:init(),
Category_programming_languages = find_unimplemented_tasks:rosetta_code_list_of( "Programming_Languages" ),
Programming_languages = [X || "Category:" ++ X <- Category_programming_languages],
{ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" ),
Count_categories = lists:sort( [{Y, X} || {X, Y} <- category_counts(Body, []), lists:member(X, Programming_languages)] ),
lists:foldr( fun place_count_category_write/2, #print_fold{}, Count_categories ).
category_counts( "", [[] | Acc] ) -> Acc;
category_counts( String, Acc ) ->
{Begin, End} = category_count_begin_end( String ),
{Category_count, String_continuation} = category_count_extract( String, Begin, End ),
category_counts( String_continuation, [Category_count | Acc] ).
category_count_begin_end( String ) ->
Begin = string:str( String, "/wiki/Category:" ),
End = string:str( string:substr(String, Begin), " member" ),
category_count_begin_end( Begin, End, erlang:length(" member") ).
category_count_begin_end( _Begin, 0, _End_length ) -> {0, 0};
category_count_begin_end( Begin, End, End_length ) ->
{Begin, Begin + End + End_length}.
category_count_extract( _String, 0, _End ) -> {[], ""};
category_count_extract( String, Begin, End ) ->
Category_count = category_count_extract( string:substr(String, Begin, End - Begin) ),
{Category_count, string:substr( String, End + 1 )}.
category_count_extract( "/wiki/Category:" ++ T ) ->
Category_member = string:tokens( T, " " ),
Category = category_count_extract_category( Category_member ),
Member = category_count_extract_count( lists:reverse(Category_member) ),
{Category, Member}.
category_count_extract_category( [Category | _T] ) ->
lists:map( fun category_count_extract_category_map/1, string:strip(Category, right, $") ).
category_count_extract_category_map( $_ ) -> $\s;
category_count_extract_category_map( Character ) -> Character.
category_count_extract_count( ["member" ++ _, "(" ++ N | _T] ) -> erlang:list_to_integer( N );
category_count_extract_count( _T ) -> 0.
place_count_category_write( {Count, Category}, Acc ) ->
Print_fold = place_count_category_write( Count, Acc ),
io:fwrite("~p. ~p - ~p~n", [Print_fold#print_fold.place, Count, Category] ),
Print_fold;
place_count_category_write( Count, #print_fold{place_step=Place_step, previous_count=Count}=Print_fold ) ->
Print_fold#print_fold{place_step=Place_step + 1};
place_count_category_write( Count, #print_fold{place=Place, place_step=Place_step} ) ->
#print_fold{place=Place + Place_step, previous_count=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.
|
#BASIC256
|
BASIC256
|
function FBString(lon, cad$)
# Definimos la función String en BASIC256
cadena$ = ""
for a = 1 to lon
cadena$ += cad$
next a
return cadena$
end function
function RLDecode(i$)
rCount$ = "" : outP$ = ""
for Loop0 = 1 to length(i$)
m$ = mid(i$, Loop0, 1)
begin case
case m$ = "0"
rCount$ += m$
case m$ = "1"
rCount$ += m$
case m$ = "2"
rCount$ += m$
case m$ = "3"
rCount$ += m$
case m$ = "4"
rCount$ += m$
case m$ = "5"
rCount$ += m$
case m$ = "6"
rCount$ += m$
case m$ = "7"
rCount$ += m$
case m$ = "8"
rCount$ += m$
case m$ = "9"
rCount$ += m$
else
if length(rCount$) then
outP$ += FBString(int(rCount$), m$)
rCount$ = ""
else
outP$ += m$
end if
end case
next Loop0
RLDecode = outP$
end function
function RLEncode(i$)
outP$ = ""
tmp1 = mid(i$, 1, 1)
tmp2 = tmp1
rCount = 1
for Loop0 = 2 to length(i$)
tmp1 = mid(i$, Loop0, 1)
if tmp1 <> tmp2 then
outP$ += string(rCount) + tmp2
tmp2 = tmp1
rCount = 1
else
rCount += 1
end if
next Loop0
outP$ += replace(string(rCount)," ", "")
outP$ += tmp2
RLEncode = outP$
end function
input "Type something: ", initial
encoded$ = RLEncode(initial)
decoded$ = RLDecode(encoded$)
print initial
print encoded$
print decoded$
end
|
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.
|
#Arturo
|
Arturo
|
rect: function [r,phi][
to :complex @[ r * cos phi, r * sin phi ]
]
roots: function [n][
map 0..dec n 'k -> rect 1.0 2 * k * pi / n
]
loop 2..10 'nr ->
print [pad to :string nr 3 "=>" join.with:", " to [:string] .format:".3f" roots nr]
|
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.
|
#AutoHotkey
|
AutoHotkey
|
n := 8, a := 8*atan(1)/n
Loop %n%
i := A_Index-1, t .= cos(a*i) ((s:=sin(a*i))<0 ? " - i*" . -s : " + i*" . s) "`n"
Msgbox % t
|
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.
|
#ALGOL_68
|
ALGOL 68
|
quadratic equation:
BEGIN
MODE ROOTS = UNION([]REAL, []COMPL);
MODE QUADRATIC = STRUCT(REAL a,b,c);
PROC solve = (QUADRATIC q)ROOTS:
BEGIN
REAL a = a OF q, b = b OF q, c = c OF q;
REAL sa = b**2 - 4*a*c;
IF sa >=0 THEN # handle the +ve case as REAL #
REAL sqrt sa = ( b<0 | sqrt(sa) | -sqrt(sa));
REAL r1 = (-b + sqrt sa)/(2*a),
r2 = (-b - sqrt sa)/(2*a);
[]REAL((r1,r2))
ELSE # handle the -ve case as COMPL conjugate pairs #
COMPL compl sqrt sa = ( b<0 | complex sqrt(sa) | -complex sqrt(sa));
COMPL r1 = (-b + compl sqrt sa)/(2*a),
r2 = (-b - compl sqrt sa)/(2*a);
[]COMPL (r1, r2)
FI
END # solve #;
PROC real evaluate = (QUADRATIC q, REAL x )REAL: (a OF q*x + b OF q)*x + c OF q;
PROC compl evaluate = (QUADRATIC q, COMPL x)COMPL: (a OF q*x + b OF q)*x + c OF q;
# only a very tiny difference between the 2 examples #
[]QUADRATIC test = ((1, -10e5, 1), (1, 0, 1), (1,-3,2), (1,3,2), (4,0,4), (3,4,5));
FORMAT real fmt = $g(-0,8)$;
FORMAT compl fmt = $f(real fmt)"+"f(real fmt)"i"$;
FORMAT quadratic fmt = $f(real fmt)" x**2 + "f(real fmt)" x + "f(real fmt)" = 0"$;
FOR index TO UPB test DO
QUADRATIC quadratic = test[index];
ROOTS r = solve(quadratic);
# Output the two different scenerios #
printf(($"Quadratic: "$, quadratic fmt, quadratic, $l$));
CASE r IN
([]REAL r):
printf(($"REAL x1 = "$, real fmt, r[1],
$", x2 = "$, real fmt, r[2], $"; "$,
$"REAL y1 = "$, real fmt, real evaluate(quadratic,r[1]),
$", y2 = "$, real fmt, real evaluate(quadratic,r[2]), $";"ll$
)),
([]COMPL c):
printf(($"COMPL x1,x2 = "$, real fmt, re OF c[1], $"+/-"$,
real fmt, ABS im OF c[1], $"; "$,
$"COMPL y1 = "$, compl fmt, compl evaluate(quadratic,c[1]),
$", y2 = "$, compl fmt, compl evaluate(quadratic,c[2]), $";"ll$
))
ESAC
OD
END # quadratic_equation #
|
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
|
#Applesoft_BASIC
|
Applesoft BASIC
|
100HOME:INPUT"ENTER A STRING:";S$:FORL=1TOLEN(S$):I$=MID$(S$,L,1):LC=(ASC(I$)>95)*32:C$=CHR$(ASC(I$)-LC):IFC$>="A"ANDC$<="Z"THENC$=CHR$(ASC(C$)+13):C$=CHR$(ASC(C$)-26*(C$>"Z")):I$=CHR$(ASC(C$)+LC)
110A$=A$+I$:NEXT:PRINTA$
|
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 }
|
#FutureBasic
|
FutureBasic
|
window 1
def fn dydx( x as double, y as double ) as double = x * sqr(y)
def fn exactY( x as long ) as double = ( x ^2 + 4 ) ^2 / 16
long i
double h, k1, k2, k3, k4, x, y, result
h = 0.1
y = 1
for i = 0 to 100
x = i * h
if x == int(x)
result = fn exactY( x )
print "y("; mid$( str$(x), 2, len$(str$(x) )); ") = "; y, "Error = "; result - y
end if
k1 = h * fn dydx( x, y )
k2 = h * fn dydx( x + h / 2, y + k1 / 2 )
k3 = h * fn dydx( x + h / 2, y + k2 / 2 )
k4 = h * fn dydx( x + h, y + k3 )
y = y + 1 / 6 * ( k1 + 2 * k2 + 2 * k3 + k4 )
next
HandleEvents
|
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 }
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
type ypFunc func(t, y float64) float64
type ypStepFunc func(t, y, dt float64) float64
// newRKStep takes a function representing a differential equation
// and returns a function that performs a single step of the forth-order
// Runge-Kutta method.
func newRK4Step(yp ypFunc) ypStepFunc {
return func(t, y, dt float64) float64 {
dy1 := dt * yp(t, y)
dy2 := dt * yp(t+dt/2, y+dy1/2)
dy3 := dt * yp(t+dt/2, y+dy2/2)
dy4 := dt * yp(t+dt, y+dy3)
return y + (dy1+2*(dy2+dy3)+dy4)/6
}
}
// example differential equation
func yprime(t, y float64) float64 {
return t * math.Sqrt(y)
}
// exact solution of example
func actual(t float64) float64 {
t = t*t + 4
return t * t / 16
}
func main() {
t0, tFinal := 0, 10 // task specifies times as integers,
dtPrint := 1 // and to print at whole numbers.
y0 := 1. // initial y.
dtStep := .1 // step value.
t, y := float64(t0), y0
ypStep := newRK4Step(yprime)
for t1 := t0 + dtPrint; t1 <= tFinal; t1 += dtPrint {
printErr(t, y) // print intermediate result
for steps := int(float64(dtPrint)/dtStep + .5); steps > 1; steps-- {
y = ypStep(t, y, dtStep)
t += dtStep
}
y = ypStep(t, y, float64(t1)-t) // adjust step to integer time
t = float64(t1)
}
printErr(t, y) // print final result
}
func printErr(t, y float64) {
fmt.Printf("y(%.1f) = %f Error: %e\n", t, y, math.Abs(actual(t)-y))
}
|
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
|
#Go
|
Go
|
package main
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
)
const language = "Go"
var baseQuery = "http://rosettacode.org/mw/api.php?action=query" +
"&format=xml&list=categorymembers&cmlimit=100"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
fmt.Println(err) // connection or request fail
return ""
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
fmt.Println(err)
return ""
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
func main() {
// get language members, store in a map
langMap := make(map[string]bool)
storeLang := func(cm string) { langMap[cm] = true }
languageQuery := baseQuery + "&cmtitle=Category:" + language
continueAt := req(languageQuery, storeLang)
for continueAt > "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
// a quick check to avoid long output
if len(langMap) == 0 {
fmt.Println("no tasks implemented for", language)
return
}
// get tasks, print as we go along
printUnImp := func(cm string) {
if !langMap[cm] {
fmt.Println(cm)
}
}
taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks"
continueAt = req(taskQuery, printUnImp)
for continueAt > "" {
continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp)
}
}
|
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.
|
#UNIX_Shell
|
UNIX Shell
|
eval_with_x() {
set -- "`x=$2; eval "$1"`" "`x=$3; eval "$1"`"
expr "$2" - "$1"
}
eval_with_x '
# compute 2 ** $x
p=1
while test $x -gt 0; do
p=`expr $p \* 2`
x=`expr $x - 1`
done
echo $p
' 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.
|
#Wren
|
Wren
|
import "meta" for Meta
var x
Meta.eval("x = 2")
System.print("First x = %(x)")
var y = x // save this value
Meta.eval("x = 5")
System.print("Second x = %(x)")
Meta.eval("x = x - y")
System.print("Delta x = %(x)")
|
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.
|
#Factor
|
Factor
|
USING: formatting kernel math.parser multiline peg peg.ebnf
regexp sequences prettyprint words ;
IN: rosetta-code.s-expressions
STRING: input
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
;
EBNF: sexp>seq [=[
ws = [\n\t\r ]* => [[ drop ignore ]]
digits = [0-9]+
number = digits => [[ string>number ]]
float = digits:a "." digits:b => [[ a b "." glue string>number ]]
string = '"'~ [^"]* '"'~ => [[ "" like ]]
symbol = [!#-'*-~]+ => [[ "" like <uninterned-word> ]]
object = ws ( float | number | string | symbol ) ws
sexp = ws "("~ ( object | sexp )* ")"~ ws => [[ { } like ]]
]=]
: seq>sexp ( seq -- str )
unparse R/ {\s+/ "(" R/ \s+}/ ")" [ re-replace ] 2bi@ ;
input [ "Input:\n%s\n\n" printf ] [
sexp>seq dup seq>sexp
"Native:\n%u\n\nRound trip:\n%s\n" printf
] bi
|
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
|
#Perl
|
Perl
|
my @langs = qw(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);
my $text = join "", <STDIN>;
my $slang="/lang";
for (@langs) {
$text =~ s|<$_>|<lang $_>|g;
$text =~ s|</$_>|<$slang>|g;
}
$text =~ s|<code (.+?)>(.*?)</code>|<lang $1>$2<$slang>|sg;
print $text;
|
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
|
#Phix
|
Phix
|
with javascript_semantics
constant ltext = `_div abap actionscript actionscript3 ada apache
applescript apt_sources asm asp autoit avisynth bash basic4gl bf
blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp
cpp-qt csharp css d delphi diff dos dot eiffel email fortran
freebasic genero gettext glsl gml gnuplot groovy haskell hq9plus
html4strict idl ini inno intercal io java java5 javascript kixtart
klonec klonecpp latex lisp lolcode lotusformulas lotusscript
lscript lua m68k make matlab mirc modula3 mpasm mxml mysql nsis
objc ocaml ocaml-brief oobas oracle11 oracle8 pascal per perl php
php-brief pic16 pixelbender plsql povray powershell progress
prolog providex python qbasic r 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`,
langs = split(substitute(ltext,"\n"," "))
function fix_tags(string text)
for i=1 to length(langs) do
string lang = langs[i],
openl = sprintf("<%s>",{lang}),
openc = sprintf("<code %s>",{lang}),
lopen = sprintf("<lang %s>",{lang}),
closl = sprintf("</%s>",{lang}),
closc = sprintf("</%s>",{"code"}),
lclos = sprintf("</%s>",{"lang"})
text = substitute_all(text,{openl,openc,closl,closc},
{lopen,lopen,lclos,lclos})
end for
return text
end function
constant test = """
lorem ipsum <c>some c code</c>dolor sit amet, <csharp>some
csharp code</csharp> consectetur adipisicing elit, <code r>
some r code </code>sed do eiusmod tempor incididunt
"""
puts(1,fix_tags(test))
|
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.
|
#Rust
|
Rust
|
extern crate num;
use num::bigint::BigUint;
use num::integer::Integer;
use num::traits::{One, Zero};
fn mod_exp(b: &BigUint, e: &BigUint, n: &BigUint) -> Result<BigUint, &'static str> {
if n.is_zero() {
return Err("modulus is zero");
}
if b >= n {
// base is too large and should be split into blocks
return Err("base is >= modulus");
}
if b.gcd(n) != BigUint::one() {
return Err("base and modulus are not relatively prime");
}
let mut bb = b.clone();
let mut ee = e.clone();
let mut result = BigUint::one();
while !ee.is_zero() {
if ee.is_odd() {
result = (result * &bb) % n;
}
ee >>= 1;
bb = (&bb * &bb) % n;
}
Ok(result)
}
fn main() {
let msg = "Rosetta Code";
let n = "9516311845790656153499716760847001433441357"
.parse()
.unwrap();
let e = "65537".parse().unwrap();
let d = "5617843187844953170308463622230283376298685"
.parse()
.unwrap();
let msg_int = BigUint::from_bytes_be(msg.as_bytes());
let enc = mod_exp(&msg_int, &e, &n).unwrap();
let dec = mod_exp(&enc, &d, &n).unwrap();
let msg_dec = String::from_utf8(dec.to_bytes_be()).unwrap();
println!("msg as txt: {}", msg);
println!("msg as num: {}", msg_int);
println!("enc as num: {}", enc);
println!("dec as num: {}", dec);
println!("dec as txt: {}", msg_dec);
}
|
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.
|
#Scala
|
Scala
|
object RSA_saket{
val d = BigInt("5617843187844953170308463622230283376298685")
val n = BigInt("9516311845790656153499716760847001433441357")
val e = 65537
val text = "Rosetta Code"
val encode = (msg:BigInt) => pow_mod(msg,e,n)
val decode = (msg:BigInt) => pow_mod(msg,d,n)
val getmsg = (txt:String) => BigInt(txt.map(x => "%03d".format(x.toInt)).reduceLeft(_+_))
def pow_mod(p:BigInt, q:BigInt, n:BigInt):BigInt = {
if(q==0) BigInt(1)
else if(q==1) p
else if(q%2 == 1) pow_mod(p,q-1,n)*p % n
else pow_mod(p*p % n,q/2,n)
}
def gettxt(num:String) = {
if(num.size%3==2)
("0" + num).grouped(3).toList.foldLeft("")(_ + _.toInt.toChar)
else
num.grouped(3).toList.foldLeft("")(_ + _.toInt.toChar)
}
def main(args: Array[String]): Unit = {
println(f"Original String \t: "+text)
val msg = getmsg(text)
println(f"Converted Signal \t: "+msg)
val enc_sig = encode(msg)
println("Encoded Signal \t\t: "+ enc_sig)
val dec_sig = decode(enc_sig)
println("Decoded String \t\t: "+ dec_sig)
val rec_msg = gettxt(dec_sig.toString)
println("Retrieved Signal \t: "+rec_msg)
}
}
|
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.
|
#FOCAL
|
FOCAL
|
01.10 S T=0
01.20 F X=1,6;D 4;S AT(X)=S3;S T=T+S3
01.30 I (T-75)1.1
01.40 S K=0;F X=1,6;D 2
01.50 I (K-2)1.1
01.55 T "STR DEX CON INT WIS CHA TOTAL",!
01.60 F X=1,6;T %2,AT(X)," "
01.70 T T,!
01.80 Q
02.10 I (AT(X)-15)2.3,2.2,2.2
02.20 S K=K+1
02.30 R
04.01 C--ROLL 4 D6ES AND GIVE SUM OF LARGEST 3
04.10 S XS=7;S S3=0;S XN=4
04.20 D 6;S S3=S3+A;I (XS-A)4.4,4.4,4.3
04.30 S XS=A
04.40 S XN=XN-1;I (XN),4.5,4.2
04.50 S S3=S3-XS
06.01 C--ROLL A D6
06.10 S A=FRAN()*10;S A=A-FITR(A)
06.20 S A=1+FITR(A*6)
|
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.
|
#Forth
|
Forth
|
require random.fs
: d6 ( -- roll ) 6 random 1 + ;
variable smallest
: genstat ( -- stat )
d6 dup smallest !
3 0 do
d6 dup smallest @ < if dup smallest ! then +
loop
smallest @ -
;
variable strong
variable total
: genstats ( -- cha wis int con dex str )
0 strong !
0 total !
6 0 do
genstat
dup 15 >= if strong @ 1 + strong ! then
dup total @ + total !
loop
total @ 75 < strong @ 2 < or if
drop drop drop drop drop drop
recurse
then
;
: roll ( -- )
genstats
." str:" . ." dex:" . ." con:" .
." int:" . ." wis:" . ." cha:" .
." (total:" total @ . 8 emit ." )"
;
utime drop seed !
|
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
|
#Red
|
Red
|
primes: function [n [integer!]][
poke prim: make bitset! n 1 true
r: 2 while [r * r <= n][
repeat q n / r - 1 [poke prim q + 1 * r true]
until [not pick prim r: r + 1]
]
collect [repeat i n [if not prim/:i [keep i]]]
]
primes 100
== [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]
|
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
|
#Clojure
|
Clojure
|
(ns count-examples
(:import [java.net URLEncoder])
(:use [clojure.contrib.http.agent :only (http-agent string)]
[clojure.contrib.json :only (read-json)]
[clojure.contrib.string :only (join)]))
(defn url-encode [v] (URLEncoder/encode (str v) "utf-8"))
(defn rosettacode-get [path params]
(let [param-string (join "&" (for [[n v] params] (str (name n) "=" (url-encode v))))]
(string (http-agent (format "http://www.rosettacode.org/w/%s?%s" path param-string)))))
(defn rosettacode-query [params]
(read-json (rosettacode-get "api.php" (merge {:action "query" :format "json"} params))))
(defn list-cm
([params] (list-cm params nil))
([params continue]
(let [cm-params (merge {:list "categorymembers"} params (or continue {}))
result (rosettacode-query cm-params)]
(concat (-> result (:query) (:categorymembers))
(if-let [cmcontinue (-> result (:query-continue) (:categorymembers))]
(list-cm params cmcontinue))))))
(defn programming-tasks []
(let [result (list-cm {:cmtitle "Category:Programming_Tasks" :cmlimit 50})]
(map #(:title %) result)))
(defn task-count [task]
[task (count
(re-seq #"==\{\{header"
(rosettacode-get "index.php" {:action "raw" :title task})))])
(defn print-result []
(let [task-counts (map task-count (programming-tasks))]
(doseq [[task count] task-counts]
(println (str task ":") count)
(flush))
(println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts))))
|
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
|
#Haskell
|
Haskell
|
import Data.List
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
needles = ["Washington","Bush"]
|
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.
|
#F.23
|
F#
|
open System
open System.Text.RegularExpressions
[<EntryPoint>]
let main argv =
let rosettacodeSpecialCategoriesAddress =
"http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let rosettacodeProgrammingLaguagesAddress =
"http://rosettacode.org/wiki/Category:Programming_Languages"
let getWebContent (url :string) =
using (new System.Net.WebClient()) (fun x -> x.DownloadString url)
let regexForTitleCategoryFollowedOptionallyByMembercount =
new Regex("""
title="Category: (?<Name> [^"]* ) "> # capture the name of the category
( # group begin for optional part
[^(]* # ignore up to next open paren (on this line)
\( # verbatim open paren
(?<Number>
\d+ # a number (= some digits)
)
\s+ # whitespace
member(s?) # verbatim text members (maybe singular)
\) # verbatim closing paren
)? # end of optional part
""", // " <- Make syntax highlighting happy
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.ExplicitCapture)
let matchesForTitleCategoryFollowedOptionallyByMembercount str =
regexForTitleCategoryFollowedOptionallyByMembercount.Matches(str)
let languages =
matchesForTitleCategoryFollowedOptionallyByMembercount
(getWebContent rosettacodeProgrammingLaguagesAddress)
|> Seq.cast
|> Seq.map (fun (m: Match) -> (m.Groups.Item("Name").Value, true))
|> Map.ofSeq
let entriesWithCount =
let parse str = match Int32.TryParse(str) with | (true, n) -> n | (false, _) -> -1
matchesForTitleCategoryFollowedOptionallyByMembercount
(getWebContent rosettacodeSpecialCategoriesAddress)
|> Seq.cast
|> Seq.map (fun (m: Match) ->
(m.Groups.Item("Name").Value, parse (m.Groups.Item("Number").Value)))
|> Seq.filter (fun p -> (snd p) > 0 && Map.containsKey (fst p) languages)
|> Seq.sortBy (fun x -> -(snd x))
Seq.iter2 (fun i x -> printfn "%4d. %s" i x)
(seq { 1 .. 20 })
(entriesWithCount |> Seq.map (fun x -> sprintf "%3d - %s" (snd x) (fst x)))
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.
|
#BBC_BASIC
|
BBC BASIC
|
input$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
PRINT "Input: " input$
rle$ = FNencodeRLE(input$)
output$ = FNdecodeRLE(rle$)
PRINT "Output: " output$
END
DEF FNencodeRLE(text$)
LOCAL n%, r%, c$, o$
n% = 1
WHILE n% <= LEN(text$)
c$ = MID$(text$, n%, 1)
n% += 1
r% = 1
WHILE c$ = MID$(text$, n%, 1) AND r% < 127
r% += 1
n% += 1
ENDWHILE
IF r% < 3 o$ += STRING$(r%, c$) ELSE o$ += CHR$(128+r%) + c$
ENDWHILE
= o$
DEF FNdecodeRLE(rle$)
LOCAL n%, c$, o$
n% = 1
WHILE n% <= LEN(rle$)
c$ = MID$(rle$, n%, 1)
n% += 1
IF ASC(c$) > 128 THEN
o$ += STRING$(ASC(c$)-128, MID$(rle$, n%, 1))
n% += 1
ELSE
o$ += c$
ENDIF
ENDWHILE
= o$
|
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.
|
#AWK
|
AWK
|
# syntax: GAWK -f ROOTS_OF_UNITY.AWK
BEGIN {
pi = 3.1415926
for (n=2; n<=5; n++) {
printf("%d: ",n)
for (root=0; root<=n-1; root++) {
real = cos(2 * pi * root / n)
imag = sin(2 * pi * root / n)
printf("%8.5f %8.5fi",real,imag)
if (root != n-1) { printf(", ") }
}
printf("\n")
}
exit(0)
}
|
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.
|
#BASIC
|
BASIC
|
CLS
PI = 3.1415926#
n = 5 'this can be changed for any desired n
angle = 0 'start at angle 0
DO
real = COS(angle) 'real axis is the x axis
IF (ABS(real) < 10 ^ -5) THEN real = 0 'get rid of annoying sci notation
imag = SIN(angle) 'imaginary axis is the y axis
IF (ABS(imag) < 10 ^ -5) THEN imag = 0 'get rid of annoying sci notation
PRINT real; "+"; imag; "i" 'answer on every line
angle = angle + (2 * PI) / n
'all the way around the circle at even intervals
LOOP WHILE angle < 2 * PI
|
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.
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % quadratic(u,v, 1,-3,2) ", " u ", " v
MsgBox % quadratic(u,v, 1,3,2) ", " u ", " v
MsgBox % quadratic(u,v, -2,4,-2) ", " u ", " v
MsgBox % quadratic(u,v, 1,0,1) ", " u ", " v
SetFormat FloatFast, 0.15e
MsgBox % quadratic(u,v, 1,-1.0e8,1) ", " u ", " v
quadratic(ByRef x1, ByRef x2, a,b,c) { ; -> #real roots {x1,x2} of ax²+bx+c
If (a = 0)
Return -1 ; ERROR: not quadratic
d := b*b - 4*a*c
If (d < 0) {
x1 := x2 := ""
Return 0
}
If (d = 0) {
x1 := x2 := -b/2/a
Return 1
}
x1 := (-b - (b<0 ? -sqrt(d) : sqrt(d)))/2/a
x2 := c/a/x1
Return 2
}
|
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
|
#Arturo
|
Arturo
|
rot13: function [c][
case [in? lower c]
when? -> `a`..`m` -> return to :char (to :integer c) + 13
when? -> `n`..`z` -> return to :char (to :integer c) - 13
else -> return c
]
loop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 'ch
-> prints rot13 ch
print ""
|
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 }
|
#Groovy
|
Groovy
|
class Runge_Kutta{
static void main(String[] args){
def y=1.0,t=0.0,counter=0;
def dy1,dy2,dy3,dy4;
def real;
while(t<=10)
{if(counter%10==0)
{real=(t*t+4)*(t*t+4)/16;
println("y("+t+")="+ y+ " Error:"+ (real-y));
}
dy1=dy(dery(y,t));
dy2=dy(dery(y+dy1/2,t+0.05));
dy3=dy(dery(y+dy2/2,t+0.05));
dy4=dy(dery(y+dy3,t+0.1));
y=y+(dy1+2*dy2+2*dy3+dy4)/6;
t=t+0.1;
counter++;
}
}
static def dery(def y,def t){return t*(Math.sqrt(y));}
static def dy(def x){return x*0.1;}
}
|
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
|
#Haskell
|
Haskell
|
import Network.Browser
import Network.HTTP
import Network.URI
import Data.List
import Data.Maybe
import Text.XML.Light
import Control.Arrow
import Data.Char
getRespons url = do
rsp <- Network.Browser.browse $ do
setAllowRedirects True
setOutHandler $ const (return ()) -- quiet
request $ getRequest url
return $ rspBody $ snd rsp
replaceWithSpace c = (\x -> if c==x then ' ' else x)
encl = chr 34
unimpTasks lang = do
allTasks <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
impl <- getRespons ( "http://rosettacode.org/json/isb/" ++ lang ++ ".json")
let langxx = map (map(replaceWithSpace '_')) $ filter (/=",") $ words $ map (replaceWithSpace encl ) $ init $ drop 1 impl
xml = onlyElems $ parseXML allTasks
allxx = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xml
mapM_ putStrLn $ sort $ allxx \\ langxx
|
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.
|
#zkl
|
zkl
|
fcn evalWithX(text,x) {
f:=Compiler.Compiler.compileText(text);
f.x = x; // set free var in compiled blob
f.__constructor(); // run blob
vm.regX // compiler sets the VMs X register for cases like this
}
const TEXT="var x; x*2"; // variables need to be declared
evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4
|
http://rosettacode.org/wiki/S-expressions
|
S-expressions
|
S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
Newlines and other whitespace may be ignored unless contained within a quoted string.
“()” inside quoted strings are not interpreted, but treated as part of the string.
Handling escaped quotes inside a string is optional; thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error.
For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.
Languages that support it may treat unquoted strings as symbols.
Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.
The reader should be able to read the following input
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.)
The writer should be able to take the produced list and turn it into a new S-Expression.
Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted.
Extra Credit
Let the writer produce pretty printed output with indenting and line-breaks.
|
#Go
|
Go
|
package main
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"unicode"
)
var input = `((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))`
func main() {
fmt.Println("input:")
fmt.Println(input)
s, err := parseSexp(input)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("\nparsed:")
fmt.Println(s)
fmt.Println("\nrepresentation:")
s.dump(0)
}
// dynamic types for i are string, qString, int, float64, list, and error.
type sexp struct {
i interface{}
}
type qString string
type list []sexp
func (s sexp) String() string {
return fmt.Sprintf("%v", s.i)
}
func (q qString) String() string {
return strconv.Quote(string(q))
}
func (l list) String() string {
if len(l) == 0 {
return "()"
}
b := fmt.Sprintf("(%v", l[0])
for _, s := range l[1:] {
b = fmt.Sprintf("%s %v", b, s)
}
return b + ")"
}
// parseSexp parses a string into a Go representation of an s-expression.
//
// Quoted strings go from one " to the next. There is no escape character,
// all characters except " are valid.
//
// Otherwise atoms are any string of characters between any of '(', ')',
// '"', or white space characters. If the atom parses as a Go int type
// using strconv.Atoi, it is taken as int; if it parses as a Go float64
// type using strconv.ParseFloat, it is taken as float64; otherwise it is
// taken as an unquoted string.
//
// Unmatched (, ), or " are errors.
// An empty or all whitespace input string is an error.
// Left over text after the sexp is an error.
//
// An empty list is a valid sexp, but there is no nil, no cons, no dot.
func parseSexp(s string) (sexp, error) {
s1, rem := ps2(s, -1)
if err, isErr := s1.i.(error); isErr {
return sexp{}, err
}
if rem > "" {
return s1, errors.New("Left over text: " + rem)
}
return s1, nil
}
// recursive. n = -1 means not parsing a list. n >= 0 means the number
// of list elements parsed so far. string result is unparsed remainder
// of the input string s0.
func ps2(s0 string, n int) (x sexp, rem string) {
tok, s1 := gettok(s0)
switch t := tok.(type) {
case error:
return sexp{tok}, s1
case nil: // this is also an error
if n < 0 {
return sexp{errors.New("blank input string")}, s0
} else {
return sexp{errors.New("unmatched (")}, ""
}
case byte:
switch {
case t == '(':
x, s1 = ps2(s1, 0) // x is a list
if _, isErr := x.i.(error); isErr {
return x, s0
}
case n < 0:
return sexp{errors.New("unmatched )")}, ""
default:
// found end of list. allocate space for it.
return sexp{make(list, n)}, s1
}
default:
x = sexp{tok} // x is an atom
}
if n < 0 {
// not in a list, just return the s-expression x
return x, s1
}
// in a list. hold on to x while we parse the rest of the list.
l, s1 := ps2(s1, n+1)
// result l is either an error or the allocated list, not completely
// filled in yet.
if _, isErr := l.i.(error); !isErr {
// as long as no errors, drop x into its place in the list
l.i.(list)[n] = x
}
return l, s1
}
// gettok gets one token from string s.
// return values are the token and the remainder of the string.
// dynamic type of tok indicates result:
// nil: no token. string was empty or all white space.
// byte: one of '(' or ')'
// otherwise string, qString, int, float64, or error.
func gettok(s string) (tok interface{}, rem string) {
s = strings.TrimSpace(s)
if s == "" {
return nil, ""
}
switch s[0] {
case '(', ')':
return s[0], s[1:]
case '"':
if i := strings.Index(s[1:], `"`); i >= 0 {
return qString(s[1 : i+1]), s[i+2:]
}
return errors.New(`unmatched "`), s
}
i := 1
for i < len(s) && s[i] != '(' && s[i] != ')' && s[i] != '"' &&
!unicode.IsSpace(rune(s[i])) {
i++
}
if j, err := strconv.Atoi(s[:i]); err == nil {
return j, s[i:]
}
if f, err := strconv.ParseFloat(s[:i], 64); err == nil {
return f, s[i:]
}
return s[:i], s[i:]
}
func (s sexp) dump(i int) {
fmt.Printf("%*s%v: ", i*3, "", reflect.TypeOf(s.i))
if l, isList := s.i.(list); isList {
fmt.Println(len(l), "elements")
for _, e := range l {
e.dump(i + 1)
}
} else {
fmt.Println(s.i)
}
}
|
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
|
#PicoLisp
|
PicoLisp
|
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(let Lang '("ada" "awk" "c" "forth" "prolog" "python" "z80")
(in NIL
(while (echo "<")
(let S (till ">" T)
(cond
((pre? "code " S) (prin "<lang" (cddddr (chop S))))
((member S Lang) (prin "<lang " S))
((= S "/code") (prin "</lang"))
((and (pre? "/" S) (member (pack (cdr (chop S))) Lang))
(prin "</lang") )
(T (prin "<" S)) ) ) ) ) )
(bye)
|
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
|
#PureBasic
|
PureBasic
|
If Not OpenConsole()
End
ElseIf CountProgramParameters() <> 2
PrintN("Usage: "+GetFilePart(ProgramFilename())+" InFile OutFile")
End
EndIf
Define Infile$ =ProgramParameter(), Outfile$=ProgramParameter()
If ReadFile(0,Infile$)
NewList Out$()
Define line$, part$, new$, pos1, pos2
While Not Eof(0)
line$=ReadString(0): pos2=0
Repeat
pos1=FindString(line$,"<",pos2)
pos2=FindString(line$,">",pos1)
If pos1 And pos2
part$=Mid(line$,pos1+1,pos2-pos1-1)
If Mid(part$,1,1)="/"
new$="<"+"/lang>" ; Line split to avoid problem forum coding
ElseIf Mid(part$,1,5)="code "
new$="<lang "+Mid(part$,6)+">"
Else
new$="<lang "+part$+">"
EndIf
line$=ReplaceString(line$,"<"+part$+">",new$)
Else
Break
EndIf
ForEver
AddElement(Out$()): Out$()=line$
Wend
CloseFile(0)
If CreateFile(1, Outfile$)
ForEach Out$()
WriteStringN(1,Out$())
Next
CloseFile(1)
EndIf
EndIf
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "bigint.s7i";
include "bytedata.s7i";
const proc: main is func
local
const string: plainText is "Rosetta Code";
# Use a key big enough to hold 16 bytes of plain text in a single block.
const bigInteger: modulus is 9516311845790656153499716760847001433441357_;
const bigInteger: encode is 65537_;
const bigInteger: decode is 5617843187844953170308463622230283376298685_;
var bigInteger: plainTextNumber is 0_;
var bigInteger: encodedNumber is 0_;
var bigInteger: decodedNumber is 0_;
var string: decodedText is "";
begin
writeln("Plain text: " <& plainText);
plainTextNumber := bytes2BigInt(plainText, UNSIGNED, BE);
if plainTextNumber >= modulus then
writeln("Plain text message too long");
else
writeln("Plain text as a number: " <& plainTextNumber);
encodedNumber := modPow(plainTextNumber, encode, modulus);
writeln("Encoded: " <& encodedNumber);
decodedNumber := modPow(encodedNumber, decode, modulus);
writeln("Decoded: " <& decodedNumber);
decodedText := bytes(decodedNumber, UNSIGNED, BE);
writeln("Decoded number as text: " <& decodedText);
end if;
end func;
|
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.
|
#Sidef
|
Sidef
|
const n = 9516311845790656153499716760847001433441357
const e = 65537
const d = 5617843187844953170308463622230283376298685
module Message {
var alphabet = [('A' .. 'Z')..., ' ']
var rad = alphabet.len
var code = Hash(^rad -> map {|i| (alphabet[i], i) }...)
func encode(String t) {
[code{t.reverse.chars...}] ~Z* t.len.range.map { |i| rad**i } -> sum(0)
}
func decode(Number n) {
''.join(alphabet[
gather {
loop {
var (d, m) = n.divmod(rad)
take(m)
break if (n < rad)
n = d
}
}...]
).reverse
}
}
var secret_message = "ROSETTA CODE"
say "Secret message is #{secret_message}"
var numeric_message = Message::encode(secret_message)
say "Secret message in integer form is #{numeric_message}"
var numeric_cipher = expmod(numeric_message, e, n)
say "After exponentiation with public exponent we get: #{numeric_cipher}"
var text_cipher = Message::decode(numeric_cipher)
say "This turns into the string #{text_cipher}"
var numeric_cipher2 = Message::encode(text_cipher)
say "If we re-encode it in integer form we get #{numeric_cipher2}"
var numeric_message2 = expmod(numeric_cipher2, d, n)
say "After exponentiation with SECRET exponent we get: #{numeric_message2}"
var secret_message2 = Message::decode(numeric_message2)
say "This turns into the string #{secret_message2}"
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
for {
var values [6]int
vsum := 0
for i := range values {
var numbers [4]int
for j := range numbers {
numbers[j] = 1 + r.Intn(6)
}
sort.Ints(numbers[:])
nsum := 0
for _, n := range numbers[1:] {
nsum += n
}
values[i] = nsum
vsum += values[i]
}
if vsum < 75 {
continue
}
vcount := 0
for _, v := range values {
if v >= 15 {
vcount++
}
}
if vcount < 2 {
continue
}
fmt.Println("The 6 random numbers generated are:")
fmt.Println(values)
fmt.Println("\nTheir sum is", vsum, "and", vcount, "of them are >= 15")
break
}
}
|
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
|
#REXX
|
REXX
|
/*REXX program generates and displays primes via the sieve of Eratosthenes algorithm.*/
parse arg H .; if H=='' | H=="," then H= 200 /*optain optional argument from the CL.*/
w= length(H); @prime= right('prime', 20) /*W: is used for aligning the output.*/
@.=. /*assume all the numbers are prime. */
#= 0 /*number of primes found (so far). */
do j=2 for H-1; if @.j=='' then iterate /*all prime integers up to H inclusive.*/
#= # + 1 /*bump the prime number counter. */
say @prime right(#,w) " ───► " right(j,w) /*display the prime to the terminal. */
do m=j*j to H by j; @.m=; end /*strike all multiples as being ¬ prime*/
end /*j*/ /* ─── */
say /*stick a fork in it, we're all done. */
say right(#, 1+w+length(@prime) ) 'primes found up to and including ' H
|
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
|
#D
|
D
|
import tango.io.Stdout;
import tango.net.http.HttpClient;
import tango.net.http.HttpHeaders;
import tango.text.xml.Document;
import tango.text.Util;
alias HttpHeader.ContentLength CL;
auto url = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";
void main()
{
auto client = new HttpClient (HttpClient.Get, url);
client.open();
char[] mainData, tmp;
int total, i;
void cat(void[] content) { tmp ~= cast(char[]) content; }
if (client.isResponseOK) {
client.read(&cat, client.getResponseHeaders.getInt(CL));
mainData = tmp;
tmp = null;
auto doc = new Document!(char);
doc.parse(mainData);
foreach (n; doc.query.descendant("cm").attribute("title")) {
auto subClient = new HttpClient(HttpClient.Get,
"http://www.rosettacode.org/w/index.php?title=" ~
replace(n.value.dup, ' ', '_') ~ "&action=raw");
subClient.open();
if (! subClient.isResponseOK) {
Stderr (client.getResponse);
break;
}
subClient.read(&cat, subClient.getResponseHeaders.getInt(CL));
foreach (segment; patterns(cast(char[])tmp, "=={{header|")) i++;
--i;
if (i) --i;
Stdout.formatln ("{0,-40} - {}", n.value, i);
total += i;
tmp = null;
i = 0;
}
Stdout("total examples: ", total).newline;
} else {
Stderr (client.getResponse);
}
}
|
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
|
#HicEst
|
HicEst
|
CHARACTER haystack='Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo.'
CHARACTER needle*10
DLG(TItle="Enter search string", Edit=needle)
n = EDIT(Text=haystack, Option=2, End, Count=needle) ! Option = word
IF( n == 0 ) THEN
WRITE(Messagebox="!") needle, "not found" ! bus not found
ELSE
first = EDIT(Text=needle, LeXicon=haystack)
WRITE(ClipBoard) "First ", needle, "found in position ", first
! First bush found in position 5
last = EDIT(Text=haystack, End, Left=needle, Count=" ") + 1
WRITE(ClipBoard) "Last ", needle, "found in position ", last
! Last bush found in position 8
ENDIF
|
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.
|
#Go
|
Go
|
package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http://rosettacode.org/mw/api.php?action=query" +
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err) // connection or request fail
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
// satisfy sort interface (reverse sorting)
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
// get languages, store in a map
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
// allocate slice for sorting
s := make(popList, 0, len(langMap))
// get big list of categories
resp, err := http.Get("http://rosettacode.org/mw/index.php" +
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
// split out fields of interest and populate sortable slice
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
// output
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
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.
|
#Befunge
|
Befunge
|
~"y"- ~$ v
<temp var for when char changes
format:
first,'n' and a newline. :
a char then a v _"n",v
number then a space continuously 9
example: 1
n > v ,+<
a5 b2
decoded:aaaaabb
the program is ended using decoder
Ctrl-C on linux,or alt-f4
on windows.copy the output >\v encoder
of the program somewhere ^_ $ v
to encode press y : > $11g:, v
to decode pipe file in >1-^ ~ v +1\<
the output of the encoder \ v< $ ^ .\_^
starts with n,this is so ^,:<\&~< _~:,>1>\:v>^
you can pipe it straight in ^ <
~
the spaces seem to be a annoying thing :
thanks to CCBI...if a interpreter dosen't 1
create them it's non-conforming and thus 1
the validity of this program is NOT affected p-
>^
--written by Gamemanj,for Rosettacode
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
@% = &20408
FOR n% = 2 TO 5
PRINT STR$(n%) ": " ;
FOR root% = 0 TO n%-1
real = COS(2*PI * root% / n%)
imag = SIN(2*PI * root% / n%)
PRINT real imag "i" ;
IF root% <> n%-1 PRINT "," ;
NEXT
PRINT
NEXT n%
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
double a, c, s, PI2 = atan2(1, 1) * 8;
int n, i;
for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
c = s = 0;
if (!i ) c = 1;
else if(n == 4 * i) s = 1;
else if(n == 2 * i) c = -1;
else if(3 * n == 4 * i) s = -1;
else
a = i * PI2 / n, c = cos(a), s = sin(a);
if (c) printf("%.2g", c);
printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s);
printf(i == n - 1 ?"\n":", ");
}
return 0;
}
|
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
|
Rosetta Code/Find bare lang tags
|
Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare language tags.
1 in perl
1 in no language
Extra credit
Allow multiple files to be read. Summarize all results by language:
5 bare language tags.
2 in c ([[Foo]], [[Bar]])
1 in perl ([[Foo]])
2 in no language ([[Baz]])
Extra extra credit
Use the Media Wiki API to test actual RC tasks.
|
#AutoHotkey
|
AutoHotkey
|
task =
(
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
)
lang := "no language", out := Object(lang, 0), total := 0
Loop Parse, task, `r`n
If RegExMatch(A_LoopField, "==\s*{{\s*header\s*\|\s*([^\s\}]+)\s*}}\s*==", $)
lang := $1, out[lang] := 0
else if InStr(A_LoopField, "<lang>")
out[lang]++
For lang, num in Out
If num
total++, str .= "`n" num " in " lang
MsgBox % clipboard := total " bare lang tags.`n" . str
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
FOR test% = 1 TO 7
READ a$, b$, c$
PRINT "For a = " ; a$ ", b = " ; b$ ", c = " ; c$ TAB(32) ;
PROCsolvequadratic(EVAL(a$), EVAL(b$), EVAL(c$))
NEXT
END
DATA 1, -1E9, 1
DATA 1, 0, 1
DATA 2, -1, -6
DATA 1, 2, -2
DATA 0.5, SQR(2), 1
DATA 1, 3, 2
DATA 3, 4, 5
DEF PROCsolvequadratic(a, b, c)
LOCAL d, f
d = b^2 - 4*a*c
CASE SGN(d) OF
WHEN 0:
PRINT "the single root is " ; -b/2/a
WHEN +1:
f = (1 + SQR(1-4*a*c/b^2))/2
PRINT "the real roots are " ; -f*b/a " and " ; -c/b/f
WHEN -1:
PRINT "the complex roots are " ; -b/2/a " +/- " ; SQR(-d)/2/a "*i"
ENDCASE
ENDPROC
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <math.h>
typedef double complex cplx;
void quad_root
(double a, double b, double c, cplx * ra, cplx *rb)
{
double d, e;
if (!a) {
*ra = b ? -c / b : 0;
*rb = 0;
return;
}
if (!c) {
*ra = 0;
*rb = -b / a;
return;
}
b /= 2;
if (fabs(b) > fabs(c)) {
e = 1 - (a / b) * (c / b);
d = sqrt(fabs(e)) * fabs(b);
} else {
e = (c > 0) ? a : -a;
e = b * (b / fabs(c)) - e;
d = sqrt(fabs(e)) * sqrt(fabs(c));
}
if (e < 0) {
e = fabs(d / a);
d = -b / a;
*ra = d + I * e;
*rb = d - I * e;
return;
}
d = (b >= 0) ? d : -d;
e = (d - b) / a;
d = e ? (c / e) / a : 0;
*ra = d;
*rb = e;
return;
}
int main()
{
cplx ra, rb;
quad_root(1, 1e12 + 1, 1e12, &ra, &rb);
printf("(%g + %g i), (%g + %g i)\n",
creal(ra), cimag(ra), creal(rb), cimag(rb));
quad_root(1e300, -1e307 + 1, 1e300, &ra, &rb);
printf("(%g + %g i), (%g + %g i)\n",
creal(ra), cimag(ra), creal(rb), cimag(rb));
return 0;
}
|
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
|
#AutoHotkey
|
AutoHotkey
|
ROT13(string) ; by Raccoon July-2009
{
Static a := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
Static b := "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM "
s=
Loop, Parse, string
{
c := substr(b,instr(a,A_LoopField,True),1)
if (c != " ")
s .= c
else
s .= A_LoopField
}
Return s
}
|
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 }
|
#Hare
|
Hare
|
use fmt;
use math;
export fn main() void = {
rk4_driver(&f, 0.0, 10.0, 1.0, 0.1);
};
fn rk4_driver(func: *fn(_: f64, _: f64) f64, t_init: f64, t_final: f64, y_init: f64, h: f64) void = {
let n = ((t_final - t_init) / h): int;
let tn: f64 = t_init;
let yn: f64 = y_init;
let i: int = 1;
fmt::printfln("{: 2} {: 18} {: 21}", "t", "y(t)", "absolute error")!;
fmt::printfln("{: 2} {: 18} {: 21}", tn, yn, math::absf64(exact(tn) - yn))!;
for (i <= n; i += 1) {
yn = rk4(func, tn, yn, h);
tn = t_init + (i: f64)*h;
if (i % 10 == 0) {
fmt::printfln("{: 2} {: 18} {: 21}\t", tn, yn, math::absf64(exact(tn) - yn))!;
};
};
};
fn rk4(func: *fn(_: f64, _: f64) f64, t: f64, y: f64, h: f64) f64 = {
const k1 = func(t, y);
const k2 = func(t + 0.5*h, y + 0.5*h*k1);
const k3 = func(t + 0.5*h, y + 0.5*h*k2);
const k4 = func(t + h, y + h*k3);
return y + h/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4);
};
fn f(t: f64, y: f64) f64 = {
return t * math::sqrtf64(y);
};
fn exact(t: f64) f64 = {
return 1.0/16.0 * math::powf64(t*t + 4.0, 2.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
|
#Icon_and_Unicon
|
Icon and Unicon
|
$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500"
$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCUA "User-Agent: Unicon Rosetta 0.1"
$define RCXUA "X-Unicon: http://unicon.org/"
$define TASKTOT "* Total Tasks *"
$define TOTTOT "* Total Headers*"
link strings
link hexcvt
procedure main(A) # simple single threaded read all at once implementation
lang := \A[1] | "Unicon"
write("Unimplemented tasks for ",lang," as of ",&date)
every task := taskNames() do {
if lang == languages(task) then next
write(task)
}
end
# Generate task names
procedure taskNames()
continue := ""
while \(txt := ReadURL(RCINDEX||continue)) do {
txt ? {
while tab(find("<cm ") & find(s :="title=\"")+*s) do
suspend tab(find("\""))\1
if tab(find("cmcontinue=")) then {
continue := "&"||tab(upto(' \t'))
}
else break
}
}
end
# Generate language headers in a task
procedure languages(task)
static WS
initial WS := ' \t'
page := ReadURL(RCTASK||CleanURI(task))
page ? while (tab(find("\n==")),tab(many(WS))|"",tab(find("{{"))) do {
header := tab(find("=="))
header ? {
while tab(find("{{header|")) do {
suspend 2(="{{header|",tab(find("}}")))\1
}
}
}
end
procedure CleanURI(u) #: clean up a URI
static tr,dxml # xml & http translation
initial {
tr := table()
every c := !string(~(&digits++&letters++'-_.!~*()/\'`')) do
tr[c] := "%"||hexstring(ord(c),2)
every /tr[c := !string(&cset)] := c
tr[" "] := "_" # wiki convention
every push(dxml := [],"&#"||right(ord(c := !"&<>'\""),3,"0")||";",c)
}
dxml[1] := u # insert URI as 1st arg
u := replacem!dxml # de-xml it
every (c := "") ||:= tr[!u] # reencode everything
c := replace(c,"%3E","'") # Hack to put single quotes back in
c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in
return c
end
procedure ReadURL(url) #: read URL into string
page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url)
text := ""
if page["Status-Code"] < 300 then while text ||:= reads(page,-1)
else write(&errout,image(url),": ",
page["Status-Code"]," ",page["Reason-Phrase"])
close(page)
return text
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.
|
#Haskell
|
Haskell
|
import qualified Data.Functor.Identity as F
import qualified Text.Parsec.Prim as Prim
import Text.Parsec
((<|>), (<?>), many, many1, char, try, parse, sepBy, choice,
between)
import Text.Parsec.Token
(integer, float, whiteSpace, stringLiteral, makeTokenParser)
import Text.Parsec.Char (noneOf)
import Text.Parsec.Language (haskell)
data Val
= Int Integer
| Float Double
| String String
| Symbol String
| List [Val]
deriving (Eq, Show)
tProg :: Prim.ParsecT String a F.Identity [Val]
tProg = many tExpr <?> "program"
where
tExpr = between ws ws (tList <|> tAtom) <?> "expression"
ws = whiteSpace haskell
tAtom =
(try (Float <$> float haskell) <?> "floating point number") <|>
(try (Int <$> integer haskell) <?> "integer") <|>
(String <$> stringLiteral haskell <?> "string") <|>
(Symbol <$> many1 (noneOf "()\"\t\n\r ") <?> "symbol") <?>
"atomic expression"
tList = List <$> between (char '(') (char ')') (many tExpr) <?> "list"
p :: String -> IO ()
p = either print (putStrLn . unwords . map show) . parse tProg ""
main :: IO ()
main = do
let expr =
"((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))"
putStrLn ("The input:\n" ++ expr ++ "\n\nParsed as:")
p expr
|
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
|
#Python
|
Python
|
# coding: utf-8
import sys
import re
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'
text = sys.stdin.read()
for i in langs:
text = text.replace("<%s>" % i,"<lang %s>" % i)
text = text.replace("</%s>" % i, "<%s>" % slang)
text = re.sub("(?s)<%s (.+?)>(.*?)</%s>"%(code,code), r"<lang \1>\2<%s>" % slang, text)
sys.stdout.write(text)
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “
n
{\displaystyle n}
” and “
e
{\displaystyle e}
” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “
d
{\displaystyle d}
” is kept secret, so that only the recipient can read the encrypted plaintext.
The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters
a
=
01
,
b
=
02
,
.
.
.
,
z
=
26
{\displaystyle a=01,b=02,...,z=26}
). This yields a string of numbers, generally referred to as "numerical plaintext", “
P
{\displaystyle P}
”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield
08051212152315181204
{\displaystyle 08051212152315181204}
.
The plaintext must also be split into blocks so that the numerical plaintext is smaller than
n
{\displaystyle n}
otherwise the decryption will fail.
The ciphertext,
C
{\displaystyle C}
, is then computed by taking each block of
P
{\displaystyle P}
, and computing
C
≡
P
e
mod
n
{\displaystyle C\equiv P^{e}\mod n}
Similarly, to decode, one computes
P
≡
C
d
mod
n
{\displaystyle P\equiv C^{d}\mod n}
To generate a key, one finds 2 (ideally large) primes
p
{\displaystyle p}
and
q
{\displaystyle q}
. the value “
n
{\displaystyle n}
” is simply:
n
=
p
×
q
{\displaystyle n=p\times q}
.
One must then choose an “
e
{\displaystyle e}
” such that
gcd
(
e
,
(
p
−
1
)
×
(
q
−
1
)
)
=
1
{\displaystyle \gcd(e,(p-1)\times (q-1))=1}
. That is to say,
e
{\displaystyle e}
and
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle (p-1)\times (q-1)}
are relatively prime to each other.
The decryption value
d
{\displaystyle d}
is then found by solving
d
×
e
≡
1
mod
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)}
The security of the code is based on the secrecy of the Private Key (decryption exponent) “
d
{\displaystyle d}
” and the difficulty in factoring “
n
{\displaystyle n}
”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes).
Summary of the task requirements:
Encrypt and Decrypt a short message or two using RSA with a demonstration key.
Implement RSA do not call a library.
Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine).
Either support blocking or give an error if the message would require blocking)
Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure:
n = 9516311845790656153499716760847001433441357
e = 65537
d = 5617843187844953170308463622230283376298685
Messages can be hard-coded into the program, there is no need for elaborate input coding.
Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
# This is a straight-forward square-and-multiply implementation that relies on
# Tcl 8.5's bignum support (based on LibTomMath) for speed.
proc modexp {b expAndMod} {
lassign $expAndMod -> e n
if {$b >= $n} {puts stderr "WARNING: modulus too small"}
for {set r 1} {$e != 0} {set e [expr {$e >> 1}]} {
if {$e & 1} {
set r [expr {($r * $b) % $n}]
}
set b [expr {($b ** 2) % $n}]
}
return $r
}
# Assumes that messages are shorter than the modulus
proc rsa_encrypt {message publicKey} {
if {[lindex $publicKey 0] ne "publicKey"} {error "key handling"}
set toEnc 0
foreach char [split [encoding convertto utf-8 $message] ""] {
set toEnc [expr {$toEnc * 256 + [scan $char "%c"]}]
}
return [modexp $toEnc $publicKey]
}
proc rsa_decrypt {encrypted privateKey} {
if {[lindex $privateKey 0] ne "privateKey"} {error "key handling"}
set toDec [modexp $encrypted $privateKey]
for {set message ""} {$toDec > 0} {set toDec [expr {$toDec >> 8}]} {
append message [format "%c" [expr {$toDec & 255}]]
}
return [encoding convertfrom utf-8 [string reverse $message]]
}
# Assemble packaged public and private keys
set e 65537
set n 9516311845790656153499716760847001433441357
set d 5617843187844953170308463622230283376298685
set publicKey [list "publicKey" $e $n]
set privateKey [list "privateKey" $d $n]
# Test on some input strings
foreach input {"Rosetta Code" "UTF-8 \u263a test"} {
set enc [rsa_encrypt $input $publicKey]
set dec [rsa_decrypt $enc $privateKey]
puts "$input -> $enc -> $dec"
}
|
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.
|
#Haskell
|
Haskell
|
import Control.Monad (replicateM)
import System.Random (randomRIO)
import Data.Bool (bool)
import Data.List (sort)
character :: IO [Int]
character =
discardUntil
(((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=)))
(replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int)))
discardUntil :: ([Int] -> Bool) -> IO [Int] -> IO [Int]
discardUntil p throw = go
where
go = throw >>= (<*>) (bool go . return) p
-------------------------- TEST ---------------------------
main :: IO ()
main = replicateM 10 character >>= mapM_ (print . (sum >>= (,)))
|
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
|
#Ring
|
Ring
|
limit = 100
sieve = list(limit)
for i = 2 to limit
for k = i*i to limit step i
sieve[k] = 1
next
if sieve[i] = 0 see "" + i + " " ok
next
|
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
|
#EGL
|
EGL
|
package com.eglexamples.client;
import org.eclipse.edt.rui.widgets.*;
handler RosettaCodeHandler type RUIhandler{initialUI =[ui], title = "Rosetta Code Tasks and Counts"}
ui GridLayout{columns = 3, rows = 4, cellPadding = 4, children = [ b1, dg1, l1, l2, l3, l4 ]};
b1 Button{ layoutData = new GridLayoutData{ row = 1, column = 1 }, text = "Go!", onClick ::= b1_onClick };
l1 TextLabel{ layoutData = new GridLayoutData{ row = 1, column = 2 }, text = "Total Tasks:" };
l2 TextLabel{ layoutData = new GridLayoutData{ row = 1, column = 3 }, text = "0" };
l3 TextLabel{ layoutData = new GridLayoutData{ row = 2, column = 2 }, text = "Total Implementations:" };
l4 TextLabel{ layoutData = new GridLayoutData{ row = 2, column = 3 }, text = "0" };
dg1 DataGrid{ layoutData = new GridLayoutData{ row = 3, column = 1, horizontalSpan = 3 },
pageSize = 10, showScrollbar = true,
columns = [ new DataGridColumn{name = "title", displayName = "Task", width=220},
new DataGridColumn{name = "count", displayName = "Count", width=100} ] };
cmcontinue string?;
title string?;
allTasks Task[];
restBindingTasks IHttp? = new HttpRest{
restType = eglx.rest.ServiceType.TrueRest,
request.uri = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=1&format=json"};
restBindingPageDetail IHttp? = new HttpRest{
restType = eglx.rest.ServiceType.TrueRest,
request.uri = "http://rosettacode.org/mw/index.php"};
function b1_onClick(event Event in)
call ProxyFunctions.listTasks("") using restBindingTasks
returning to listTasksCallBack onException exceptionHandler;
end
function listTasksCallBack(retResult RosettaCodeJSON in)
title = retResult.query.categorymembers[1].title;
cmcontinue = retResult.queryContinue.categorymembers.cmcontinue;
call ProxyFunctions.fetchPageDetail(title) using restBindingPageDetail
returning to pageDetailCallBack onException exceptionHandler;
end
function pageDetailCallBack(pageResults string in)
count int = countSubstring("=={{header", pageResults);
allTasks.appendElement(new Task { title = title, count = count });
l2.text = l2.text as int + 1;
l4.text = l4.text as int + count;
if(cmcontinue != null)
call ProxyFunctions.listTasks(cmcontinue) using restBindingTasks
returning to listTasksCallBack onException exceptionHandler;
else
dg1.data = allTasks as any[];
end
end
function countSubstring(substr string in, str string in) returns(int)
if(str.length() > 0 and substr.length() > 0)
return (str.length() - str.replaceStr(subStr, "").length()) / subStr.length();
else
return 0;
end
end
function exceptionHandler(exp AnyException in)
end
end
record Task
title string;
count int;
end
|
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
|
#Erlang
|
Erlang
|
-module(rosseta_examples).
-include_lib("xmerl/include/xmerl.hrl").
-export([main/0]).
main() ->
application:start(inets),
Titles = read_titles(empty),
Result = lists:foldl(fun(Title,Acc) -> Acc + calculate_one(Title) end, 0, Titles),
io:format("Total: ~p examples.\n",[Result]),
application:stop(inets).
read_titles(CurrentContinue) ->
URL0 = "http://rosettacode.org/mw/api.php?" ++
"action=query&list=categorymembers&cmtitle=Category:Programming_Tasks" ++
"&cmlimit=500&format=xml",
URL =
case CurrentContinue of
empty -> URL0;
_ -> URL0 ++ "&cmcontinue=" ++ CurrentContinue
end,
{ok,Answer} = httpc:request(URL),
{Document,_} = xmerl_scan:string(lists:last(tuple_to_list(Answer))),
Continue =
[Value || #xmlAttribute{value = Value} <- xmerl_xpath:string("//@cmcontinue", Document)],
Titles =
[Value || #xmlAttribute{value = Value} <- xmerl_xpath:string("//@title", Document)],
case Continue of
[]->
Titles;
[ContValue | _] ->
Titles ++ read_titles(ContValue)
end.
calculate_one(Title0) ->
Title = replace_chars(Title0),
URL = "http://www.rosettacode.org/w/index.php?title=" ++
Title ++ "&action=raw",
case httpc:request(URL) of
{ok,Result} ->
{match,Found} =
re:run(lists:last(tuple_to_list(Result)), "\n=={{header(|)", [global]),
io:format("~ts: ~p examples.\n",[Title0,length(Found)]),
length(Found);
{error,socket_closed_remotely} ->
io:format("Socket closed remotely. Retry.\n"),
calculate_one(Title0)
end.
replace_chars(String) ->
replace_chars(String,[]).
replace_chars([$ | T],Acc) ->
replace_chars(T, [$_| Acc]);
replace_chars([$+| T],Acc) ->
replace_chars(T, lists:reverse("%2B") ++ Acc);
replace_chars([8211| T],Acc) ->
replace_chars(T, lists:reverse("%E2%80%93") ++ Acc);
replace_chars([Other| T],Acc) ->
replace_chars(T, [Other| Acc]);
replace_chars([],Acc) ->
lists:reverse(Acc).
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
link lists
procedure main()
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] # the haystack
every needle := !["Bush","Washington"] do { # the needles
if i := lindex(haystack,needle) then { # first occurrence
write("needle=",needle, " is at position ",i," in haystack.")
if i <:= last(lindex,[haystack,needle]) then # last occurrence
write("needle=",needle, " is at last position ",i," in haystack.")
}
else {
write("needle=",needle, " is not in haystack.")
runerr(500,needle) # throw an error
}
}
end
procedure last(p,arglist) #: return the last generation of p(arglist) or fail
local i
every i := p!arglist
return \i
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.
|
#Groovy
|
Groovy
|
def html = new URL('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000').getText([
connectTimeout:500,
readTimeout:15000,
requestProperties: [ 'User-Agent': 'Firefox/2.0.0.4']])
def count = [:]
(html =~ '<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>').each { match, language, members ->
count[language] = (members as int)
}
count.sort { v1, v2 -> v2.value <=> v1.value }.eachWithIndex { value, index -> println "${index + 1} $value" }
|
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.
|
#Bracmat
|
Bracmat
|
( run-length
= character otherCharacter acc begin end
. :?acc
& 0:?begin
& @( !arg
: ?
[!begin
%@?character
?
[?end
( (%@:~!character:?otherCharacter) ?
& !acc !end+-1*!begin !character:?acc
& !otherCharacter:?character
& !end:?begin
& ~`
| &!acc !end+-1*!begin !character:?acc
)
)
& str$!acc
)
& run-length$WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
|
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.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
class Program
{
static IEnumerable<Complex> RootsOfUnity(int degree)
{
return Enumerable
.Range(0, degree)
.Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
}
static void Main()
{
var degree = 3;
foreach (var root in RootsOfUnity(degree))
{
Console.WriteLine(root);
}
}
}
|
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.
|
#C.2B.2B
|
C++
|
#include <complex>
#include <cmath>
#include <iostream>
double const pi = 4 * std::atan(1);
int main()
{
for (int n = 2; n <= 10; ++n)
{
std::cout << n << ": ";
for (int k = 0; k < n; ++k)
std::cout << std::polar(1, 2*pi*k/n) << " ";
std::cout << std::endl;
}
}
|
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
|
Rosetta Code/Find bare lang tags
|
Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare language tags.
1 in perl
1 in no language
Extra credit
Allow multiple files to be read. Summarize all results by language:
5 bare language tags.
2 in c ([[Foo]], [[Bar]])
1 in perl ([[Foo]])
2 in no language ([[Baz]])
Extra extra credit
Use the Media Wiki API to test actual RC tasks.
|
#Erlang
|
Erlang
|
-module( find_bare_lang_tags ).
-export( [task/0] ).
task() ->
{ok, Binary} = file:read_file( "priv/find_bare_lang_tags_1" ),
Lines = string:tokens( erlang:binary_to_list(Binary), "\n" ),
{_Lang, Dict} = lists:foldl( fun count_empty_lang/2, {"no language", dict:new()}, Lines ),
Count_langs = [{dict:fetch(X, Dict), X} || X <- dict:fetch_keys(Dict)],
io:fwrite( "~p bare language tags.~n", [lists:sum([X || {X, _Y} <- Count_langs])] ),
[io:fwrite( "~p in ~p~n", [X, Y] ) || {X, Y} <- Count_langs].
count_empty_lang( Line, {Lang, Dict} ) ->
Empty_lang = string:str( Line, "<lang>" ),
New_dict = dict_update_counter( Empty_lang, Lang, Dict ),
New_lang = new_lang( string:str( Line,"=={{header|" ), Line, Lang ),
{New_lang, New_dict}.
dict_update_counter( 0, _Lang, Dict ) -> Dict;
dict_update_counter( _Start, Lang, Dict ) -> dict:update_counter( Lang, 1, Dict ).
new_lang( 0, _Line, Lang ) -> Lang;
new_lang( _Start, Line, _Lang ) ->
Start = string:str( Line, "|" ),
Stop = string:rstr( Line, "}}==" ),
string:sub_string( Line, Start+1, Stop-1 ).
|
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.
|
#C.23
|
C#
|
using System;
using System.Numerics;
class QuadraticRoots
{
static Tuple<Complex, Complex> Solve(double a, double b, double c)
{
var q = -(b + Math.Sign(b) * Complex.Sqrt(b * b - 4 * a * c)) / 2;
return Tuple.Create(q / a, c / q);
}
static void Main()
{
Console.WriteLine(Solve(1, -1E20, 1));
}
}
|
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
|
#AWK
|
AWK
|
# usage: awk -f rot13.awk
BEGIN {
for(i=0; i < 256; i++) {
amap[sprintf("%c", i)] = i
}
for(l=amap["a"]; l <= amap["z"]; l++) {
rot13[l] = sprintf("%c", (((l-amap["a"])+13) % 26 ) + amap["a"])
}
FS = ""
}
{
o = ""
for(i=1; i <= NF; i++) {
if ( amap[tolower($i)] in rot13 ) {
c = rot13[amap[tolower($i)]]
if ( tolower($i) != $i ) c = toupper(c)
o = o c
} else {
o = o $i
}
}
print o
}
|
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 }
|
#Haskell
|
Haskell
|
dv
:: Floating a
=> a -> a -> a
dv = (. sqrt) . (*)
fy t = 1 / 16 * (4 + t ^ 2) ^ 2
rk4
:: (Enum a, Fractional a)
=> (a -> a -> a) -> a -> a -> a -> [(a, a)]
rk4 fd y0 a h = zip ts $ scanl (flip fc) y0 ts
where
ts = [a,h ..]
fc t y =
sum . (y :) . zipWith (*) [1 / 6, 1 / 3, 1 / 3, 1 / 6] $
scanl
(\k f -> h * fd (t + f * h) (y + f * k))
(h * fd t y)
[1 / 2, 1 / 2, 1]
task =
mapM_
(print . (\(x, y) -> (truncate x, y, fy x - y)))
(filter (\(x, _) -> 0 == mod (truncate $ 10 * x) 10) $
take 101 $ rk4 dv 1.0 0 0.1)
|
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
|
#J
|
J
|
require 'strings web/gethttp'
findUnimpTasks=: ('Programming_Tasks' -.&getCategoryMembers ,&'/Omit') ([ #~ -.@e.) getCategoryMembers
getTagContents=: dyad define
'starttag endtag'=. x
('\' -.~ endtag&taketo)&.>@(starttag&E. <@((#starttag)&}.);.1 ]) y
)
NB. RosettaCode Utilities
parseTitles=: ('"title":"';'"')&getTagContents
parseCMcontinue=:('"cmcontinue":"';'"')&getTagContents
getCMcontquery=: ('&cmcontinue=' , urlencode)^:(0 < #)@>@parseCMcontinue
getCategoryMembers=: monad define
buildqry=. 'action=query&list=categorymembers&cmtitle=Category:' , ,&'&cmlimit=500&format=json'
url=.'http://www.rosettacode.org/w/api.php'
uri=. url ,'?', buildqry urlencode y
catmbrs=. qrycont=. ''
whilst. #qrycont=. getCMcontquery jsondat do.
jsondat=. gethttp uri , qrycont
catmbrs=. catmbrs, parseTitles jsondat
end.
catmbrs
)
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link ximage
procedure main()
in := "((data 'quoted data' 123 4.5) (data (!@# (4.5) '(more' 'data)')))"
# in := map(in,"'","\"") # uncomment to put back double quotes if desired
write("Input: ",image(in))
write("Structure: \n",ximage(S := string2sexp(in)))
write("Output: ",image(sexp2string(S)))
end
procedure sexp2string(S) #: return a string representing the s-expr
s := ""
every t := !S do {
if type(t) == "list" then
s ||:= "(" || trim(sexp2string(t)) || ")"
else
if upto('() \t\r\n',t) then
s ||:= "'" || t || "'"
else
s ||:= t
s ||:= " "
}
return trim(s)
end
procedure string2sexp(s) #: return a s-expression nested list
if s ? ( sexptokenize(T := []), pos(0) ) then
return sexpnest(T)
else
write("Malformed: ",s)
end
procedure sexpnest(T,L) #: transform s-expr token list to nested list
/L := []
while t := get(T) do
case t of {
"(" : {
put(L,[])
sexpnest(T,L[*L])
}
")" : return L
default : put(L, numeric(t) | t)
}
return L
end
procedure sexptokenize(T) #: return list of tokens parsed from an s-expr string
static sym
initial sym := &letters++&digits++'~`!@#$%^&*_-+|;:.,<>[]{}'
until pos(0) do
case &subject[&pos] of {
" " : tab(many(' \t\r\n')) # consume whitespace
"'"|"\"" :
(q := move(1)) & put(T,tab(find(q))) & move(1) # quotes
"(" : put(T,move(1)) & sexptokenize(T) # open
")" : put(T,move(1)) &return T # close
default : put(T, tab(many(sym))) # other symbols
}
return T
end
|
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
|
#R
|
R
|
fixtags <- function(page)
{
langs <- c("c", "c-sharp", "r") # a complete list is required, obviously
langs <- paste(langs, collapse="|")
page <- gsub(paste("<(", langs, ")>", sep=""), "<lang \\1>", page)
page <- gsub(paste("</(", langs, ")>", sep=""), "</#####lang>", page)
page <- gsub(paste("<code(", langs, ")>", sep=""), "<lang \\1>", page)
page <- gsub(paste("</code>", sep=""), "</#####lang>", page)
page
}
page <- "lorem ipsum <c>some c code</c>dolor sit amet,<c-sharp>some c-sharp code</c-sharp>
consectetur adipisicing elit,<code r>some r code</code>sed do eiusmod tempor incididunt"
fixtags(page)
|
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
|
#Racket
|
Racket
|
#lang racket
(define lang-names '("X" "Y" "Z"))
(define rx
(regexp (string-join lang-names "|"
#:before-first "<((/?(?:code)?)(?:( )?("
#:after-last "))?)>")))
(let loop () ; does all in a single scan
(define m (regexp-match rx (current-input-port) 0 #f (current-output-port)))
(when m
(define-values [all pfx space lang] (apply values (cdr m)))
(printf "<~a>"
(cond [(not lang) (if (equal? pfx #"/code") #"/lang" all)]
[space (if (equal? pfx #"code") (bytes-append #"lang " lang) all)]
[(equal? pfx #"") (bytes-append #"lang " lang)]
[(equal? pfx #"/") #"/lang"]
[else all]))
(loop)))
|
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
|
#Raku
|
Raku
|
my @langs = <
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 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
>;
$_ = slurp;
for @langs -> $l {
s:g:i [ '<' 'lang '? $l '>' ] = "<lang $l>";
s:g [ '</' $l '>' ] = '</' ~ 'lang>';
}
s:g [ '<code '(.+?) '>' (.*?) '</code>' ] = "<lang $0>{$1}</"~"lang>";
.say;
|
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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System
Imports System.Numerics
Imports System.Text
Module Module1
Sub Main()
Dim n As BigInteger = BigInteger.Parse("9516311845790656153499716760847001433441357")
Dim e As BigInteger = 65537
Dim d As BigInteger = BigInteger.Parse("5617843187844953170308463622230283376298685")
Dim plainTextStr As String = "Hello, Rosetta!"
Dim plainTextBA As Byte() = ASCIIEncoding.ASCII.GetBytes(plainTextStr)
Dim pt As BigInteger = New BigInteger(plainTextBA)
If pt > n Then Throw New Exception() ' Blocking not implemented
Dim ct As BigInteger = BigInteger.ModPow(pt, e, n)
Console.WriteLine(" Encoded: " & ct.ToString("X"))
Dim dc As BigInteger = BigInteger.ModPow(ct, d, n)
Console.WriteLine(" Decoded: " & dc.ToString("X"))
Dim decoded As String = ASCIIEncoding.ASCII.GetString(dc.ToByteArray())
Console.WriteLine("As ASCII: " & decoded)
End Sub
End Module
|
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.
|
#J
|
J
|
roll=: [: >: 4 6 ?@:$ 6:
massage=: +/ - <./
generate_attributes=: massage@:roll
accept=: (75 <: +/) *. (2 <: [: +/ 15&<:)
Until=: conjunction def 'u^:(0-:v)^:_'
NB. show displays discarded attribute sets
NB. and since roll ignores arguments, echo would suffice in place of show
show=: [ echo
NB. use: generate_character 'name'
generate_character=: (; (+/ ; ])@:([: generate_attributes@:show Until accept 0:))&>@:boxopen
|
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
|
#Ruby
|
Ruby
|
def eratosthenes(n)
nums = [nil, nil, *2..n]
(2..Math.sqrt(n)).each do |i|
(i**2..n).step(i){|m| nums[m] = nil} if nums[i]
end
nums.compact
end
p eratosthenes(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
|
#F.23
|
F#
|
#r "System.Xml.Linq.dll"
let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
let uri2 task = sprintf "http://www.rosettacode.org/w/index.php?title=%s&action=raw" task
[|for xml in (System.Xml.Linq.XDocument.Load uri1).Root.Descendants() do
for attrib in xml.Attributes() do
if attrib.Name.LocalName = "title" then
yield async {
let uri = uri2 (attrib.Value.Replace(" ", "_") |> System.Web.HttpUtility.UrlEncode)
use client = new System.Net.WebClient()
let! html = client.AsyncDownloadString(System.Uri uri)
let sols' = html.Split([|"{{header|"|], System.StringSplitOptions.None).Length - 1
lock stdout (fun () -> printfn "%s: %d examples" attrib.Value sols')
return sols' }|]
|> Async.Parallel
|> Async.RunSynchronously
|> fun xs -> printfn "Total: %d examples" (Seq.sum xs)
|
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
|
#Factor
|
Factor
|
USING: arrays assocs concurrency.combinators
concurrency.semaphores formatting hashtables http.client io
json.reader kernel math math.parser sequences splitting
urls.encoding ;
IN: rosetta-code.count-examples
CONSTANT: list-url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&cmprop=title&format=json"
: titles ( query -- titles )
"query" of "categorymembers" of [ "title" of ] map ;
: continued-url ( query -- url/f )
"query-continue" of "categorymembers" of
[ assoc>query list-url swap "&" glue ] [ f ] if* ;
: (all-programming-titles) ( titles url -- titles' url' )
http-get nip json> [ titles append ] [ continued-url ] bi
[ (all-programming-titles) ] [ f ] if* ;
: all-programming-titles ( -- titles ) { } list-url (all-programming-titles) drop ;
CONSTANT: content-base-url "http://rosettacode.org/mw/index.php?title=&action=raw"
: content-url ( title -- url )
" " "_" replace
"title" associate assoc>query
content-base-url swap "&" glue ;
: occurences ( seq subseq -- n ) split-subseq length 1 - ;
: count-examples ( title -- n )
content-url http-get nip "=={{header|" occurences ;
: print-task ( title n -- ) "%s: %d examples.\n" printf ;
: print-total ( assoc -- ) values sum "Total: %d examples.\n" printf ;
: fetch-counts ( titles -- assoc )
10 <semaphore> [
[ dup count-examples 2array ] with-semaphore
] curry parallel-map ;
: print-counts ( titles -- )
[ [ print-task ] assoc-each nl ] [ print-total ] bi ;
: rosetta-examples ( -- )
all-programming-titles fetch-counts print-counts ;
MAIN: rosetta-examples
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.