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/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Ada
|
Ada
|
with Ada.Text_IO; with Ada.Numerics.Float_Random;
procedure Rock_Paper_Scissors is
package Rand renames Ada.Numerics.Float_Random;
Gen: Rand.Generator;
type Choice is (Rock, Paper, Scissors);
Cnt: array (Choice) of Natural := (1, 1, 1);
-- for the initialization: pretend that each of Rock, Paper,
-- and Scissors, has been played once by the human
-- else the first computer choice would be deterministic
function Computer_Choice return Choice is
Random_Number: Natural :=
Integer(Rand.Random(Gen)
* (Float(Cnt(Rock)) + Float(Cnt(Paper)) + Float(Cnt(Scissors))));
begin
if Random_Number < Cnt(Rock) then
-- guess the human will choose Rock
return Paper;
elsif Random_Number - Cnt(Rock) < Cnt(Paper) then
-- guess the human will choose Paper
return Scissors;
else -- guess the human will choose Scissors
return Rock;
end if;
end Computer_Choice;
Finish_The_Game: exception;
function Human_Choice return Choice is
Done: Boolean := False;
T: constant String
:= "enter ""r"" for Rock, ""p"" for Paper, or ""s"" for Scissors""!";
U: constant String
:= "or enter ""q"" to Quit the game";
Result: Choice;
begin
Ada.Text_IO.Put_Line(T);
Ada.Text_IO.Put_Line(U);
while not Done loop
Done := True;
declare
S: String := Ada.Text_IO.Get_Line;
begin
if S="r" or S="R" then
Result := Rock;
elsif S="p" or S = "P" then
Result := Paper;
elsif S="s" or S="S" then
Result := Scissors;
elsif S="q" or S="Q" then
raise Finish_The_Game;
else
Done := False;
end if;
end;
end loop;
return Result;
end Human_Choice;
type Result is (Human_Wins, Draw, Computer_Wins);
function "<" (X, Y: Choice) return Boolean is
-- X < Y if X looses against Y
begin
case X is
when Rock => return (Y = Paper);
when Paper => return (Y = Scissors);
when Scissors => return (Y = Rock);
end case;
end "<";
Score: array(Result) of Natural := (0, 0, 0);
C,H: Choice;
Res: Result;
begin
-- play the game
loop
C := Computer_Choice; -- the computer makes its choice first
H := Human_Choice; -- now ask the player for his/her choice
Cnt(H) := Cnt(H) + 1; -- update the counts for the AI
if C < H then
Res := Human_Wins;
elsif H < C then
Res := Computer_Wins;
else
Res := Draw;
end if;
Ada.Text_IO.Put_Line("COMPUTER'S CHOICE: " & Choice'Image(C)
& " RESULT: " & Result'Image(Res));
Ada.Text_IO.New_Line;
Score(Res) := Score(Res) + 1;
end loop;
exception
when Finish_The_Game =>
Ada.Text_IO.New_Line;
for R in Score'Range loop
Ada.Text_IO.Put_Line(Result'Image(R) & Natural'Image(Score(R)));
end loop;
end Rock_Paper_Scissors;
|
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.
|
#Clojure
|
Clojure
|
(defn compress [s]
(->> (partition-by identity s) (mapcat (juxt count first)) (apply str)))
(defn extract [s]
(->> (re-seq #"(\d+)([A-Z])" s)
(mapcat (fn [[_ n ch]] (repeat (Integer/parseInt n) ch)))
(apply str)))
|
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.
|
#Fortran
|
Fortran
|
PROGRAM Roots
COMPLEX :: root
INTEGER :: i, n
REAL :: angle, pi
pi = 4.0 * ATAN(1.0)
DO n = 2, 7
angle = 0.0
WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
DO i = 1, n
root = CMPLX(COS(angle), SIN(angle))
WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j "
angle = angle + (2.0*pi / REAL(n))
END DO
WRITE(*,*)
END DO
END PROGRAM Roots
|
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.
|
#FreeBASIC
|
FreeBASIC
|
#define twopi 6.2831853071795864769252867665590057684
dim as uinteger m, n
dim as double real, imag, theta
input "n? ", n
for m = 0 to n-1
theta = m*twopi/n
real = cos(theta)
imag = sin(theta)
if imag >= 0 then
print using "#.##### + #.##### i"; real; imag
else
print using "#.##### - #.##### i"; real; -imag
end if
next m
|
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.
|
#Julia
|
Julia
|
using Gumbo, AbstractTrees, HTTP, JSON, Dates
rosorg = "http://rosettacode.org"
qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json"
sqURI = "http://www.rosettacode.org/mw/index.php?title="
function topages(js, v)
for d in js["query"]["categorymembers"]
push!(v, sqURI * HTTP.Strings.escapehtml(replace(d["title"], " " => "_")) * "&action=raw")
end
end
function getpages(uri)
wikipages = Vector{String}()
response = HTTP.request("GET", rosorg * uri)
if response.status == 200
fromjson = JSON.parse(String(response.body))
topages(fromjson, wikipages)
while haskey(fromjson, "continue")
cmcont, cont = fromjson["continue"]["cmcontinue"], fromjson["continue"]["continue"]
response = HTTP.request("GET", rosorg * uri * "&cmcontinue=$cmcont&continue=$cont")
fromjson = JSON.parse(String(response.body))
topages(fromjson, wikipages)
end
end
wikipages
end
function processtaskpages(wpages, verbose=false)
totalcount = 0
langcount = Dict{String, Int}()
for pag in wpages
count = 0
checked = 0
try
response = HTTP.request("GET", pag)
if response.status == 200
doc = parsehtml(String(response.body))
lasttext = ""
for elem in StatelessBFS(doc.root)
if typeof(elem) != HTMLText
if tag(elem) == :lang
if isempty(attrs(elem))
count += 1
if lasttext != ""
if verbose
println("Missing lang attibute for lang $lasttext")
end
if !haskey(langcount, lasttext)
langcount[lasttext] = 1
else
langcount[lasttext] += 1
end
end
else
checked += 1
end
end
else
m = match(r"header\|(.+)}}==", text(elem))
lasttext = (m == nothing) ? "" : m.captures[1]
end
end
end
catch y
if verbose
println("Page $pag is not loaded or found: $y.")
end
continue
end
if count > 0 && verbose
println("Page $pag had $count bare lang tags.")
end
totalcount += count
end
println("Total bare tags: $totalcount.")
for k in sort(collect(keys(langcount)))
println("Total bare <lang> for language $k: $(langcount[k])")
end
end
println("Programming examples at $(DateTime(now())):")
qURI |> getpages |> processtaskpages
println("\nDraft programming tasks:")
qdURI |> getpages |> processtaskpages
|
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.
|
#Kotlin
|
Kotlin
|
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.regex.Pattern
import java.util.stream.Collectors
const val BASE = "http://rosettacode.org"
fun main() {
val client = HttpClient.newBuilder().build()
val titleUri = URI.create("$BASE/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks")
val titleRequest = HttpRequest.newBuilder(titleUri).GET().build()
val titleResponse = client.send(titleRequest, HttpResponse.BodyHandlers.ofString())
if (titleResponse.statusCode() == 200) {
val titleBody = titleResponse.body()
val titlePattern = Pattern.compile("\"title\": \"([^\"]+)\"")
val titleMatcher = titlePattern.matcher(titleBody)
val titleList = titleMatcher.results().map { it.group(1) }.collect(Collectors.toList())
val headerPattern = Pattern.compile("==\\{\\{header\\|([^}]+)}}==")
val barePredicate = Pattern.compile("<lang>").asPredicate()
val countMap = mutableMapOf<String, Int>()
for (title in titleList) {
val pageUri = URI("http", null, "//rosettacode.org/wiki", "action=raw&title=$title", null)
val pageRequest = HttpRequest.newBuilder(pageUri).GET().build()
val pageResponse = client.send(pageRequest, HttpResponse.BodyHandlers.ofString())
if (pageResponse.statusCode() == 200) {
val pageBody = pageResponse.body()
//println("Title is $title")
var language = "no language"
for (line in pageBody.lineSequence()) {
val headerMatcher = headerPattern.matcher(line)
if (headerMatcher.matches()) {
language = headerMatcher.group(1)
continue
}
if (barePredicate.test(line)) {
countMap[language] = countMap.getOrDefault(language, 0) + 1
}
}
} else {
println("Got a ${titleResponse.statusCode()} status code")
}
}
for (entry in countMap.entries) {
println("${entry.value} in ${entry.key}")
}
} else {
println("Got a ${titleResponse.statusCode()} status code")
}
}
|
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.
|
#Forth
|
Forth
|
: quadratic ( fa fb fc -- r1 r2 )
frot frot
( c a b )
fover 3 fpick f* -4e f* fover fdup f* f+
( c a b det )
fdup f0< if abort" imaginary roots" then
fsqrt
fover f0< if fnegate then
f+ fnegate
( c a b-det )
2e f/ fover f/
( c a r1 )
frot frot f/ fover f/ ;
|
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.
|
#Fortran
|
Fortran
|
PROGRAM QUADRATIC
IMPLICIT NONE
INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15)
REAL(dp) :: a, b, c, e, discriminant, rroot1, rroot2
COMPLEX(dp) :: croot1, croot2
WRITE(*,*) "Enter the coefficients of the equation ax^2 + bx + c"
WRITE(*, "(A)", ADVANCE="NO") "a = "
READ *, a
WRITE(*,"(A)", ADVANCE="NO") "b = "
READ *, b
WRITE(*,"(A)", ADVANCE="NO") "c = "
READ *, c
WRITE(*,"(3(A,E23.15))") "Coefficients are: a = ", a, " b = ", b, " c = ", c
e = 1.0e-9_dp
discriminant = b*b - 4.0_dp*a*c
IF (ABS(discriminant) < e) THEN
rroot1 = -b / (2.0_dp * a)
WRITE(*,*) "The roots are real and equal:"
WRITE(*,"(A,E23.15)") "Root = ", rroot1
ELSE IF (discriminant > 0) THEN
rroot1 = -(b + SIGN(SQRT(discriminant), b)) / (2.0_dp * a)
rroot2 = c / (a * rroot1)
WRITE(*,*) "The roots are real:"
WRITE(*,"(2(A,E23.15))") "Root1 = ", rroot1, " Root2 = ", rroot2
ELSE
croot1 = (-b + SQRT(CMPLX(discriminant))) / (2.0_dp*a)
croot2 = CONJG(croot1)
WRITE(*,*) "The roots are complex:"
WRITE(*,"(2(A,2E23.15,A))") "Root1 = ", croot1, "j ", " Root2 = ", croot2, "j"
END IF
|
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
|
#BCPL
|
BCPL
|
get "libhdr"
let rot13(x) =
'A' <= x <= 'Z' -> (x - 'A' + 13) rem 26 + 'A',
'a' <= x <= 'z' -> (x - 'a' + 13) rem 26 + 'a',
x
let start() be
$( let ch = rdch()
if ch = endstreamch then break
wrch(rot13(ch))
$) repeat
|
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 }
|
#Liberty_BASIC
|
Liberty BASIC
|
'[RC] Runge-Kutta method
'initial conditions
x0 = 0
y0 = 1
'step
h = 0.1
'number of points
N=101
y=y0
FOR i = 0 TO N-1
x = x0+ i*h
IF x = INT(x) THEN
actual = exactY(x)
PRINT "y("; x ;") = "; y; TAB(20); "Error = "; actual - y
END IF
k1 = h*dydx(x,y)
k2 = h*dydx(x+h/2,y+k1/2)
k3 = h*dydx(x+h/2,y+k2/2)
k4 = h*dydx(x+h,y+k3)
y = y + 1/6 * (k1 + 2*k2 + 2*k3 + k4)
NEXT i
function dydx(x,y)
dydx=x*sqr(y)
end function
function exactY(x)
exactY=(x^2 + 4)^2 / 16
end function
|
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
|
#Phix
|
Phix
|
-- demo\rosetta\Find_unimplemented_tasks.exw
without js -- (libcurl, file i/o, peek, progress..)
constant language = "Phix",
-- language = "Go",
-- language = "Julia",
-- language = "Python",
-- language = "Wren",
base_query = "http://rosettacode.org/mw/api.php?action=query"&
"&format=xml&list=categorymembers&cmlimit=100"
include builtins\libcurl.e
atom curl = NULL
atom pErrorBuffer
include builtins\xml.e
function req(string url, integer rid)
if curl=NULL then
curl_global_init()
curl = curl_easy_init()
pErrorBuffer = allocate(CURL_ERROR_SIZE)
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pErrorBuffer)
end if
curl_easy_setopt(curl, CURLOPT_URL, url)
object res = curl_easy_perform_ex(curl)
if integer(res) then
string error = sprintf("%d [%s]",{res,peek_string(pErrorBuffer)})
crash("Download error: %s\n",{error})
end if
if not string(res) then ?9/0 end if
object xml = xml_parse(res)[XML_CONTENTS]
res = xml_get_nodes(xml,"continue")
res = iff(res=={}?"":xml_get_attribute(res[1],"cmcontinue"))
xml = xml_get_nodes(xml,"query")[1]
xml = xml_get_nodes(xml,"categorymembers")[1]
xml = xml_get_nodes(xml,"cm")
for i=1 to length(xml) do
call_proc(rid,{xml_get_attribute(xml[i],"title")})
end for
return res
end function
function html_clean(string ri)
ri = substitute(ri,`"`,`"`)
ri = substitute(ri,`'`,`'`)
ri = substitute(ri,"\xE2\x80\x99","'")
ri = substitute(ri,"\xC3\xB6","o")
ri = substitute(ri,"%3A",":")
ri = substitute(ri,"%E2%80%93","-")
ri = substitute(ri,"%E2%80%99","'")
ri = substitute(ri,"%27","'")
ri = substitute(ri,"%2B","+")
ri = substitute(ri,"%C3%A8","e")
ri = substitute(ri,"%C3%A9","e")
ri = substitute(ri,"%C3%B6","o")
ri = substitute(ri,"%C5%91","o")
ri = substitute(ri,"%22",`"`)
ri = substitute(ri,"%2A","*")
return ri
end function
sequence titles = {}
procedure store_title(string title)
titles = append(titles,title)
end procedure
integer unimplemented_count = 0,
task_count = 0
procedure print_unimplemented(string title)
if not find(title,titles) then
title = html_clean(title)
printf(1,"%s\n",{title})
unimplemented_count += 1
end if
task_count += 1
end procedure
procedure main()
printf(1,"Loading implemented tasks list...\n")
-- get and store task itles
string lang_query := base_query & "&cmtitle=Category:" & language,
continue_at := req(lang_query, store_title)
while continue_at!="" do
continue_at = req(lang_query&"&cmcontinue="&continue_at, store_title)
end while
-- a quick check to avoid long output
if length(titles)==0 then
printf(1,"no tasks implemented for %s\n", {language})
return
end if
-- get tasks, print as we go along
printf(1,"Tasks:\n")
string task_query := base_query & "&cmtitle=Category:Programming_Tasks"
continue_at = req(task_query, print_unimplemented)
while continue_at!="" do
continue_at = req(task_query&"&cmcontinue="&continue_at, print_unimplemented)
end while
printf(1,"%d unimplemented tasks found for %s.\n",{unimplemented_count,language})
integer full_tasks = unimplemented_count
printf(1,"Draft tasks:\n")
task_query := base_query & "&cmtitle=Category:Draft_Programming_Tasks"
continue_at = req(task_query, print_unimplemented)
while continue_at!="" do
continue_at = req(task_query&"&cmcontinue="&continue_at, print_unimplemented)
end while
integer draft_tasks = unimplemented_count-full_tasks
printf(1,"%d unimplemented draft tasks found for %s.\n",{draft_tasks,language})
printf(1,"%d unimplemented tasks in total found for %s (out of %d).\n",{unimplemented_count,language,task_count})
end procedure
main()
|
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.
|
#Lua
|
Lua
|
lpeg = require 'lpeg' -- see http://www.inf.puc-rio.br/~roberto/lpeg/
imports = 'P R S C V match'
for w in imports:gmatch('%a+') do _G[w] = lpeg[w] end -- make e.g. 'lpeg.P' function available as 'P'
function tosymbol(s) return s end
function tolist(x, ...) return {...} end -- ignore the first capture, the whole sexpr
ws = S' \t\n'^0 -- whitespace, 0 or more
digits = R'09'^1 -- digits, 1 or more
Tnumber = C(digits * (P'.' * digits)^-1) * ws / tonumber -- ^-1 => at most 1
Tstring = C(P'"' * (P(1) - P'"')^0 * P'"') * ws
sep = S'()" \t\n'
symstart = (P(1) - (R'09' + sep))
symchar = (P(1) - sep)
Tsymbol = C(symstart * symchar^0) * ws / tosymbol
atom = Tnumber + Tstring + Tsymbol
lpar = P'(' * ws
rpar = P')' * ws
sexpr = P{ -- defines a recursive pattern
'S';
S = ws * lpar * C((atom + V'S')^0) * rpar / tolist
}
|
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.
|
#min
|
min
|
randomize ; Seed the rng with current timestamp.
; Implement some general operators we'll need that aren't in the library.
(() 0 shorten) :new
((new (over -> swons)) dip times nip) :replicate
(('' '' '') => spread if) :if?
((1 0 if?) concat map sum) :count
(5 random succ) :d6 ; Roll a 1d6.
('d6 4 replicate '< sort 3 take sum) :attr ; Roll an attribute.
('attr 6 replicate) :attrs ; Roll 6 attributes.
(sum 75 >=) :big? ; Is a set of attributes "big?"
(attrs (dup big?) () (pop attrs) () linrec) :big ; Roll a set of big attributes.
((15 >=) count 2 >=) :special? ; Is a set of atributes "special?"
(big (dup special?) () (pop big) () linrec) :stats ; Roll a set of big and special attributes.
stats puts "Total: " print! sum puts!
|
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.
|
#MiniScript
|
MiniScript
|
roll = function()
results = []
for i in range(0,3)
results.push ceil(rnd * 6)
end for
results.sort
results.remove 0
return results.sum
end function
while true
attributes = []
gt15 = 0 // (how many attributes > 15)
for i in range(0,5)
attributes.push roll
if attributes[i] > 15 then gt15 = gt15 + 1
end for
print "Attribute values: " + attributes.join(", ")
print "Attributes total: " + attributes.sum
if attributes.sum >= 75 and gt15 >= 2 then break
print "Attributes failed, rerolling"
print
end while
print "Success!"
|
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
|
#Scala
|
Scala
|
import scala.annotation.tailrec
import scala.collection.parallel.mutable
import scala.compat.Platform
object GenuineEratosthenesSieve extends App {
def sieveOfEratosthenes(limit: Int) = {
val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt)
@tailrec
def prim(candidate: Int): Unit = {
if (candidate <= sqrtLimit) {
if (primes contains candidate) primes --= candidate * candidate to limit by candidate
prim(candidate + 1)
}
}
prim(2)
primes
}
// BitSet toList is shuffled when using the ParSet version. So it has to be sorted before using it as a sequence.
assert(sieveOfEratosthenes(15099480).size == 976729)
println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}
|
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
|
#jq
|
jq
|
#!/bin/bash
# Produce lines of the form: URI TITLE
function titles {
local uri="http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers"
uri+="&cmtitle=Category:Programming_Tasks&cmlimit=5000&format=json"
curl -Ss "$uri" |
jq -r '.query.categorymembers[] | .title | "\(@uri) \(.)"'
}
# Syntax: count URI
function count {
local uri="$1"
curl -Ss "http://rosettacode.org/mw/index.php?title=${uri}&action=raw" |
jq -R -n 'reduce (inputs|select(test("=={{header\\|"))) as $x(0; .+1)'
}
local n=0 i
while read uri title
do
i=$(count "$uri")
echo "$title: $i examples."
n=$((n + i))
done < <(titles)
echo Total: $n examples.
|
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
|
#Julia
|
Julia
|
using HTTP, JSON, Dates
rosorg = "http://rosettacode.org"
qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json"
sqURI = rosorg * "/wiki/"
topages(js, v) = for d in js["query"]["categorymembers"] push!(v, sqURI * replace(d["title"], " " => "_")) end
function getpages(uri)
wikipages = Vector{String}()
response = HTTP.request("GET", rosorg * uri)
if response.status == 200
fromjson = JSON.parse(String(response.body))
topages(fromjson, wikipages)
while haskey(fromjson, "continue")
cmcont, cont = fromjson["continue"]["cmcontinue"], fromjson["continue"]["continue"]
response = HTTP.request("GET", rosorg * uri * "&cmcontinue=$cmcont&continue=$cont")
fromjson = JSON.parse(String(response.body))
topages(fromjson, wikipages)
end
end
wikipages
end
function processtaskpages(wpages, verbose=false)
totalexamples = 0
for pag in wpages
response = HTTP.request("GET", pag)
if response.status == 200
n = length(collect(eachmatch(r"span class=\"mw-headline\"", String(response.body))))
if verbose
println("Wiki page $pag => $n examples.")
end
totalexamples += n
end
end
println("Total of $totalexamples on $(length(wpages)) task pages.\n")
end
println("Programming examples at $(DateTime(now())):")
qURI |> getpages |> processtaskpages
println("Draft programming tasks:")
qdURI |> getpages |> processtaskpages
|
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
|
#K
|
K
|
Haystack:("Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo")
Needles:("Washington";"Bush")
{:[y _in x;(y;x _bin y);(y;"Not Found")]}[Haystack]'Needles
|
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.
|
#Julia
|
Julia
|
using HTTP
try
response = HTTP.request("GET", "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000")
langcount = Dict{String, Int}()
for mat in eachmatch(r"<li><a href[^\>]+>([^\<]+)</a>[^1-9]+(\d+)[^\w]+member.?.?</li>", String(response.body))
if match(r"^Programming", mat.captures[1]) == nothing
langcount[mat.captures[1]] = parse(Int, mat.captures[2])
end
end
langs = sort(collect(keys(langcount)), lt=(x, y)->langcount[x]<langcount[y], rev=true)
for (i, lang) in enumerate(langs)
println("Language $lang can be ranked #$i at $(langcount[lang]).")
end
catch y
println("HTTP request failed: $y.")
exit()
end
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#8080_Assembly
|
8080 Assembly
|
org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes a 16-bit integer in HL, and stores it
;; as a 0-terminated string starting at BC.
;; On exit, all registers destroyed; BC pointing at
;; end of string.
mkroman: push h ; put input on stack
lxi h,mkromantab
mkromandgt: mov a,m ; scan ahead to next entry
ana a
inx h
jnz mkromandgt
xthl ; load number
mov a,h ; if zero, we're done
ora l
jz mkromandone
xthl ; load next entry from table
mov e,m ; de = number
inx h
mov d,m
inx h
xthl ; load number
xra a ; find how many we need
subtract: inr a ; with trial subtraction
dad d
jc subtract
push psw ; keep counter
mov a,d ; we subtracted one too many
cma ; so we need to add one back
mov d,a
mov a,e
cma
mov e,a
inx d
dad d
pop d ; restore counter (into D)
xthl ; load table pointer
stringouter: dcr d ; do we need to include one?
jz mkromandgt
push h ; keep string location
stringinner: mov a,m ; copy string into target
stax b
ana a ; done yet?
jz stringdone
inx h
inx b ; copy next character
jmp stringinner
stringdone: pop h ; restore string location
jmp stringouter
mkromandone: pop d ; remove temporary variable from stack
ret
mkromantab: db 0
db 18h,0fch,'M',0 ; The value for each entry
db 7ch,0fch,'CM',0 ; is stored already negated
db 0ch,0feh,'D',0 ; so that it can be immediately
db 70h,0feh,'CD',0 ; added using `dad'.
db 9ch,0ffh,'C',0 ; This also has the convenient
db 0a6h,0ffh,'XC',0 ; property of not having any
db 0ceh,0ffh,'L',0 ; zero bytes except the string
db 0d8h,0ffh,'XL',0 ; and row terminators.
db 0f6h,0ffh,'X',0
db 0f7h,0ffh,'IX',0
db 0fbh,0ffh,'V',0
db 0fch,0ffh,'IV',0
db 0ffh,0ffh,'I',0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test code
test: mvi c,10 ; read string from console
lxi d,dgtbufdef
call 5
lxi h,0 ; convert to integer
lxi b,dgtbuf
readdgt: ldax b
ana a
jz convert
dad h ; hl *= 10
mov d,h
mov e,l
dad h
dad h
dad d
sui '0'
mov e,a
mvi d,0
dad d
inx b
jmp readdgt
convert: lxi b,romanbuf ; convert to roman
call mkroman
mvi a,'$' ; switch string terminator
stax b
mvi c,9 ; output result
lxi d,romanbuf
jmp 5
nl: db 13,10,'$'
dgtbufdef: db 5,0
dgtbuf: ds 6
romanbuf:
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Action.21
|
Action!
|
CARD FUNC DecodeRomanDigit(CHAR c)
IF c='I THEN RETURN (1)
ELSEIF c='V THEN RETURN (5)
ELSEIF c='X THEN RETURN (10)
ELSEIF c='L THEN RETURN (50)
ELSEIF c='C THEN RETURN (100)
ELSEIF c='D THEN RETURN (500)
ELSEIF c='M THEN RETURN (1000)
FI
RETURN (0)
CARD FUNC DecodeRomanNumber(CHAR ARRAY s)
CARD res,curr,prev
BYTE i
res=0 prev=0 i=s(0)
WHILE i>0
DO
curr=DecodeRomanDigit(s(i))
IF curr<prev THEN
res==-curr
ELSE
res==+curr
FI
prev=curr
i==-1
OD
RETURN (res)
PROC Test(CHAR ARRAY s)
CARD n
n=DecodeRomanNumber(s)
PrintF("%S=%U%E",s,n)
RETURN
PROC Main()
Test("MCMXC")
Test("MMVIII")
Test("MDCLXVI")
Test("MMMDCCCLXXXVIII")
Test("MMMCMXCIX")
RETURN
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#Axiom
|
Axiom
|
expr := x^3-3*x^2+2*x
solve(expr,x)
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#BBC_BASIC
|
BBC BASIC
|
function$ = "x^3-3*x^2+2*x"
rangemin = -1
rangemax = 3
stepsize = 0.001
accuracy = 1E-8
PROCroots(function$, rangemin, rangemax, stepsize, accuracy)
END
DEF PROCroots(func$, min, max, inc, eps)
LOCAL x, sign%, oldsign%
oldsign% = 0
FOR x = min TO max STEP inc
sign% = SGN(EVAL(func$))
IF sign% = 0 THEN
PRINT "Root found at x = "; x
sign% = -oldsign%
ELSE IF sign% <> oldsign% AND oldsign% <> 0 THEN
IF inc < eps THEN
PRINT "Root found near x = "; x
ELSE
PROCroots(func$, x-inc, x+inc/8, inc/8, eps)
ENDIF
ENDIF
ENDIF
oldsign% = sign%
NEXT x
ENDPROC
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Aime
|
Aime
|
text
computer_play(record plays, record beats)
{
integer a, c, total;
text s;
total = plays["rock"] + plays["paper"] + plays["scissors"];
a = drand(total - 1);
for (s, c in plays) {
if (a < c) {
break;
}
a -= c;
}
beats[s];
}
integer
main(void)
{
integer computer, human;
record beats, plays;
file f;
text s;
computer = human = 0;
f.stdin;
beats["rock"] = "paper";
beats["paper"] = "scissors";
beats["scissors"] = "rock";
plays["rock"] = 1;
plays["paper"] = 1;
plays["scissors"] = 1;
while (1) {
o_text("Your choice [rock/paper/scissors]:\n");
if (f.line(s) == -1) {
break;
}
if (!plays.key(s)) {
o_text("Invalid choice, try again\n");
} else {
text c;
c = computer_play(plays, beats);
o_form("Human: ~, Computer: ~\n", s, c);
if (s == c) {
o_text("Draw\n");
} elif (c == beats[s]) {
computer += 1;
o_text("Computer wins\n");
} else {
human += 1;
o_text("Human wins\n");
}
plays.up(s);
o_form("Score: Human: ~, Computer: ~\n", human, computer);
}
}
return 0;
}
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#COBOL
|
COBOL
|
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. run-length-encoding.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION encode
FUNCTION decode
.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 input-str PIC A(100).
01 encoded PIC X(200).
01 decoded PIC X(200).
PROCEDURE DIVISION.
ACCEPT input-str
MOVE encode(FUNCTION TRIM(input-str)) TO encoded
DISPLAY "Encoded: " FUNCTION TRIM(encoded)
DISPLAY "Decoded: " FUNCTION TRIM(decode(encoded))
.
END PROGRAM run-length-encoding.
IDENTIFICATION DIVISION.
FUNCTION-ID. encode.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 str-len PIC 9(3) COMP.
01 i PIC 9(3) COMP.
01 current-char PIC A.
01 num-chars PIC 9(3) COMP.
01 num-chars-disp PIC Z(3).
01 encoded-pos PIC 9(3) COMP VALUE 1.
LINKAGE SECTION.
01 str PIC X ANY LENGTH.
01 encoded PIC X(200).
PROCEDURE DIVISION USING str RETURNING encoded.
MOVE FUNCTION LENGTH(str) TO str-len
MOVE str (1:1) TO current-char
MOVE 1 TO num-chars
PERFORM VARYING i FROM 2 BY 1 UNTIL i > str-len
IF str (i:1) <> current-char
CALL "add-num-chars" USING encoded, encoded-pos,
CONTENT current-char, num-chars
MOVE str (i:1) TO current-char
MOVE 1 TO num-chars
ELSE
ADD 1 TO num-chars
END-IF
END-PERFORM
CALL "add-num-chars" USING encoded, encoded-pos, CONTENT current-char,
num-chars
.
END FUNCTION encode.
IDENTIFICATION DIVISION.
PROGRAM-ID. add-num-chars.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 num-chars-disp PIC Z(3).
LINKAGE SECTION.
01 str PIC X(200).
01 current-pos PIC 9(3) COMP.
01 char-to-encode PIC X.
01 num-chars PIC 9(3) COMP.
PROCEDURE DIVISION USING str, current-pos, char-to-encode, num-chars.
MOVE num-chars TO num-chars-disp
MOVE FUNCTION TRIM(num-chars-disp) TO str (current-pos:3)
ADD FUNCTION LENGTH(FUNCTION TRIM(num-chars-disp)) TO current-pos
MOVE char-to-encode TO str (current-pos:1)
ADD 1 TO current-pos
.
END PROGRAM add-num-chars.
IDENTIFICATION DIVISION.
FUNCTION-ID. decode.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 encoded-pos PIC 9(3) COMP VALUE 1.
01 decoded-pos PIC 9(3) COMP VALUE 1.
01 num-of-char PIC 9(3) COMP VALUE 0.
LINKAGE SECTION.
01 encoded PIC X(200).
01 decoded PIC X(100).
PROCEDURE DIVISION USING encoded RETURNING decoded.
PERFORM VARYING encoded-pos FROM 1 BY 1
UNTIL encoded (encoded-pos:2) = SPACES OR encoded-pos > 200
IF encoded (encoded-pos:1) IS NUMERIC
COMPUTE num-of-char = num-of-char * 10
+ FUNCTION NUMVAL(encoded (encoded-pos:1))
ELSE
PERFORM UNTIL num-of-char = 0
MOVE encoded (encoded-pos:1) TO decoded (decoded-pos:1)
ADD 1 TO decoded-pos
SUBTRACT 1 FROM num-of-char
END-PERFORM
END-IF
END-PERFORM
.
END FUNCTION decode.
|
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.
|
#Frink
|
Frink
|
roots[n] :=
{
a = makeArray[[n], 0]
alpha = 360/n degrees
theta = 0 degrees
for k = 0 to length[a] - 1
{
a@k = cos[theta] + i sin[theta]
theta = theta + alpha
}
a
}
|
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.
|
#FunL
|
FunL
|
import math.{exp, Pi}
def rootsOfUnity( n ) = {exp( 2Pi i k/n ) | k <- 0:n}
println( rootsOfUnity(3) )
|
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.
|
#Maple
|
Maple
|
#Did not count the tasks where languages tasks are properly closed
add_lan := proc(language, n, existence, languages, pos)
if (assigned(existence[language])) then
existence[language] += n:
return pos;
else
existence[language] := n:
languages(pos) := language:
return pos+1;
end if;
end proc:
count_tags := proc(tasks, pos)
local task, url, txt, header_tags, close_tags, close_len, header_len, occurence, i, pos_copy;
pos_copy := pos:
for task in tasks do
url := cat("http://www.rosettacode.org/mw/index.php?title=", StringTools:-Encode(StringTools:-SubstituteAll(task["title"], " ", "_"), 'percent'), "&action=raw"):
txt := URL:-Get(url):
header_tags := [StringTools:-SearchAll("=={{header|", txt)]:
close_tags := [StringTools:-SearchAll("}}==",txt)]:
close_len := numelems(close_tags):
header_len := numelems(header_tags):
if header_len = 0 then
break;
end if;
if (not header_len = close_len) then
printf("%s is not counted since some language tags are not properly closed.\n", task["title"]);
break;
end if;
occurence := numelems([StringTools:-SearchAll("<lang>", txt[1..header_tags[1]])]):
if occurence > 0 then
pos_copy := add_lan("no languages", occurence, existence, languages, pos_copy):
end if:
if close_len > 1 then
for i from 2 to close_len do
occurence := numelems([StringTools:-SearchAll("<lang>", txt[header_tags[i-1]..header_tags[i]])]):
if occurence > 0 then
pos_copy := add_lan(txt[header_tags[i-1]+11..close_tags[i-1]-1], occurence, existence, languages, pos_copy):
end if:
end do:
occurence := numelems([StringTools:-SearchAll("<lang>", txt[header_tags[-1]..])]):
if occurence > 0 then
pos_copy := add_lan(txt[header_tags[-1]+11..close_tags[-1]-1], occurence, existence, languages, pos_copy):
end if:
end if:
end do:
return pos_copy:
end proc:
existence := table():
languages := Array():
pos := 1:
#go through every task
x := JSON:-ParseFile("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json"):
pos := count_tags(x["query"]["categorymembers"], pos):
while(assigned(x["continue"]["cmcontinue"])) do
continue := x["continue"]["cmcontinue"]:
more_tasks:= cat("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json", "&continue=", x["continue"]["continue"], "&cmcontinue=", x["continue"]["cmcontinue"]):
x := JSON:-ParseFile(more_tasks):
pos := count_tags(x["query"]["categorymembers"], pos):
end do:
#Prints out the table
total := 0:
for lan in languages do
total += existence[lan]:
printf("There are %d bare lang tags in %s\n", existence[lan], lan);
end do:
printf("Total number %d", total);
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
tasks[page_: ""] :=
Module[{res =
Import["http://rosettacode.org/mw/api.php?format=xml&action=\
query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=\
500" <> page, "XML"]},
If[MemberQ[res[[2, 3]], XMLElement["query-continue", __]],
Join[res[[2, 3, 1, 3, 1, 3, All, 2, 3, 2]],
tasks["&cmcontinue=" <> res[[2, 3, 2, 3, 1, 2, 1, 2]]]],
res[[2, 3, 1, 3, 1, 3, All, 2, 3, 2]]]];
bareTags = # -> (# -> StringCount[#2, "<lang>"] &) @@@
Partition[
Prepend[StringSplit[
Import["http://rosettacode.org/wiki?action=raw&title=" <>
URLEncode[#], "Text"],
Shortest["=={{header|" ~~ x__ ~~ "}}=="] :> x],
"no language"] //. {a___,
multi_String?StringContainsQ["}}" ~~ ___ ~~ "{{header|"],
bare_Integer, b___} :> {a, StringSplit[multi, "}"][[1]],
bare, StringSplit[multi, "|"][[-1]], bare, b}, 2] & /@
tasks[];
Print[IntegerString[Total[Flatten[bareTags[[All, 2, All, 2]]]]] <>
" bare language tags.\n"];
langCounts =
Normal[Total /@
GroupBy[Flatten[bareTags[[All, 2]]], Keys -> Values]];
Print[IntegerString[#2] <> " in " <> # <> " ([[" <>
StringRiffle[
Keys[Select[bareTags,
Function[task, MemberQ[task[[2]], # -> _Integer?Positive]]]],
"]], [["] <> "]])"] & @@@
Select[SortBy[langCounts, Keys], #[[2]] > 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.
|
#Nim
|
Nim
|
import algorithm, htmlparser, httpclient, json
import sequtils, strformat, strscans, tables, times, xmltree
import strutils except escape
const
Rosorg = "http://rosettacode.org"
QUri = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
QdUri = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json"
SqUri = "http://www.rosettacode.org/mw/index.php?title="
proc addPages(pages: var seq[string], fromJson: JsonNode) =
for d in fromJson{"query", "categorymembers"}:
pages.add SqUri & d["title"].getStr().replace(" ", "_").escape() & "&action=raw"
proc getPages(client: var HttpClient; uri: string): seq[string] =
let response = client.get(Rosorg & uri)
if response.status == $Http200:
var fromJson = response.body.parseJson()
result.addPages(fromJson)
while fromJson.hasKey("continue"):
let cmcont = fromJson{"continue", "cmcontinue"}.getStr()
let cont = fromJson{"continue", "continue"}.getStr()
let response = client.get(Rosorg & uri & fmt"&cmcontinue={cmcont}&continue={cont}")
fromJson = response.body.parseJson()
result.addPages(fromJson)
proc processTaskPages(client: var HttpClient; pages: seq[string]; verbose = false) =
var totalCount = 0
var langCount: CountTable[string]
for page in pages:
var count, checked = 0
try:
let response = client.get(page)
if response.status == $Http200:
let doc = response.body.parseHtml()
if doc.kind != xnElement: continue
var lastText = ""
for elem in doc:
if elem.kind == xnElement and elem.tag == "lang":
if elem.attrs.isNil:
inc count
if lastText.len != 0:
if verbose:
echo "Missing lang attribute for lang ", lastText
langCount.inc lastText
else:
inc checked
elif elem.kind == xnText:
discard elem.text.scanf("=={{header|$+}}", lastText):
except CatchableError:
if verbose:
echo &"Page {page} is not loaded or found: {getCurrentExceptionMsg()}"
continue
if count > 0 and verbose:
echo &"Page {page} had {count} bare lang tags."
inc totalCount, count
echo &"Total bare tags: {totalCount}."
for k in sorted(toSeq(langCount.keys)):
echo &"Total bare <lang> for language {k}: ({langcount[k]})"
echo "Programming examples at ", now()
var client = newHttpClient()
client.processTaskPages(client.getPages(QUri))
echo "\nDraft programming tasks:"
client.processTaskPages(client.getPages(QdUri))
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' version 20-12-2020
' compile with: fbc -s console
#Include Once "gmp.bi"
Sub solvequadratic_n(a As Double ,b As Double, c As Double)
Dim As Double f, d = b ^ 2 - 4 * a * c
Select Case Sgn(d)
Case 0
Print "1: the single root is "; -b / 2 / a
Case 1
Print "1: the real roots are "; (-b + Sqr(d)) / 2 * a; " and ";(-b - Sqr(d)) / 2 * a
Case -1
Print "1: the complex roots are "; -b / 2 / a; " +/- "; Sqr(-d) / 2 / a; "*i"
End Select
End Sub
Sub solvequadratic_c(a As Double ,b As Double, c As Double)
Dim As Double f, d = b ^ 2 - 4 * a * c
Select Case Sgn(d)
Case 0
Print "2: the single root is "; -b / 2 / a
Case 1
f = (1 + Sqr(1 - 4 * a *c / b ^ 2)) / 2
Print "2: the real roots are "; -f * b / a; " and "; -c / b / f
Case -1
Print "2: the complex roots are "; -b / 2 / a; " +/- "; Sqr(-d) / 2 / a; "*i"
End Select
End Sub
Sub solvequadratic_gmp(a_ As Double ,b_ As Double, c_ As Double)
#Define PRECISION 1024 ' about 300 digits
#Define MAX 25
Dim As ZString Ptr text
text = Callocate (1000)
Mpf_set_default_prec(PRECISION)
Dim As Mpf_ptr a, b, c, d, t
a = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(a, a_)
b = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(b, b_)
c = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(c, c_)
d = Allocate(Len(__mpf_struct)) : Mpf_init(d)
t = Allocate(Len(__mpf_struct)) : Mpf_init(t)
mpf_mul(d, b, b)
mpf_set_ui(t, 4)
mpf_mul(t, t, a)
mpf_mul(t, t, c)
mpf_sub(d, d, t)
Select Case mpf_sgn(d)
Case 0
mpf_neg(t, b)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the single root is "; *text
Case Is > 0
mpf_sqrt(d, d)
mpf_add(a, a, a)
mpf_neg(t, b)
mpf_add(t, t, d)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the real roots are "; *text; " and ";
mpf_neg(t, b)
mpf_sub(t, t, d)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print *text
Case Is < 0
mpf_neg(t, b)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the complex roots are "; *text; " +/- ";
mpf_neg(t, d)
mpf_sqrt(t, t)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print *text; "*i"
End Select
End Sub
' ------=< MAIN >=------
Dim As Double a, b, c
Print "1: is the naieve way"
Print "2: is the cautious way"
Print "3: is the naieve way with help of GMP"
Print
For i As Integer = 1 To 10
Read a, b, c
Print "Find root(s) for "; Str(a); "X^2"; IIf(b < 0, "", "+");
Print Str(b); "X"; IIf(c < 0, "", "+"); Str(c)
solvequadratic_n(a, b , c)
solvequadratic_c(a, b , c)
solvequadratic_gmp(a, b , c)
Print
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
Data 1, -1E9, 1
Data 1, 0, 1
Data 2, -1, -6
Data 1, 2, -2
Data 0.5, 1.4142135623731, 1
Data 1, 3, 2
Data 3, 4, 5
Data 1, -1e100, 1
Data 1, -1e200, 1
Data 1, -1e300, 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
|
#Befunge
|
Befunge
|
~:"z"`#v_:"m"`#v_:"`"` |>
:"Z"`#v_:"M"`#v_:"@"`|>
: 0 `#v_@v-6-7< >
, < <+6+7 <<v
|
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 }
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
(* Symbolic solution *)
DSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, t]
Table[{t, 1/16 (4 + t^2)^2}, {t, 0, 10}]
(* Numerical solution I (not RK4) *)
Table[{t, y[t], Abs[y[t] - 1/16*(4 + t^2)^2]}, {t, 0, 10}] /.
First@NDSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, {t, 0, 10}]
(* Numerical solution II (RK4) *)
f[{t_, y_}] := {1, t Sqrt[y]}
h = 0.1;
phi[y_] := Module[{k1, k2, k3, k4},
k1 = h*f[y];
k2 = h*f[y + 1/2 k1];
k3 = h*f[y + 1/2 k2];
k4 = h*f[y + k3];
y + k1/6 + k2/3 + k3/3 + k4/6]
solution = NestList[phi, {0, 1}, 101];
Table[{y[[1]], y[[2]], Abs[y[[2]] - 1/16 (y[[1]]^2 + 4)^2]},
{y, solution[[1 ;; 101 ;; 10]]}]
|
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 }
|
#MATLAB
|
MATLAB
|
function testRK4Programs
figure
hold on
t = 0:0.1:10;
y = 0.0625.*(t.^2+4).^2;
plot(t, y, '-k')
[tode4, yode4] = testODE4(t);
plot(tode4, yode4, '--b')
[trk4, yrk4] = testRK4(t);
plot(trk4, yrk4, ':r')
legend('Exact', 'ODE4', 'RK4')
hold off
fprintf('Time\tExactVal\tODE4Val\tODE4Error\tRK4Val\tRK4Error\n')
for k = 1:10:length(t)
fprintf('%.f\t\t%7.3f\t\t%7.3f\t%7.3g\t%7.3f\t%7.3g\n', t(k), y(k), ...
yode4(k), abs(y(k)-yode4(k)), yrk4(k), abs(y(k)-yrk4(k)))
end
end
function [t, y] = testODE4(t)
y0 = 1;
y = ode4(@(tVal,yVal)tVal*sqrt(yVal), t, y0);
end
function [t, y] = testRK4(t)
dydt = @(tVal,yVal)tVal*sqrt(yVal);
y = zeros(size(t));
y(1) = 1;
for k = 1:length(t)-1
dt = t(k+1)-t(k);
dy1 = dt*dydt(t(k), y(k));
dy2 = dt*dydt(t(k)+0.5*dt, y(k)+0.5*dy1);
dy3 = dt*dydt(t(k)+0.5*dt, y(k)+0.5*dy2);
dy4 = dt*dydt(t(k)+dt, y(k)+dy3);
y(k+1) = y(k)+(dy1+2*dy2+2*dy3+dy4)/6;
end
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
|
#PicoLisp
|
PicoLisp
|
(load "@lib/http.l" "@lib/xm.l")
(de rosettaCategory (Cat)
(let (Cont NIL Xml)
(make
(loop
(client "rosettacode.org" 80
(pack
"mw/api.php?action=query&list=categorymembers&cmtitle=Category:"
Cat
"&cmlimit=200&format=xml"
Cont )
(while (line))
(setq Xml (and (xml?) (xml))) )
(NIL Xml)
(for M (body Xml 'query 'categorymembers)
(link (attr M 'title)) )
(NIL (attr Xml 'query-continue' categorymembers 'cmcontinue))
(setq Cont (pack "&cmcontinue=" @)) ) ) ) )
(de unimplemented (Task)
(diff
(rosettaCategory "Programming_Tasks")
(rosettaCategory Task) ) )
|
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
|
#PowerShell
|
PowerShell
|
function Find-UnimplementedTask
{
[CmdletBinding()]
[OutputType([string[]])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[string]
$Language
)
$url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_$Language"
$web = Invoke-WebRequest $url
$unimplemented = 1
[string[]](($web.AllElements |
Where-Object {$_.class -eq "mw-content-ltr"})[$unimplemented].outerText -split "`r`n" |
Select-String -Pattern "[^0-9A-Z]$" -CaseSensitive)
}
|
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.
|
#Nim
|
Nim
|
import strutils
const Input = """
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
"""
type
TokenKind = enum
tokInt, tokFloat, tokString, tokIdent
tokLPar, tokRPar
tokEnd
Token = object
case kind: TokenKind
of tokString: stringVal: string
of tokInt: intVal: int
of tokFloat: floatVal: float
of tokIdent: ident: string
else: discard
proc lex(input: string): seq[Token] =
var pos = 0
template current: char =
if pos < input.len: input[pos]
else: '\x00'
while pos < input.len:
case current
of ';':
inc(pos)
while current notin {'\r', '\n'}:
inc(pos)
if current == '\r': inc(pos)
if current == '\n': inc(pos)
of '(': inc(pos); result.add(Token(kind: tokLPar))
of ')': inc(pos); result.add(Token(kind: tokRPar))
of '0'..'9':
var
num = ""
isFloat = false
while current in Digits:
num.add(current)
inc(pos)
if current == '.':
num.add(current)
isFloat = true
inc(pos)
while current in Digits:
num.add(current)
inc(pos)
result.add(if isFloat: Token(kind: tokFloat, floatVal: parseFloat(num))
else: Token(kind: tokInt, intVal: parseInt(num)))
of ' ', '\t', '\n', '\r': inc(pos)
of '"':
var str = ""
inc(pos)
while current != '"':
str.add(current)
inc(pos)
inc(pos)
result.add(Token(kind: tokString, stringVal: str))
else:
const BannedChars = {' ', '\t', '"', '(', ')', ';'}
var ident = ""
while current notin BannedChars:
ident.add(current)
inc(pos)
result.add(Token(kind: tokIdent, ident: ident))
result.add(Token(kind: tokEnd))
type
SExprKind = enum
seInt, seFloat, seString, seIdent, seList
SExpr = ref object
case kind: SExprKind
of seInt: intVal: int
of seFloat: floatVal: float
of seString: stringVal: string
of seIdent: ident: string
of seList: children: seq[SExpr]
ParseError = object of CatchableError
proc `$`*(se: SExpr): string =
case se.kind
of seInt: result = $se.intVal
of seFloat: result = $se.floatVal
of seString: result = '"' & se.stringVal & '"'
of seIdent: result = se.ident
of seList:
result = "("
for i, ex in se.children:
if ex.kind == seList and ex.children.len > 1:
result.add("\n")
result.add(indent($ex, 2))
else:
if i > 0:
result.add(" ")
result.add($ex)
result.add(")")
var
tokens = lex(Input)
pos = 0
template current: Token =
if pos < tokens.len: tokens[pos]
else: Token(kind: tokEnd)
proc parseInt(token: Token): SExpr =
result = SExpr(kind: seInt, intVal: token.intVal)
proc parseFloat(token: Token): SExpr =
result = SExpr(kind: seFloat, floatVal: token.floatVal)
proc parseString(token: Token): SExpr =
result = SExpr(kind: seString, stringVal: token.stringVal)
proc parseIdent(token: Token): SExpr =
result = SExpr(kind: seIdent, ident: token.ident)
proc parse(): SExpr
proc parseList(): SExpr =
result = SExpr(kind: seList)
while current.kind notin {tokRPar, tokEnd}:
result.children.add(parse())
if current.kind == tokEnd:
raise newException(ParseError, "Missing right paren ')'")
else:
inc(pos)
proc parse(): SExpr =
var token = current
inc(pos)
result =
case token.kind
of tokInt: parseInt(token)
of tokFloat: parseFloat(token)
of tokString: parseString(token)
of tokIdent: parseIdent(token)
of tokLPar: parseList()
else: nil
echo parse()
|
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.
|
#Nim
|
Nim
|
# Import "random" to get random numbers and "algorithm" to get sorting functions for arrays.
import random, algorithm
randomize()
proc diceFourRolls(): array[4, int] =
## Generates 4 random values between 1 and 6.
for i in 0 .. 3:
result[i] = rand(1..6)
proc sumRolls(rolls: array[4, int]): int =
## Save the sum of the 3 highest values rolled.
var sorted = rolls
sorted.sort()
# By sorting first and then starting the iteration on 1 instead of 0, the lowest number is discarded even if it is repeated.
for i in 1 .. 3:
result += sorted[i]
func twoFifteens(attr: var array[6, int]): bool =
attr.sort()
# Sorting implies than the second to last number is lesser than or equal to the last.
if attr[4] < 15: false else: true
var sixAttr: array[6, int]
while true:
var sumAttr = 0
for i in 0 .. 5:
sixAttr[i] = sumRolls(diceFourRolls())
sumAttr += sixAttr[i]
echo "The roll sums are, in order: ", sixAttr, ", which adds to ", sumAttr
if not twoFifteens(sixAttr) or sumAttr < 75: echo "Not good enough. Rerolling..."
else: 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
|
#Scheme
|
Scheme
|
; Tail-recursive solution :
(define (sieve n)
(define (aux u v)
(let ((p (car v)))
(if (> (* p p) n)
(let rev-append ((u u) (v v))
(if (null? u) v (rev-append (cdr u) (cons (car u) v))))
(aux (cons p u)
(let wheel ((u '()) (v (cdr v)) (a (* p p)))
(cond ((null? v) (reverse u))
((= (car v) a) (wheel u (cdr v) (+ a p)))
((> (car v) a) (wheel u v (+ a p)))
(else (wheel (cons (car v) u) (cdr v) a))))))))
(aux '(2)
(let range ((v '()) (k (if (odd? n) n (- n 1))))
(if (< k 3) v (range (cons k v) (- k 2))))))
; > (sieve 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)
; > (length (sieve 10000000))
; 664579
|
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
|
#Lasso
|
Lasso
|
local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result))
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
with i in #root->find('query')->find('categorymembers') do => {^
#thiscount = 0
#title = #i->find('title')
#urltitle = #i->find('title')
#urltitle->replace(' ','_')
#title+': '
local(src = curl('http://rosettacode.org/mw/index.php?title='+#urltitle->asBytes->encodeurl+'&action=raw')->result->asString)
#thiscount = (#src->split('=={{header|'))->size - 1
#thiscount < 0 ? #thiscount = 0
#thiscount + ' examples.'
#totalex += #thiscount
'\r'
^}
'Total: '+#totalex+' examples.'
|
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
|
#LiveCode
|
LiveCode
|
on mouseUp
put empty into fld "taskurls"
put URL "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=xml" into apixml
put revXMLCreateTree(apixml,true,true,false) into pDocID
put "/api/query/categorymembers/cm" into pXPathExpression
repeat for each line xmlnode in revXMLEvaluateXPath(pDocID, pXPathExpression)
put revXMLAttribute(pDocID,xmlnode,"title") into pgTitle
put revXMLAttribute(pDocID,xmlnode,"pageid") into pageId
put "http://www.rosettacode.org/w/index.php?title=" & urlEncode(pgTitle) & "&action=raw" into taskURL
put URL taskURL into taskPage
filter lines of taskPage with "=={{header|*"
put the number of lines of taskPage into taskTotal
put pgTitle & comma & taskTotal & cr after fld "tasks"
add taskTotal to allTaskTotal
end repeat
put "Total" & comma & allTaskTotal after fld "tasks"
end mouseUp
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6 (search_list.kt)
fun main(args: Array<String>) {
val haystack = listOf("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag")
println(haystack)
var needle = "Zag"
var index = haystack.indexOf(needle)
val index2 = haystack.lastIndexOf(needle)
println("\n'$needle' first occurs at index $index of the list")
println("'$needle' last occurs at index $index2 of the list\n")
needle = "Donald"
index = haystack.indexOf(needle)
if (index == -1) throw Exception("$needle does not occur in the list")
}
|
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.
|
#Kotlin
|
Kotlin
|
import java.net.URL
import java.io.*
object Popularity {
/** Gets language data. */
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection() // URL completed, connection opened
// Rosetta Code objects to the default Java user agent so use a blank one
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
// have a programming language - should look like "[title] => Category:languageName"
languageName = line[':']
} else if (line.startsWith("[pages]")) {
// number of pages the language has (probably)
val pageCount = line['>']
if (pageCount != "Array") {
// haven't got "[pages] => Array" - must be a number of pages
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>'] // have an indication of whether there is more data or not
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
/** Custom sort Comparator for sorting the language list.
* Assumes the first character is the page count and the rest is the language name. */
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
// as we "know" we will be comparing languages, we will assume the Strings have the appropriate format
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
// r == 0: the counts are the same - compare the names
}
}
/** Gets the string following marker in text. */
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http://www.rosettacode.org/mw/api.php?action=query" +
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
// read/sort/print the languages (CSV format):
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#8086_Assembly
|
8086 Assembly
|
mov ax,0070h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,1776h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,2021h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,3999h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,4000h
call EncodeRoman
mov si,offset StringRam
ReturnToDos ;macro that calls the int that exits dos
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Ada
|
Ada
|
Pragma Ada_2012;
Pragma Assertion_Policy( Check );
With
Unchecked_Conversion,
Ada.Text_IO;
Procedure Test_Roman_Numerals is
-- We create an enumeration of valid characters, note that they are
-- character-literals, this is so that we can use literal-strings,
-- and that their size is that of Integer.
Type Roman_Digits is ('I', 'V', 'X', 'L', 'C', 'D', 'M' )
with Size => Integer'Size;
-- We use a representation-clause ensure the proper integral-value
-- of each individual character.
For Roman_Digits use
(
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000
);
-- To convert a Roman_Digit to an integer, we now only need to
-- read its value as an integer.
Function Convert is new Unchecked_Conversion
( Source => Roman_Digits, Target => Integer );
-- Romena_Numeral is a string of Roman_Digit.
Type Roman_Numeral is array (Positive range <>) of Roman_Digits;
-- The Numeral_List type is used herein only for testing
-- and verification-data.
Type Numeral_List is array (Positive range <>) of
not null access Roman_Numeral;
-- The Test_Cases subtype ensures that Test_Data and Validation_Data
-- both contain the same number of elements, and that the indecies
-- are the same; essentially the same as:
--
-- pragma Assert( Test_Data'Length = Validation_Data'Length
-- AND Test_Data'First = Validation_Data'First);
subtype Test_Cases is Positive range 1..14;
Test_Data : constant Numeral_List(Test_Cases):=
(
New Roman_Numeral'("III"), -- 3
New Roman_Numeral'("XXX"), -- 30
New Roman_Numeral'("CCC"), -- 300
New Roman_Numeral'("MMM"), -- 3000
New Roman_Numeral'("VII"), -- 7
New Roman_Numeral'("LXVI"), -- 66
New Roman_Numeral'("CL"), -- 150
New Roman_Numeral'("MCC"), -- 1200
New Roman_Numeral'("IV"), -- 4
New Roman_Numeral'("IX"), -- 9
New Roman_Numeral'("XC"), -- 90
New Roman_Numeral'("ICM"), -- 901
New Roman_Numeral'("CIM"), -- 899
New Roman_Numeral'("MDCLXVI") -- 1666
);
Validation_Data : constant array(Test_Cases) of Natural:=
( 3, 30, 300, 3000,
7, 66, 150, 1200,
4, 9, 90,
901, 899,
1666
);
-- In Roman numerals, the subtractive form [IV = 4] was used
-- very infrequently, the most common form was the addidive
-- form [IV = 6]. (Consider military logistics and squads.)
-- SUM returns the Number, read in the additive form.
Function Sum( Number : Roman_Numeral ) return Natural is
begin
Return Result : Natural:= 0 do
For Item of Number loop
Result:= Result + Convert( Item );
end loop;
End Return;
end Sum;
-- EVAL returns Number read in the subtractive form.
Function Eval( Number : Roman_Numeral ) return Natural is
Current : Roman_Digits:= 'I';
begin
Return Result : Natural:= 0 do
For Item of Number loop
if Current < Item then
Result:= Convert(Item) - Result;
Current:= Item;
else
Result:= Result + Convert(Item);
end if;
end loop;
End Return;
end Eval;
-- Display the given Roman_Numeral via Text_IO.
Procedure Put( S: Roman_Numeral ) is
begin
For Ch of S loop
declare
-- The 'Image attribute returns the character inside
-- single-quotes; so we select the character itself.
C : Character renames Roman_Digits'Image(Ch)(2);
begin
Ada.Text_IO.Put( C );
end;
end loop;
end;
-- This displays pass/fail dependant on the parameter.
Function PF ( Value : Boolean ) Return String is
begin
Return Result : String(1..4):= ( if Value then"pass"else"fail" );
End PF;
Begin
Ada.Text_IO.Put_Line("Starting Test:");
for Index in Test_Data'Range loop
declare
Item : Roman_Numeral renames Test_Data(Index).all;
Value : constant Natural := Eval(Item);
begin
Put( Item );
Ada.Text_IO.Put( ASCII.HT & "= ");
Ada.Text_IO.Put( Value'Img );
Ada.Text_IO.Put_Line( ASCII.HT & '[' &
PF( Value = Validation_Data(Index) )& ']');
end;
end loop;
Ada.Text_IO.Put_Line("Testing complete.");
End Test_Roman_Numerals;
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#C
|
C
|
#include <math.h>
#include <stdio.h>
double f(double x)
{
return x*x*x-3.0*x*x +2.0*x;
}
double secant( double xA, double xB, double(*f)(double) )
{
double e = 1.0e-12;
double fA, fB;
double d;
int i;
int limit = 50;
fA=(*f)(xA);
for (i=0; i<limit; i++) {
fB=(*f)(xB);
d = (xB - xA) / (fB - fA) * fB;
if (fabs(d) < e)
break;
xA = xB;
fA = fB;
xB -= d;
}
if (i==limit) {
printf("Function is not converging near (%7.4f,%7.4f).\n", xA,xB);
return -99.0;
}
return xB;
}
int main(int argc, char *argv[])
{
double step = 1.0e-2;
double e = 1.0e-12;
double x = -1.032; // just so we use secant method
double xx, value;
int s = (f(x)> 0.0);
while (x < 3.0) {
value = f(x);
if (fabs(value) < e) {
printf("Root found at x= %12.9f\n", x);
s = (f(x+.0001)>0.0);
}
else if ((value > 0.0) != s) {
xx = secant(x-step, x,&f);
if (xx != -99.0) // -99 meaning secand method failed
printf("Root found at x= %12.9f\n", xx);
else
printf("Root found near x= %7.4f\n", x);
s = (f(x+.0001)>0.0);
}
x += step;
}
return 0;
}
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
# rock/paper/scissors game #
# counts of the number of times the player has chosen each move #
# we initialise each to 1 so that the total isn't zero when we are #
# choosing the computer's first move (as in the Ada version) #
INT r count := 1;
INT p count := 1;
INT s count := 1;
# counts of how many games the player and computer have won #
INT player count := 0;
INT computer count := 0;
print( ( "rock/paper/scissors", newline, newline ) );
WHILE
CHAR player move;
# get the players move - r => rock, p => paper, s => scissors #
# q => quit #
WHILE
print( ( "Please enter your move (r/p/s) or q to quit: " ) );
read( ( player move, newline ) );
( player move /= "r"
AND player move /= "p"
AND player move /= "s"
AND player move /= "q"
)
DO
print( ( "Unrecognised move", newline ) )
OD;
# continue playing until the player chooses quit #
player move /= "q"
DO
# decide the computer's move based on the player's history #
CHAR computer move;
INT move count = r count + p count + s count;
# predict player will play rock if the random number #
# is in the range 0 .. rock / total #
# predict player will play paper if the random number #
# is in the range rock / total .. ( rock + paper ) / total #
# predict player will play scissors otherwise #
REAL r limit = r count / move count;
REAL p limit = r limit + ( p count / move count );
REAL random move = next random;
IF random move < r limit THEN
# we predict the player will choose rock - we choose paper #
computer move := "p"
ELIF random move < p limit THEN
# we predict the player will choose paper - we choose scissors #
computer move := "s"
ELSE
# we predict the player will choose scissors - we choose rock #
computer move := "r"
FI;
print( ( "You chose: " + player move, newline ) );
print( ( "I chose: " + computer move, newline ) );
IF player move = computer move THEN
# both players chose the same - draw #
print( ( "We draw", newline ) )
ELSE
# players chose different moves - there is a winner #
IF ( player move = "r" AND computer move = "s" )
OR ( player move = "p" AND computer move = "r" )
OR ( player move = "s" AND computer move = "p" )
THEN
player count +:= 1;
print( ( "You win", newline ) )
ELSE
computer count +:= 1;
print( ( "I win", newline ) )
FI;
print( ( "You won: "
, whole( player count , 0 )
, ", I won: "
, whole( computer count, 0 )
, newline
)
)
FI;
IF player move = "r" THEN
# player chose rock #
r count +:= 1
ELIF player move = "p" THEN
# player chose paper #
p count +:= 1
ELSE
# player chose scissors #
s count +:= 1
FI
OD;
print( ( "Thanks for a most enjoyable game", newline ) )
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.
|
#CoffeeScript
|
CoffeeScript
|
encode = (str) ->
str.replace /(.)\1*/g, (w) ->
w[0] + w.length
decode = (str) ->
str.replace /(.)(\d+)/g, (m,w,n) ->
new Array(+n+1).join(w)
console.log s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
console.log encode s
console.log decode encode s
|
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.
|
#FutureBasic
|
FutureBasic
|
window 1, @"Roots of Unity", (0,0,1050,200)
long n, root
double real, imag
for n = 2 to 7
print n;":" ;
for root = 0 to n-1
real = cos( 2 * pi * root / n)
imag = sin( 2 * pi * root / n)
print using "-##.#####"; real;using "-##.#####"; imag; "i";
if root != n-1 then print ",";
next
print
next
HandleEvents
|
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.
|
#GAP
|
GAP
|
roots := n -> List([0 .. n-1], k -> E(n)^k);
r:=roots(7);
# [ 1, E(7), E(7)^2, E(7)^3, E(7)^4, E(7)^5, E(7)^6 ]
List(r, x -> x^7);
# [ 1, 1, 1, 1, 1, 1, 1 ]
|
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.
|
#Objeck
|
Objeck
|
use Web.HTTP;
use Query.RegEx;
use Collection.Generic;
class Program {
function : Main(args : String[]) ~ Nil {
master_tasks := ProcessTasks(["100_doors", "99_bottles_of_beer", "Filter", "Array_length", "Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"]);
"---"->PrintLine();
PrintTasks(master_tasks);
}
function : ProcessTasks(tasks : String[]) ~ MultiMap<String, String> {
master_tasks := MultiMap->New()<String, String>;
each(i : tasks) {
task := tasks[i];
"Processing '{$task}'..."->PrintLine();
matches := ProcessTask(task);
langs := matches->GetKeys()<String>;
each(j : langs) {
master_tasks->Insert(langs->Get(j), task);
};
};
return master_tasks;
}
function : ProcessTask(task : String) ~ Set<String> {
langs := Set->New()<String>;
header_regex := RegEx->New("==\\{\\{header\\|(\\w|/|-|_)+\\}\\}==");
lang_regex := RegEx->New("<(\\s)*lang(\\s)*>");
url := "http://rosettacode.org/mw/index.php?action=raw&title={$task}";
lines := HttpClient->New()->GetAll(url)->Split("\n");
last_header : String;
each(i : lines) {
line := lines[i];
# get header
header := header_regex->FindFirst(line);
if(<>header->IsEmpty()) {
last_header := HeaderName(header);
};
# get language
lang := lang_regex->FindFirst(line);
if(lang->Size() > 0) {
if(last_header <> Nil) {
langs->Insert("{$last_header}");
}
else {
langs->Insert("no language");
};
};
};
return langs;
}
function : HeaderName(lang_str : String) ~ String {
start := lang_str->Find('|');
if(start > -1) {
start += 1;
end := lang_str->Find(start, '}');
return lang_str->SubString(start, end - start);
};
return "";
}
function : PrintTasks(tasks : MultiMap<String, String>) ~ Nil {
keys := tasks->GetKeys()<String>;
each(i : keys) {
buffer := "";
key := keys->Get(i);
values := tasks->Find(key)<String>;
count := values->Size();
buffer += "{$count} in {$key} (";
each(j : values) {
value := values->Get(j);
buffer += "[[{$value}]]";
if(j + 1 < values->Size()) {
buffer += ", ";
};
};
buffer += ")";
buffer->PrintLine();
};
}
}
|
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.
|
#GAP
|
GAP
|
QuadraticRoots := function(a, b, c)
local d;
d := Sqrt(b*b - 4*a*c);
return [ (-b+d)/(2*a), (-b-d)/(2*a) ];
end;
# Hint : E(12) is a 12th primitive root of 1
QuadraticRoots(2, 2, -1);
# [ 1/2*E(12)^4-1/2*E(12)^7+1/2*E(12)^8+1/2*E(12)^11,
# 1/2*E(12)^4+1/2*E(12)^7+1/2*E(12)^8-1/2*E(12)^11 ]
# This works also with floating-point numbers
QuadraticRoots(2.0, 2.0, -1.0);
# [ 0.366025, -1.36603 ]
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
func qr(a, b, c float64) ([]float64, []complex128) {
d := b*b-4*a*c
switch {
case d == 0:
// single root
return []float64{-b/(2*a)}, nil
case d > 0:
// two real roots
if b < 0 {
d = math.Sqrt(d)-b
} else {
d = -math.Sqrt(d)-b
}
return []float64{d/(2*a), (2*c)/d}, nil
case d < 0:
// two complex roots
den := 1/(2*a)
t1 := complex(-b*den, 0)
t2 := complex(0, math.Sqrt(-d)*den)
return nil, []complex128{t1+t2, t1-t2}
}
// otherwise d overflowed or a coefficient was NAN
return []float64{d}, nil
}
func test(a, b, c float64) {
fmt.Print("coefficients: ", a, b, c, " -> ")
r, i := qr(a, b, c)
switch len(r) {
case 1:
fmt.Println("one real root:", r[0])
case 2:
fmt.Println("two real roots:", r[0], r[1])
default:
fmt.Println("two complex roots:", i[0], i[1])
}
}
func main() {
for _, c := range [][3]float64{
{1, -2, 1},
{1, 0, 1},
{1, -10, 1},
{1, -1000, 1},
{1, -1e9, 1},
} {
test(c[0], c[1], c[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
|
#Burlesque
|
Burlesque
|
blsq ) "HELLO WORLD"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww
"URYYB JBEYQ"
blsq ) "URYYB JBEYQ"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww
"HELLO WORLD"
|
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 }
|
#Maxima
|
Maxima
|
/* Here is how to solve a differential equation */
'diff(y, x) = x * sqrt(y);
ode2(%, y, x);
ic1(%, x = 0, y = 1);
factor(solve(%, y)); /* [y = (x^2 + 4)^2 / 16] */
/* The Runge-Kutta solver is builtin */
load(dynamics)$
sol: rk(t * sqrt(y), y, 1, [t, 0, 10, 1.0])$
plot2d([discrete, sol])$
/* An implementation of RK4 for one equation */
rk4(f, x0, y0, x1, n) := block([h, x, y, vx, vy, k1, k2, k3, k4],
h: bfloat((x1 - x0) / (n - 1)),
x: x0,
y: y0,
vx: makelist(0, n + 1),
vy: makelist(0, n + 1),
vx[1]: x0,
vy[1]: y0,
for i from 1 thru n do (
k1: bfloat(h * f(x, y)),
k2: bfloat(h * f(x + h / 2, y + k1 / 2)),
k3: bfloat(h * f(x + h / 2, y + k2 / 2)),
k4: bfloat(h * f(x + h, y + k3)),
vy[i + 1]: y: y + (k1 + 2 * k2 + 2 * k3 + k4) / 6,
vx[i + 1]: x: x + h
),
[vx, vy]
)$
[x, y]: rk4(lambda([x, y], x * sqrt(y)), 0, 1, 10, 101)$
plot2d([discrete, x, y])$
s: map(lambda([x], (x^2 + 4)^2 / 16), x)$
for i from 1 step 10 thru 101 do print(x[i], " ", y[i], " ", y[i] - s[i]);
|
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
|
#Python
|
Python
|
"""
Given the name of a language on Rosetta Code,
finds all tasks which are not implemented in that language.
"""
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
url: str,
api_path: str) -> Iterator[str]:
"""Yields all unimplemented tasks for a specified language"""
site = mwclient.Site(url, path=api_path)
all_tasks = site.categories['Programming Tasks']
language_tasks = site.categories[language]
name = attrgetter('name')
all_tasks_names = map(name, all_tasks)
language_tasks_names = set(map(name, language_tasks))
for task in all_tasks_names:
if task not in language_tasks_names:
yield task
if __name__ == '__main__':
tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)
print(*tasks, sep='\n')
|
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.
|
#OCaml
|
OCaml
|
(** This module is a very simple parsing library for S-expressions. *)
(* Copyright (C) 2009 Florent Monnier, released under MIT license. *)
type sexpr = Atom of string | Expr of sexpr list
(** the type of S-expressions *)
val parse_string : string -> sexpr list
(** parse from a string *)
val parse_ic : in_channel -> sexpr list
(** parse from an input channel *)
val parse_file : string -> sexpr list
(** parse from a file *)
val parse : (unit -> char option) -> sexpr list
(** parse from a custom function, [None] indicates the end of the flux *)
val print_sexpr : sexpr list -> unit
(** a dump function for the type [sexpr] *)
val print_sexpr_indent : sexpr list -> unit
(** same than [print_sexpr] but with indentation *)
val string_of_sexpr : sexpr list -> string
(** convert an expression of type [sexpr] into a string *)
val string_of_sexpr_indent : sexpr list -> string
(** same than [string_of_sexpr] but with indentation *)
|
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.
|
#OCaml
|
OCaml
|
(* Task : RPG_attributes_generator *)
(*
A programmatic solution to generating character attributes for an RPG
*)
(* Generates random whole values between 1 and 6. *)
let rand_die () : int = Random.int 6
(* Generates 4 random values and saves the sum of the 3 largest *)
let rand_attr () : int =
let four_rolls = [rand_die (); rand_die (); rand_die (); rand_die ()]
|> List.sort compare in
let three_best = List.tl four_rolls in
List.fold_left (+) 0 three_best
(* Generates a total of 6 values this way. *)
let rand_set () : int list=
[rand_attr (); rand_attr (); rand_attr ();
rand_attr (); rand_attr (); rand_attr ()]
(* Verifies conditions: total >= 75, at least 2 >= 15 *)
let rec valid_set () : int list=
let s = rand_set () in
let above_15 = List.fold_left (fun acc el -> if el >= 15 then acc + 1 else acc) 0 s in
let total = List.fold_left (+) 0 s in
if above_15 >= 2 && total >= 75
then s
else valid_set ()
(*** Output ***)
let _ =
let s = valid_set () in
List.iter (fun i -> print_int i; print_string ", ") s
|
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
|
#Scilab
|
Scilab
|
function a = sieve(n)
a = ~zeros(n, 1)
a(1) = %f
for i = 1:n
if a(i)
j = i*i
if j > n
return
end
a(j:i:n) = %f
end
end
endfunction
find(sieve(100))
// [2 3 5 ... 97]
sum(sieve(1000))
// 168, the number of primes below 1000
|
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
|
Rosetta Code/Count examples
|
task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Maple
|
Maple
|
ConvertUTF8 := proc( str )
local i, tempstring, uniindex;
try
tempstring := str;
uniindex := [StringTools:-SearchAll("\u",str)];
if uniindex <> [] then
for i in uniindex do
tempstring := StringTools:-Substitute(tempstring, str[i..i+5], UTF8:-unicode(str[i+2..i+5]));
end do:
end if;
return tempstring;
catch:
return str;
end try;
end proc:
print_examples := proc(lst)
local task, count, url, headers, item;
for task in lst do
count := 0:
url := cat("http://www.rosettacode.org/mw/index.php?title=", StringTools:-Encode(StringTools:-SubstituteAll(task["title"], " ", "_"), 'percent'), "&action=raw"):
headers := [StringTools:-SearchAll("=={{header|",URL:-Get(url))]:
for item in headers do
count++:
end do:
printf("%s has %d examples\n",ConvertUTF8(task["title"]), count);
end do:
end proc:
x := JSON:-ParseFile("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=20&format=json"):
print_examples(x["query"]["categorymembers"]);
while(assigned(x["continue"]["cmcontinue"])) do
continue := x["continue"]["cmcontinue"]:
more_tasks:= cat("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=20&format=json", "&continue=", x["continue"]["continue"], "&cmcontinue=", x["continue"]["cmcontinue"]):
x := JSON:-ParseFile(more_tasks):
print_examples(x["query"]["categorymembers"]);
end do:
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
TaskList = Flatten[
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]&
~Map~ StringReplace[TaskList, " " -> "_"]
|
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
|
#Lang5
|
Lang5
|
: haystack(*) ['rosetta 'code 'search 'a 'list 'lang5 'code] find-index ;
: find-index
2dup eq length iota swap select swap drop
length if swap drop
else drop " is not in haystack" 2 compress "" join
then ;
: ==>search apply ;
['hello 'code] 'haystack ==>search .
|
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.
|
#Lasso
|
Lasso
|
<pre><code>[
sys_listtraits !>> 'xml_tree_trait' ? include('xml_tree.lasso')
local(lang = array)
local(f = curl('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000')->result->asString)
local(ff) = xml_tree(#f)
local(lis = #ff->body->div(3)->div(3)->div(3)->div->ul->getnodes)
with li in #lis do => {
local(title = #li->a->attribute('title'))
#title->removeLeading('Category:')
local(num = #li->asString->split('(')->last)
#num->removeTrailing(')')
#num->removeTrailing('members')
#num->removeTrailing('member')
#num->trim
#num = integer(#num)
#lang->insert(#title = #num)
}
local(c = 1)
with l in #lang
order by #l->second descending
do => {^
#c++
'. '+#l->second + ' - ' + #l->first+'\r'
^}
]</code></pre>
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Action.21
|
Action!
|
DEFINE PTR="CARD"
CARD ARRAY arabic=[1000 900 500 400 100 90 50 40 10 9 5 4 1]
PTR ARRAY roman(13)
PROC InitRoman()
roman(0)="M" roman(1)="CM" roman(2)="D" roman(3)="CD"
roman(4)="C" roman(5)="XC" roman(6)="L" roman(7)="XL"
roman(8)="X" roman(9)="IX" roman(10)="V" roman(11)="IV" roman(12)="I"
RETURN
PROC EncodeRomanNumber(CARD n CHAR ARRAY res)
BYTE i,len
CHAR ARRAY tmp
res(0)=0 len=0
FOR i=0 TO 12
DO
WHILE arabic(i)<=n
DO
tmp=roman(i)
SAssign(res,tmp,len+1,len+1+tmp(0))
len==+tmp(0)
n==-arabic(i)
OD
OD
res(0)=len
RETURN
PROC Main()
CARD ARRAY data=[1990 2008 5555 1666 3888 3999]
BYTE i
CHAR ARRAY r(20)
InitRoman()
FOR i=0 TO 5
DO
EncodeRomanNumber(data(i),r)
PrintF("%U=%S%E",data(i),r)
OD
RETURN
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#ALGOL_68
|
ALGOL 68
|
PROC roman to int = (STRING roman) INT:
BEGIN
PROC roman digit value = (CHAR roman digit) INT:
(roman digit = "M" | 1000 |:
roman digit = "D" | 500 |:
roman digit = "C" | 100 |:
roman digit = "L" | 50 |:
roman digit = "X" | 10 |:
roman digit = "V" | 5 |:
roman digit = "I" | 1);
INT result := 0, previous value := 0, run := 0;
FOR i FROM LWB roman TO UPB roman
DO
INT value = roman digit value(roman[i]);
IF previous value = value THEN
run +:= value
ELSE
IF previous value < value THEN
result -:= run
ELSE
result +:= run
FI;
run := previous value := value
FI
OD;
result +:= run
END;
MODE TEST = STRUCT (STRING input, INT expected output);
[] TEST roman test = (
("MMXI", 2011), ("MIM", 1999),
("MCMLVI", 1956), ("MDCLXVI", 1666),
("XXCIII", 83), ("LXXIIX", 78),
("IIIIX", 6)
);
print(("Test input Value Got", newline, "--------------------------", newline));
FOR i FROM LWB roman test TO UPB roman test
DO
INT output = roman to int(input OF roman test[i]);
printf(($g, n (12 - UPB input OF roman test[i]) x$, input OF roman test[i]));
printf(($g(5), 1x, g(5), 1x$, expected output OF roman test[i], output));
printf(($b("ok", "not ok"), 1l$, output = expected output OF roman test[i]))
OD
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#C.23
|
C#
|
using System;
class Program
{
public static void Main(string[] args)
{
Func<double, double> f = x => { return x * x * x - 3 * x * x + 2 * x; };
double step = 0.001; // Smaller step values produce more accurate and precise results
double start = -1;
double stop = 3;
double value = f(start);
int sign = (value > 0) ? 1 : 0;
// Check for root at start
if (value == 0)
Console.WriteLine("Root found at {0}", start);
for (var x = start + step; x <= stop; x += step)
{
value = f(x);
if (((value > 0) ? 1 : 0) != sign)
// We passed a root
Console.WriteLine("Root found near {0}", x);
else if (value == 0)
// We hit a root
Console.WriteLine("Root found at {0}", x);
// Update our sign
sign = (value > 0) ? 1 : 0;
}
}
}
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#AutoHotkey
|
AutoHotkey
|
DllCall("AllocConsole")
Write("Welcome to Rock-Paper-Scissors`nMake a choice: ")
cR := cP := cS := 0 ; user choice count
userChoice := Read()
Write("My choice: " . cpuChoice := MakeChoice(1, 1, 1))
Loop
{
Write(DecideWinner(userChoice, cpuChoice) . "`nMake A Choice: ")
cR += SubStr(userChoice, 1, 1) = "r", cP += InStr(userChoice, "P"), cS += InStr(userChoice, "S")
userChoice := Read()
Write("My Choice: " . cpuChoice := MakeChoice(cR, cP, cS))
}
MakeChoice(cR, cP, cS){
; parameters are number of times user has chosen each item
total := cR + cP + cS
Random, rand, 0.0, 1.0
if (rand >= 0 and rand <= cR / total)
return "Paper"
else if (rand > cR / total and rand <= (cR + cP) / total)
return "Scissors"
else
return "Rock"
}
DecideWinner(user, cpu){
user := SubStr(user, 1, 1), cpu := SubStr(cpu, 1, 1)
if (user = cpu)
return "`nTie!"
else if (user = "r" and cpu = "s") or (user = "p" and cpu = "r") or (user = "s" and cpu = "p")
return "`nYou Win!"
else
return "`nI Win!"
}
Read(){
FileReadLine, a, CONIN$, 1
return a
}
Write(txt){
FileAppend, % txt, CONOUT$
}
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun group-similar (sequence &key (test 'eql))
(loop for x in (rest sequence)
with temp = (subseq sequence 0 1)
if (funcall test (first temp) x)
do (push x temp)
else
collect temp
and do (setf temp (list x))))
(defun run-length-encode (sequence)
(mapcar (lambda (group) (list (first group) (length group)))
(group-similar (coerce sequence 'list))))
(defun run-length-decode (sequence)
(reduce (lambda (s1 s2) (concatenate 'simple-string s1 s2))
(mapcar (lambda (elem)
(make-string (second elem)
:initial-element
(first elem)))
sequence)))
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
(run-length-decode '((#\W 12) (#\B 1) (#\W 12) (#\B 3) (#\W 24) (#\B 1)))
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
|
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.
|
#Groovy
|
Groovy
|
/** The following closure creates a list of n evenly-spaced points around the unit circle,
* useful in FFT calculations, among other things */
def rootsOfUnity = { n ->
(0..<n).collect {
Complex.fromPolar(1, 2 * Math.PI * it / n)
}
}
|
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.
|
#Perl
|
Perl
|
my $lang = 'no language';
my $total = 0;
my %blanks = ();
while (<>) {
if (m/<lang>/) {
if (exists $blanks{lc $lang}) {
$blanks{lc $lang}++
} else {
$blanks{lc $lang} = 1
}
$total++
} elsif (m/==\s*\{\{\s*header\s*\|\s*([^\s\}]+)\s*\}\}\s*==/) {
$lang = lc $1
}
}
if ($total) {
print "$total bare language tag" . ($total > 1 ? 's' : '') . ".\n\n";
while ( my ($k, $v) = each(%blanks) ) {
print "$k in $v\n"
}
}
|
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.
|
#Haskell
|
Haskell
|
import Data.Complex (Complex, realPart)
type CD = Complex Double
quadraticRoots :: (CD, CD, CD) -> (CD, CD)
quadraticRoots (a, b, c)
| 0 < realPart b =
( (2 * c) / (- b - d),
(- b - d) / (2 * a)
)
| otherwise =
( (- b + d) / (2 * a),
(2 * c) / (- b + d)
)
where
d = sqrt $ b ^ 2 - 4 * a * c
main :: IO ()
main =
mapM_
(print . quadraticRoots)
[ (3, 4, 4 / 3),
(3, 2, -1),
(3, 2, 1),
(1, -10e5, 1),
(1, -10e9, 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
|
#C
|
C
|
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static char rot13_table[UCHAR_MAX + 1];
static void init_rot13_table(void) {
static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz";
for (int ch = '\0'; ch <= UCHAR_MAX; ch++) {
rot13_table[ch] = ch;
}
for (const unsigned char *p = upper; p[13] != '\0'; p++) {
rot13_table[p[0]] = p[13];
rot13_table[p[13]] = p[0];
}
for (const unsigned char *p = lower; p[13] != '\0'; p++) {
rot13_table[p[0]] = p[13];
rot13_table[p[13]] = p[0];
}
}
static void rot13_file(FILE *fp)
{
int ch;
while ((ch = fgetc(fp)) != EOF) {
fputc(rot13_table[ch], stdout);
}
}
int main(int argc, char *argv[])
{
init_rot13_table();
if (argc > 1) {
for (int i = 1; i < argc; i++) {
FILE *fp = fopen(argv[i], "r");
if (fp == NULL) {
perror(argv[i]);
return EXIT_FAILURE;
}
rot13_file(fp);
fclose(fp);
}
} else {
rot13_file(stdin);
}
return EXIT_SUCCESS;
}
|
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 }
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
ПП 38 П1 ПП 30 П2 ПП 35 П3 2
* ПП 30 ИП2 ИП3 + 2 * + ИП1
+ 3 / ИП7 + П7 П8 С/П БП 00
ИП6 ИП5 + П6 <-> ИП7 + П8
ИП8 КвКор ИП6 *
ИП5 * В/О
|
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 }
|
#Nim
|
Nim
|
import math
proc fn(t, y: float): float =
result = t * math.sqrt(y)
proc solution(t: float): float =
result = (t^2 + 4)^2 / 16
proc rk(start, stop, step: float) =
let nsteps = int(round((stop - start) / step)) + 1
let delta = (stop - start) / float(nsteps - 1)
var cur_y = 1.0
for i in 0..(nsteps - 1):
let cur_t = start + delta * float(i)
if abs(cur_t - math.round(cur_t)) < 1e-5:
echo "y(", cur_t, ") = ", cur_y, ", error = ", solution(cur_t) - cur_y
let dy1 = step * fn(cur_t, cur_y)
let dy2 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy1)
let dy3 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy2)
let dy4 = step * fn(cur_t + step, cur_y + dy3)
import math, strformat
proc fn(t, y: float): float =
result = t * math.sqrt(y)
proc solution(t: float): float =
result = (t^2 + 4)^2 / 16
proc rk(start, stop, step: float) =
let nsteps = int(round((stop - start) / step)) + 1
let delta = (stop - start) / float(nsteps - 1)
var cur_y = 1.0
for i in 0..<nsteps:
let cur_t = start + delta * float(i)
if abs(cur_t - math.round(cur_t)) < 1e-5:
echo &"y({cur_t}) = {cur_y}, error = {solution(cur_t) - cur_y}"
let dy1 = step * fn(cur_t, cur_y)
let dy2 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy1)
let dy3 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy2)
let dy4 = step * fn(cur_t + step, cur_y + dy3)
cur_y += (dy1 + 2 * (dy2 + dy3) + dy4) / 6
rk(start = 0, stop = 10, step = 0.1)
cur_y += (dy1 + 2.0 * (dy2 + dy3) + dy4)
|
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
|
#R
|
R
|
library(XML)
find.unimplemented.tasks <- function(lang="R"){
PT <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml",sep="") )
PT.nodes <- getNodeSet(PT,"//cm")
PT.titles = as.character( sapply(PT.nodes, xmlGetAttr, "title") )
language <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:",
lang, "&cmlimit=500&format=xml",sep="") )
lang.nodes <- getNodeSet(language,"//cm")
lang.titles = as.character( sapply(lang.nodes, xmlGetAttr, "title") )
unimplemented <- setdiff(PT.titles, lang.titles)
unimplemented
}
# Usage
find.unimplemented.tasks(lang="Python")
langs <- c("R","python","perl")
sapply(langs, find.unimplemented.tasks) # fetching data for multiple languages
|
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
|
#Racket
|
Racket
|
#lang racket
(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref]))
(define (RC-get verb params)
((compose1 get-pure-port string->url format)
"http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params)))
(define (get-category catname)
(let loop ([c #f])
(define t
((compose1 read-json RC-get) 'api
`([action . "query"] [format . "json"]
[list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)]
[cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"])))
(define (c-m key) (ref (ref t key '()) 'categorymembers #f))
(append (for/list ([page (c-m 'query)]) (ref page 'title))
(cond [(c-m 'query-continue) => loop] [else '()]))))
;; The above is the required "library" code, same as the "Rosetta
;; Code/Count" entry
(define (show-unimplemented lang)
(for-each displayln (remove* (get-category lang)
(get-category 'Programming_Tasks))))
(show-unimplemented 'Racket) ; see all of the Racket entries
|
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.
|
#Perl
|
Perl
|
#!/usr/bin/perl -w
use strict;
use warnings;
sub sexpr
{
my @stack = ([]);
local $_ = $_[0];
while (m{
\G # start match right at the end of the previous one
\s*+ # skip whitespaces
# now try to match any of possible tokens in THIS order:
(?<lparen>\() |
(?<rparen>\)) |
(?<FLOAT>[0-9]*+\.[0-9]*+) |
(?<INT>[0-9]++) |
(?:"(?<STRING>([^\"\\]|\\.)*+)") |
(?<IDENTIFIER>[^\s()]++)
# Flags:
# g = match the same string repeatedly
# m = ^ and $ match at \n
# s = dot and \s matches \n
# x = allow comments within regex
}gmsx)
{
die "match error" if 0+(keys %+) != 1;
my $token = (keys %+)[0];
my $val = $+{$token};
if ($token eq 'lparen') {
my $a = [];
push @{$stack[$#stack]}, $a;
push @stack, $a;
} elsif ($token eq 'rparen') {
pop @stack;
} else {
push @{$stack[$#stack]}, bless \$val, $token;
}
}
return $stack[0]->[0];
}
sub quote
{ (local $_ = $_[0]) =~ /[\s\"\(\)]/s ? do{s/\"/\\\"/gs; qq{"$_"}} : $_; }
sub sexpr2txt
{
qq{(@{[ map {
ref($_) eq '' ? quote($_) :
ref($_) eq 'STRING' ? quote($$_) :
ref($_) eq 'ARRAY' ? sexpr2txt($_) : $$_
} @{$_[0]} ]})}
}
|
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.
|
#Pascal
|
Pascal
|
program attributes;
var
total, roll,score, count: integer;
atribs : array [1..6] of integer;
begin
randomize; {Initalise the random number genertor}
repeat
count:=0;
total:=0;
for score :=1 to 6 do begin
{roll:=random(18)+1; produce a number up to 18, pretty much the same results}
for diceroll:=1 to 4 do dice[diceroll]:=random(6)+1; {roll 4 six sided die}
{find lowest rolled dice. If we roll two or more equal low rolls then we
eliminate the first of them, change '<' to '<=' to eliminate last low die}
lowroll:=7;
lowdie:=0;
for diceroll:=1 to 4 do if (dice[diceroll] < lowroll) then begin
lowroll := dice[diceroll];
lowdie := diceroll;
end;
{add up higest three dice}
roll:=0;
for diceroll:=1 to 4 do if (diceroll <> lowdie) then roll := roll + dice[diceroll];
atribs[score]:=roll;
total := total + roll;
if (roll>15) then count:=count+1;
end;
until ((total>74) and (count>1)); {this evens out different rolling methods }
{ Prettily print the attributes out }
writeln('Attributes :');
for count:=1 to 6 do
writeln(count,'.......',atribs[count]:2);
writeln(' ---');
writeln('Total ',total:3);
writeln(' ---');
end.
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Scratch
|
Scratch
|
when clicked
broadcast: fill list with zero (0) and wait
broadcast: put one (1) in list of multiples and wait
broadcast: fill primes where zero (0 in list
when I receive: fill list with zero (0)
delete all of primes
delete all of list
set i to 0
set maximum to 25
repeat maximum
add 0 to list
change i by 1
{end repeat}
when I receive: put ones (1) in list of multiples
set S to sqrt of maximum
set i to 2
set k to 0
repeat S
change J by 1
set i to 2
repeat until i > 100
if not (i = J) then
if item i of list = 0 then
set m to (i mod J)
if (m = 0) then
replace item i of list with 1
{end repeat until}
change i by 1
set k to 1
delete all of primes
{end repeat}
set J to 1
when I receive: fill primes where zeros (0) in list
repeat maximum
if (item k of list) = 0 then
add k to primes
set k to (k + 1)
{end repeat}
|
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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function c = count_examples(url)
c = 0;
[s, success] = urlread (url);
if ~success, return; end;
c = length(strfind(s,'<h2><span class='));
end;
% script
s = urlread ('http://rosettacode.org/wiki/Category:Programming_Tasks');
pat = '<li><a href="/wiki/';
ix = strfind(s,pat)+length(pat)-6;
for k = 1:length(ix);
% look through all tasks
e = find(s(ix(k):end)==34,1)-2;
t = s(ix(k)+[0:e]); % task
c = count_examples(['http://rosettacode.org',t]);
printf('Task "%s" has %i examples.\n',t(7:end), c);
end;
|
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
|
#Lasso
|
Lasso
|
local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')
#haystack->findindex('Bush')->first // 5
#haystack->findindex('Bush')->last // 8
protect => {^
handle_error => {^ error_msg ^}
fail_if(not #haystack->findindex('Washington')->first,'Washington is not in haystack.')
^}
|
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
|
Rosetta Code/Rank languages by popularity
|
Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,540 entries) Phix
Rank: 2 (1,531 entries) Wren
Rank: 3 (1,507 entries) Julia
Rank: 4 (1,494 entries) Go
Rank: 5 (1,488 entries) Raku
Rank: 6 (1,448 entries) Perl
Rank: 7 (1,402 entries) Nim
Rank: 8 (1,382 entries) Python
Rank: 9 (1,204 entries) C
Rank: 10 (1,152 entries) REXX
...
Notes
Each language typically demonstrates one or two methods of accessing the data:
with web scraping (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)
with the API method (examples below for Awk, Perl, Ruby, Tcl, etc).
The scraping and API solutions can be separate subsections, see the Tcl example.
Filtering wrong results is optional. You can check against Special:MostLinkedCategories (if using web scraping)
If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.
A complete ranked listing of all 813 languages (from the REXX example) is included here ──► output from the REXX program.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module RankLanguages {
Const Part1$="<a href="+""""+ "/wiki/Category", Part2$="member"
Const langHttp$="http://rosettacode.org/wiki/Category:Programming_Languages"
Const categoriesHttp$="http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
Def long m, i,j, tasks, counter, limit, T, t1
Def string LastLang$, job$
Document final$, languages$, categories$
httpGet$=lambda$ (url$, timeout=1000)->{
Declare htmldoc "Msxml2.ServerXMLHTTP"
With htmldoc , "readyState" as ready
Report "Download:"+url$
Method htmldoc "open","get", url$, True
Method htmldoc "send"
Profiler
While Ready<>4 {
Wait 20
Print Over format$("Wait: {0:3} sec", timecount/1000)
If timecount>timeout then Exit
}
If ready=4 Then With htmldoc, "responseText" as ready$ : =ready$
Declare htmldoc Nothing
print
}
languages$=httpGet$(langHttp$, 30000)
If Doc.Len(languages$)=0 then Error "File download failed (languages)"
Inventory Lang
m=Paragraph(languages$, 0)
If Forward(languages$,m) then {
While m {
job$=Paragraph$(languages$,(m))
If Instr(job$, part1$) Else Continue
i = Instr(job$, "</a>")
If i Else Continue ' same as If i=0 Then Continue
j = i
i=Rinstr(job$, ">", -i)
If i Else Continue
LastLang$=MID$(job$, i+1, j-i-1)
if Instr(job$, "Category:"+lastlang$) then Append lang, lastlang$:=0 : Print Over format$("Languages: {0}", len(lang))
}
}
Print
Document categories$=httpGet$(categoriesHttp$, 30000)
If Doc.Len(categories$)=0 then Error "File download failed (categories)"
limit=Doc.Par(categories$)
If limit<Len(Lang) then Error "Invalid data"
Refresh
set slow
m=Paragraph(categories$, 0)
counter=0
If Forward(categories$,m) then {
While m {
job$=Paragraph$(categories$,(m))
counter++
Print Over format$("{0:2:-6}%", counter/limit*100)
i=Instr(job$, part2$)
If i Else Continue
i=Rinstr(job$, "(", -i)
If i Else Continue
tasks=Val(Filter$(Mid$(job$, i+1),","))
If tasks Else Continue
i=Rinstr(job$, "<", -i)
If i Else Continue
j = i
i=Rinstr(job$, ">", -i)
If i Else Continue
LastLang$=MID$(job$, i+1, j-i-1)
If Exist(Lang, LastLang$) Then {
Return Lang, LastLang$:=Lang(LastLang$)+tasks
}
}
}
Print
\\ this type of inventory can get same keys
\\ also has stable sort
Report "Make Inventory list by Task"
Inventory queue ByTask
t1=Len(Lang)
T=Each(Lang)
While T {
Append ByTask, Eval(T):=Eval$(T!)
Print Over format$("Complete: {0} of {1}", T^+1, t1 )
}
Print
Report "Sort by task (stable sort, sort keys as numbers)"
Sort descending ByTask as number
Report "Make List"
T=Each(ByTask)
final$="Sample output on "+Date$(Today, 1033, "long date")+{:
}
While T {
final$=format$("rank:{0::-4}. {1:-5} entries - {2}", T^+1, Eval$(T!), Eval$(T))+{
}
}
Report "Copy to Clipboard"
clipboard final$
\\ present to console with 3/4 fill lines then stop for space bar or mouse click to continue
Report final$
}
RankLanguages
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#ActionScript
|
ActionScript
|
function arabic2roman(num:Number):String {
var lookup:Object = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
var roman:String = "", i:String;
for (i in lookup) {
while (num >= lookup[i]) {
roman += i;
num -= lookup[i];
}
}
return roman;
}
trace("1990 in roman is " + arabic2roman(1990));
trace("2008 in roman is " + arabic2roman(2008));
trace("1666 in roman is " + arabic2roman(1666));
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#ALGOL_W
|
ALGOL W
|
begin
% decodes a roman numeral into an integer %
% there must be at least one blank after the numeral %
% This takes a lenient view on roman numbers so e.g. IIXX is 18 - see %
% the Discussion %
integer procedure romanToDecimal ( string(32) value roman ) ;
begin
integer decimal, rPos, currDigit, nextDigit, seqValue;
string(1) rDigit;
% the roman number is a sequence of sequences of roman digits %
% if the previous sequence is of higher value digits than the next, %
% the higher value is added to the overall value %
% if the previous seequence is of lower value, it is subtracted %
% e.g. MCMLXII %
% the sequences are M, C, M, X, II %
% M is added, C subtracted, M added, X added and II added %
% get the value of a sequence of roman digits %
integer procedure getSequence ;
if rDigit = " " then begin
% end of the number %
0
end
else begin
% have another sequence %
integer sValue;
sValue := 0;
while roman( rPos // 1 ) = rDigit do begin
sValue := sValue + currDigit;
rPos := rPos + 1;
end while_have_same_digit ;
% remember the next digit %
rDigit := roman( rPos // 1 );
% result is the sequence value %
sValue
end getSequence ;
% convert a roman digit into its decimal equivalent %
% an invalid digit will terminate the program, " " is 0 %
integer procedure getValue( string(1) value romanDigit ) ;
if romanDigit = "m" or romanDigit = "M" then 1000
else if romanDigit = "d" or romanDigit = "D" then 500
else if romanDigit = "c" or romanDigit = "C" then 100
else if romanDigit = "l" or romanDigit = "L" then 50
else if romanDigit = "x" or romanDigit = "X" then 10
else if romanDigit = "v" or romanDigit = "V" then 5
else if romanDigit = "i" or romanDigit = "I" then 1
else if romanDigit = " " then 0
else begin
write( s_w := 0, "Invalid roman digit: """, romanDigit, """" );
assert false;
0
end getValue ;
% get the first sequence %
decimal := 0;
rPos := 0;
rDigit := roman( rPos // 1 );
currDigit := getValue( rDigit );
seqValue := getSequence;
% handle the sequences %
while rDigit not = " " do begin
% have another sequence %
nextDigit := getValue( rDigit );
if currDigit < nextDigit
then % prev digit is lower % decimal := decimal - seqValue
else % prev digit is higher % decimal := decimal + seqValue
;
currDigit := nextDigit;
seqValue := getSequence;
end while_have_a_roman_digit ;
% add the final sequence %
decimal + seqValue
end roman ;
% test the romanToDecimal routine %
procedure testRoman ( string(32) value romanNumber ) ;
write( i_w := 5, romanNumber, romanToDecimal( romanNumber ) );
testRoman( "I" ); testRoman( "II" );
testRoman( "III" ); testRoman( "IV" );
testRoman( "V" ); testRoman( "VI" );
testRoman( "VII" ); testRoman( "VIII" );
testRoman( "IX" ); testRoman( "IIXX" );
testRoman( "XIX" ); testRoman( "XX" );
write( "..." );
testRoman( "MCMXC" );
testRoman( "MMVIII" );
testRoman( "MDCLXVI" );
end.
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#C.2B.2B
|
C++
|
#include <iostream>
double f(double x)
{
return (x*x*x - 3*x*x + 2*x);
}
int main()
{
double step = 0.001; // Smaller step values produce more accurate and precise results
double start = -1;
double stop = 3;
double value = f(start);
double sign = (value > 0);
// Check for root at start
if ( 0 == value )
std::cout << "Root found at " << start << std::endl;
for( double x = start + step;
x <= stop;
x += step )
{
value = f(x);
if ( ( value > 0 ) != sign )
// We passed a root
std::cout << "Root found near " << x << std::endl;
else if ( 0 == value )
// We hit a root
std::cout << "Root found at " << x << std::endl;
// Update our sign
sign = ( value > 0 );
}
}
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#AutoIt
|
AutoIt
|
RPS()
Func RPS()
Local $ai_Played_games[4]
$ai_Played_games[0] = 3
For $I = 1 To 3
$ai_Played_games[$I] = 1
Next
$RPS = GUICreate("Rock Paper Scissors", 338, 108, 292, 248)
$Rock = GUICtrlCreateButton("Rock", 8, 8, 113, 25, 131072)
$Paper = GUICtrlCreateButton("Paper", 8, 40, 113, 25, 131072)
$Scissors = GUICtrlCreateButton("Scissors", 8, 72, 113, 25, 131072)
$Label1 = GUICtrlCreateLabel("W:", 136, 8, 18, 17)
$Wins = GUICtrlCreateLabel("0", 160, 8, 36, 17)
$Label3 = GUICtrlCreateLabel("L:", 208, 8, 13, 17)
$Looses = GUICtrlCreateLabel("0", 224, 8, 36, 17)
$Label5 = GUICtrlCreateLabel("D:", 272, 8, 15, 17)
$Deuce = GUICtrlCreateLabel("0", 296, 8, 36, 17)
$Displaybutton = GUICtrlCreateButton("", 136, 48, 193, 49, 131072)
GUICtrlSetState($ai_Played_games, 128)
GUISetState(@SW_SHOW)
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case -3
Exit
Case $Rock
$Ret = _RPS_Eval(1, $ai_Played_games)
GUICtrlSetData($Displaybutton, $Ret)
If $Ret = "Deuce" Then
GUICtrlSetData($Deuce, Guictrlread($Deuce)+1)
Elseif $Ret = "You Loose" Then
GUICtrlSetData($Looses, Guictrlread($Looses)+1)
Elseif $Ret = "You Win" Then
GUICtrlSetData($Wins, Guictrlread($Wins)+1)
EndIf
Case $Paper
$Ret = _RPS_Eval(2, $ai_Played_games)
GUICtrlSetData($Displaybutton, $Ret)
If $Ret = "Deuce" Then
GUICtrlSetData($Deuce, Guictrlread($Deuce)+1)
Elseif $Ret = "You Loose" Then
GUICtrlSetData($Looses, Guictrlread($Looses)+1)
Elseif $Ret = "You Win" Then
GUICtrlSetData($Wins, Guictrlread($Wins)+1)
EndIf
Case $Scissors
$Ret = _RPS_Eval(3, $ai_Played_games)
GUICtrlSetData($Displaybutton, $Ret)
If $Ret = "Deuce" Then
GUICtrlSetData($Deuce, Guictrlread($Deuce)+1)
Elseif $Ret = "You Loose" Then
GUICtrlSetData($Looses, Guictrlread($Looses)+1)
Elseif $Ret = "You Win" Then
GUICtrlSetData($Wins, Guictrlread($Wins)+1)
EndIf
EndSwitch
WEnd
EndFunc ;==>RPS
Func _RPS_Eval($i_Player_Choose, $ai_Played_games)
Local $i_choice = 1
$i_rnd = Random(1, 1000, 1)
$i_choose_1 = ($ai_Played_games[1] / $ai_Played_games[0] * 1000)
$i_choose_2 = ($ai_Played_games[2] / $ai_Played_games[0] * 1000)
$i_choose_3 = ($ai_Played_games[3] / $ai_Played_games[0] * 1000)
If $i_rnd < $i_choose_1 Then
$i_choice = 2
ElseIf $i_rnd < $i_choose_1 + $i_choose_2 And $i_rnd > $i_choose_1 Then
$i_choice = 3
ElseIf $i_rnd < $i_choose_1 + $i_choose_2 + $i_choose_3 And $i_rnd > $i_choose_1 + $i_choose_2 Then
$i_choice = 1
EndIf
$ai_Played_games[0] += 1
If $i_Player_Choose = 1 Then
$ai_Played_games[1] += 1
If $i_choice = 1 Then Return "Deuce"
If $i_choice = 2 Then Return "You Loose"
If $i_choice = 3 Then Return "You Win"
ElseIf $i_Player_Choose = 2 Then
$ai_Played_games[2] += 1
If $i_choice = 2 Then Return "Deuce"
If $i_choice = 3 Then Return "You Loose"
If $i_choice = 1 Then Return "You Win"
ElseIf $i_Player_Choose = 3 Then
$ai_Played_games[3] += 1
If $i_choice = 3 Then Return "Deuce"
If $i_choice = 1 Then Return "You Loose"
If $i_choice = 2 Then Return "You Win"
EndIf
EndFunc ;==>_RPS_Eval
|
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.
|
#D
|
D
|
import std.algorithm, std.array;
alias encode = group;
auto decode(Group!("a == b", string) enc) {
return enc.map!(t => [t[0]].replicate(t[1])).join;
}
void main() {
immutable s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW" ~
"WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
assert(s.encode.decode.equal(s));
}
|
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.
|
#Haskell
|
Haskell
|
import Data.Complex (Complex, cis)
rootsOfUnity :: (Enum a, Floating a) => a -> [Complex a]
rootsOfUnity n =
[ cis (2 * pi * k / n)
| k <- [0 .. n - 1] ]
main :: IO ()
main = mapM_ print $ rootsOfUnity 3
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
roots(10)
end
procedure roots(n)
every n := 2 to 10 do
every writes(n | (str_rep((0 to (n-1)) * 2 * &pi / n)) | "\n")
end
procedure str_rep(k)
return " " || cos(k) || "+" || sin(k) || "i"
end
|
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.
|
#Phix
|
Phix
|
--
-- demo\rosetta\Find_bare_lang_tags.exw
-- ====================================
--
-- (Uses '&' instead of/as well as 'a', for everyone's sanity..)
-- Finds/counts no of "<l&ng>" as opposed to eg "<l&ng Phix>" tags.
-- Since downloading all the pages can be very slow, this uses a cache.
--
without js -- (fairly obviously this will never ever run in a browser!)
constant include_drafts = true,
sort_by_task = true,
sort_by_lang = not sort_by_task -- (one or t'other)
include rosettacode_cache.e -- see Rosetta_Code/Count_examples#Phix
constant {utf8,ansi} = columnize({{x"E28093","-"},
{x"E28099","'"},
{x"C3A8","e"},
{x"C3A9","e"},
{x"D09A","K"},
{x"D09C","M"}})
function utf8_clean(string s)
return substitute_all(s,utf8,ansi)
end function
function multi_lang(sequence s)
-- Convert eg {"Algol","Algol","C","C","C"} to "Algol[2],C[3]"
integer i = 1, j = 2
while i<length(s) do
if s[i]=s[j] then
while j<length(s) and s[i]=s[j+1] do j+=1 end while
s[i..j] = {sprintf("%s[%d]",{s[i],j-i+1})}
end if
i += 1
j = i+1
end while
return join(s,",")
end function
function multi_task(sequence s, tasks)
-- Similar to multi_lang() but with task[indexes]
integer i = 1, j = 2
while i<=length(s) do
integer si = s[i]
string tsi = html_clean(tasks[si])
if j<=length(s) and si=s[j] then
while j<length(s) and si=s[j+1] do j+=1 end while
s[i..j] = {sprintf("%s[%d]",{tsi,j-i+1})}
else
s[i] = tsi
end if
i += 1
j = i+1
end while
if length(s)>8 then s[4..-4] = {"..."} end if
return join(s,",")
end function
bool first = true
function find_bare_lang_tags()
if get_file_type("rc_cache")!=FILETYPE_DIRECTORY then
if not create_directory("rc_cache") then
crash("cannot create rc_cache directory")
end if
end if
-- note this lot use web scraping (as cribbed from a similar task) ...
sequence tasks = dewiki(open_category("Programming_Tasks"))
if include_drafts then
tasks &= dewiki(open_category("Draft_Programming_Tasks"))
tasks = sort(tasks)
end if
integer blt = find("Rosetta_Code/Find_bare_lang_tags",tasks) -- not this one!
tasks[blt..blt] = {}
-- ... whereas the individual tasks use the web api instead (3x smaller/faster)
integer total_count = 0,
lt = length(tasks),
kept = 0
progress("%d tasks found\n",{lt})
sequence task_langs = {},
task_counts = iff(sort_by_task?repeat(0,lt):{}),
task_things = iff(sort_by_task?repeat({},lt):{})
for i=1 to length(tasks) do
string ti = tasks[i],
url = sprintf("http://rosettacode.org/mw/index.php?title=%s&action=raw",{ti}),
contents = open_download(ti&".raw",url),
curr
integer count = 0, start = 1, header
while true do
start = match(`<l`&`ang>`,contents,start)
if start=0 then exit end if
-- look backward for the nearest header
header = rmatch(`{`&`{he`&`ader|`,contents,start)
if header=0 then
curr = "no language"
else
header += length(`{`&`{he`&`ader|`)
curr = utf8_clean(contents[header..match(`}}`,contents,header)-1])
end if
if sort_by_lang then
integer k = find(curr,task_langs)
if k=0 then
task_langs = append(task_langs,curr)
task_things = append(task_things,{i})
task_counts = append(task_counts,1)
else
task_things[k] = append(task_things[k],i)
task_counts[k] += 1
end if
else
task_things[i] = append(task_things[i],curr)
end if
count += 1
start += length(`<l`&`ang>`)
end while
if count!=0 then
if sort_by_task then
task_counts[i] = count
end if
kept += 1
end if
progress("%d tasks kept, %d to go\r",{kept,lt-i})
total_count += count
if get_key()=#1B then progress("escape keyed\n") exit end if
end for
curl_cleanup()
progress("%d tasks with bare lang tags\n",{kept})
sequence tags = custom_sort(task_counts,tagset(length(task_counts)))
for i=length(tags) to 1 by -1 do
integer ti = tags[i],
tc = task_counts[ti]
if tc=0 then exit end if
if sort_by_task then
progress("%s %d (%s)\n",{html_clean(tasks[ti]),tc,multi_lang(task_things[ti])})
else -- (sort_by_count)
progress("%s %d (%s)\n",{task_langs[ti],tc,multi_task(task_things[ti],tasks)})
end if
end for
return total_count
end function
progress("Total: %d\n",{find_bare_lang_tags()})
?"done"
{} = wait_key()
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
solve(1.0, -10.0e5, 1.0)
end
procedure solve(a,b,c)
d := sqrt(b*b - 4.0*a*c)
roots := if b < 0 then [r1 := (-b+d)/(2.0*a), c/(a*r1)]
else [r1 := (-b-d)/(2.0*a), c/(a*r1)]
write(a,"*x^2 + ",b,"*x + ",c," has roots ",roots[1]," and ",roots[2])
end
|
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
|
#C.23
|
C#
|
using System;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static char Rot13(char c)
{
if ('a' <= c && c <= 'm' || 'A' <= c && c <= 'M')
{
return (char)(c + 13);
}
if ('n' <= c && c <= 'z' || 'N' <= c && c <= 'Z')
{
return (char)(c - 13);
}
return c;
}
static string Rot13(string s)
{
return new string(s.Select(Rot13).ToArray());
}
static void Main(string[] args)
{
foreach (var file in args.Where(file => File.Exists(file)))
{
Console.WriteLine(Rot13(File.ReadAllText(file)));
}
if (!args.Any())
{
Console.WriteLine(Rot13(Console.In.ReadToEnd()));
}
}
}
|
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 }
|
#Objeck
|
Objeck
|
class RungeKuttaMethod {
function : Main(args : String[]) ~ Nil {
x0 := 0.0; x1 := 10.0; dx := .1;
n := 1 + (x1 - x0)/dx;
y := Float->New[n->As(Int)];
y[0] := 1;
for(i := 1; i < n; i++;) {
y[i] := Rk4(Rate(Float, Float) ~ Float, dx, x0 + dx * (i - 1), y[i-1]);
};
for(i := 0; i < n; i += 10;) {
x := x0 + dx * i;
y2 := (x * x / 4 + 1)->Power(2.0);
x_value := x->As(Int);
y_value := y[i];
rel_value := y_value/y2 - 1.0;
"y({$x_value})={$y_value}; error: {$rel_value}"->PrintLine();
};
}
function : native : Rk4(f : (Float, Float) ~ Float, dx : Float, x : Float, y : Float) ~ Float {
k1 := dx * f(x, y);
k2 := dx * f(x + dx / 2, y + k1 / 2);
k3 := dx * f(x + dx / 2, y + k2 / 2);
k4 := dx * f(x + dx, y + k3);
return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
}
function : native : Rate(x : Float, y : Float) ~ Float {
return x * y->SquareRoot();
}
}
|
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
|
#Raku
|
Raku
|
use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Sort::Naturally;
unit sub MAIN( Str :$lang = 'Raku' );
my $client = HTTP::UserAgent.new;
my $url = 'http://rosettacode.org/mw';
my @total;
my @impl;
@total.append: .&get-cat for 'Programming_Tasks', 'Draft_Programming_Tasks';
@impl = get-cat $lang;
say "Unimplemented tasks in $lang:";
.say for (@total (-) @impl).keys.sort: &naturally;
sub get-cat ($category) {
flat mediawiki-query(
$url, 'pages',
:generator<categorymembers>,
:gcmtitle("Category:$category"),
:gcmlimit<350>,
:rawcontinue(),
:prop<title>
).map({ .<title> });
}
sub mediawiki-query ($site, $type, *%query) {
my $url = "$site/api.php?" ~ uri-query-string(
:action<query>, :format<json>, :formatversion<2>, |%query);
my $continue = '';
gather loop {
my $response = $client.get("$url&$continue");
my $data = from-json($response.content);
take $_ for $data.<query>.{$type}.values;
$continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);
}
}
sub uri-query-string (*%fields) { %fields.map({ "{.key}={uri-escape .value}" }).join("&") }
|
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.
|
#Phix
|
Phix
|
with javascript_semantics
constant s_expr_str = """
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))"""
function skip_spaces(string s, integer sidx)
while sidx<=length(s) and find(s[sidx],{' ','\t','\r','\n'}) do sidx += 1 end while
return sidx
end function
function get_term(string s, integer sidx)
-- get a single quoted string, symbol, or number.
integer ch = s[sidx]
string res = ""
if ch='\"' then
res &= ch
while 1 do
sidx += 1
ch = s[sidx]
res &= ch
if ch='\\' then
sidx += 1
ch = s[sidx]
res &= ch
elsif ch='\"' then
sidx += 1
exit
end if
end while
else
integer asnumber = (ch>='0' and ch<='9')
while not find(ch,{')',' ','\t','\r','\n'}) do
res &= ch
sidx += 1
if sidx>length(s) then exit end if
ch = s[sidx]
end while
if asnumber then
sequence scanres = scanf(res,"%f")
if length(scanres)=1 then return {scanres[1][1],sidx} end if
-- error? (failed to parse number)
end if
end if
return {res,sidx}
end function
function parse_s_expr(string s, integer sidx)
integer ch = s[sidx]
sequence res = {}
object element
if ch!='(' then ?9/0 end if
sidx += 1
while 1 do
sidx = skip_spaces(s,sidx)
-- error? (if past end of string/missing ')')
ch = s[sidx]
if ch=')' then exit end if
if ch='(' then
{element,sidx} = parse_s_expr(s,sidx)
else
{element,sidx} = get_term(s,sidx)
end if
res = append(res,element)
end while
sidx = skip_spaces(s,sidx+1)
return {res,sidx}
end function
sequence s_expr
integer sidx
{s_expr,sidx} = parse_s_expr(s_expr_str,1)
if sidx<=length(s_expr_str) then
printf(1,"incomplete parse(\"%s\")\n",{s_expr_str[sidx..$]})
end if
puts(1,"\nThe string:\n")
?s_expr_str
puts(1,"\nDefault pretty printing:\n")
--?s_expr
pp(s_expr)
puts(1,"\nBespoke pretty printing:\n")
--ppEx(s_expr,{pp_Nest,1,pp_StrFmt,-1,pp_IntCh,false,pp_Brkt,"()"})
ppEx(s_expr,{pp_Nest,4,pp_StrFmt,-1,pp_IntCh,false,pp_Brkt,"()"})
|
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.
|
#Perl
|
Perl
|
use strict;
use List::Util 'sum';
my ($min_sum, $hero_attr_min, $hero_count_min) = <75 15 3>;
my @attr_names = <Str Int Wis Dex Con Cha>;
sub heroic { scalar grep { $_ >= $hero_attr_min } @_ }
sub roll_skip_lowest {
my($dice, $sides) = @_;
sum( (sort map { 1 + int rand($sides) } 1..$dice)[1..$dice-1] );
}
my @attr;
do {
@attr = map { roll_skip_lowest(6,4) } @attr_names;
} until sum(@attr) >= $min_sum and heroic(@attr) >= $hero_count_min;
printf "%s = %2d\n", $attr_names[$_], $attr[$_] for 0..$#attr;
printf "Sum = %d, with %d attributes >= $hero_attr_min\n", sum(@attr), heroic(@attr);
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func set of integer: eratosthenes (in integer: n) is func
result
var set of integer: sieve is EMPTY_SET;
local
var integer: i is 0;
var integer: j is 0;
begin
sieve := {2 .. n};
for i range 2 to sqrt(n) do
if i in sieve then
for j range i ** 2 to n step i do
excl(sieve, j);
end for;
end if;
end for;
end func;
const proc: main is func
begin
writeln(card(eratosthenes(10000000)));
end func;
|
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
|
#Nim
|
Nim
|
import httpclient, strutils, xmltree, xmlparser, cgi
proc count(s, sub: string): int =
var i = 0
while true:
i = s.find(sub, i)
if i < 0: break
inc i
inc result
const
mainSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
subSite = "http://www.rosettacode.org/mw/index.php?title=$#&action=raw"
var client = newHttpClient()
var sum = 0
for node in client.getContent(mainSite).parseXml().findAll("cm"):
let t = node.attr("title").replace(" ", "_")
let c = client.getContent(subSite % encodeUrl(t)).toLower().count("{{header|")
echo t.replace("_", " "), ": ", c, " examples."
inc sum, c
echo "\nTotal: ", sum, " examples."
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Liberty_BASIC
|
Liberty BASIC
|
haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.