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/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
|
#Io
|
Io
|
NotFound := Exception clone
List firstIndex := method(obj,
indexOf(obj) ifNil(NotFound raise)
)
List lastIndex := method(obj,
reverseForeach(i,v,
if(v == obj, return i)
)
NotFound raise
)
haystack := list("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
list("Washington","Bush") foreach(needle,
try(
write("firstIndex(\"",needle,"\"): ")
writeln(haystack firstIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
try(
write("lastIndex(\"",needle,"\"): ")
writeln(haystack lastIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
)
|
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.
|
#Haskell
|
Haskell
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import Network.HTTP.Base (urlEncode)
import Network.HTTP.Conduit (simpleHttp)
import Data.List (sortBy, groupBy)
import Data.Function (on)
import Data.Map (Map, toList)
-- Record representing a single language.
data Language =
Language {
name :: String,
quantity :: Int
} deriving (Show)
-- Make Language an instance of FromJSON for parsing of query response.
instance FromJSON Language where
parseJSON (Object p) = do
categoryInfo <- p .:? "categoryinfo"
let quantity = case categoryInfo of
Just ob -> ob .: "size"
Nothing -> return 0
name = p .: "title"
Language <$> name <*> quantity
-- Record representing entire response to query.
-- Contains collection of languages and optional continuation string.
data Report =
Report {
continue :: Maybe String,
languages :: Map String Language
} deriving (Show)
-- Make Report an instance of FromJSON for parsing of query response.
instance FromJSON Report where
parseJSON (Object p) = do
querycontinue <- p .:? "query-continue"
let continue
= case querycontinue of
Just ob -> fmap Just $
(ob .: "categorymembers") >>=
( .: "gcmcontinue")
Nothing -> return Nothing
languages = (p .: "query") >>= (.: "pages")
Report <$> continue <*> languages
-- Pretty print a single language
showLanguage :: Int -> Bool -> Language -> IO ()
showLanguage rank tie (Language languageName languageQuantity) =
let rankStr = show rank
in putStrLn $ rankStr ++ "." ++
replicate (4 - length rankStr) ' ' ++
(if tie then " (tie)" else " ") ++
" " ++ drop 9 languageName ++
" - " ++ show languageQuantity
-- Pretty print languages with common rank
showRanking :: (Int, [Language]) -> IO ()
showRanking (ranking, languages) =
mapM_ (showLanguage ranking $ length languages > 1) languages
-- Sort and group languages by rank, then pretty print them.
showLanguages :: [Language] -> IO ()
showLanguages allLanguages =
mapM_ showRanking $
zip [1..] $
groupBy ((==) `on` quantity) $
sortBy (flip compare `on` quantity) allLanguages
-- Mediawiki api style query to send to rosettacode.org
queryStr = "http://rosettacode.org/mw/api.php?" ++
"format=json" ++
"&action=query" ++
"&generator=categorymembers" ++
"&gcmtitle=Category:Programming%20Languages" ++
"&gcmlimit=100" ++
"&prop=categoryinfo"
-- Issue query to get a list of Language descriptions
runQuery :: [Language] -> String -> IO ()
runQuery ls query = do
Just (Report continue langs) <- decode <$> simpleHttp query
let accLanguages = ls ++ map snd (toList langs)
case continue of
-- If there is no continue string we are done so display the accumulated languages.
Nothing -> showLanguages accLanguages
-- If there is a continue string, recursively continue the query.
Just continueStr -> do
let continueQueryStr = queryStr ++ "&gcmcontinue=" ++ urlEncode continueStr
runQuery accLanguages continueQueryStr
main :: IO ()
main = runQuery [] queryStr
|
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.
|
#Burlesque
|
Burlesque
|
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
=[{^^[~\/L[Sh}\m
|
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.
|
#CoffeeScript
|
CoffeeScript
|
# Find the n nth-roots of 1
nth_roots_of_unity = (n) ->
(complex_unit_vector(2*Math.PI*i/n) for i in [1..n])
complex_unit_vector = (rad) ->
new Complex(Math.cos(rad), Math.sin(rad))
class Complex
constructor: (@real, @imag) ->
toString: ->
round_z = (n) ->
if Math.abs(n) < 0.00005 then 0 else n
fmt = (n) -> n.toFixed(3)
real = round_z @real
imag = round_z @imag
s = ''
if real and imag
"#{fmt real}+#{fmt imag}i"
else if real or !imag
"#{fmt real}"
else
"#{fmt imag}i"
do ->
for n in [2..5]
console.log "---1 to the 1/#{n}"
for root in nth_roots_of_unity n
console.log root.toString()
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun roots-of-unity (n)
(loop for i below n
collect (cis (* pi (/ (* 2 i) 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.
|
#Go
|
Go
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
type header struct {
start, end int
lang string
}
type data struct {
count int
names *[]string
}
func newData(count int, name string) *data {
return &data{count, &[]string{name}}
}
var bmap = make(map[string]*data)
func add2bmap(lang, name string) {
pd := bmap[lang]
if pd != nil {
pd.count++
*pd.names = append(*pd.names, name)
} else {
bmap[lang] = newData(1, name)
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
expr := `==\s*{{\s*header\s*\|\s*([^\s\}]+)\s*}}\s*==`
expr2 := fmt.Sprintf("<%s>.*?</%s>", "lang", "lang")
r := regexp.MustCompile(expr)
r2 := regexp.MustCompile(expr2)
fileNames := []string{"example.txt", "example2.txt", "example3.txt"}
for _, fileName := range fileNames {
f, err := os.Open(fileName)
check(err)
b, err := ioutil.ReadAll(f)
check(err)
f.Close()
text := string(b)
fmt.Printf("Contents of %s:\n\n%s\n\n", fileName, text)
m := r.FindAllStringIndex(text, -1)
headers := make([]header, len(m))
if len(m) > 0 {
for i, p := range m {
headers[i] = header{p[0], p[1] - 1, ""}
}
m2 := r.FindAllStringSubmatch(text, -1)
for i, s := range m2 {
headers[i].lang = strings.ToLower(s[1])
}
}
last := len(headers) - 1
if last == -1 { // if there are no headers in the file add a dummy one
headers = append(headers, header{-1, -1, "no language"})
last = 0
}
m3 := r2.FindAllStringIndex(text, -1)
for _, p := range m3 {
if p[1] < headers[0].start {
add2bmap("no language", fileName)
} else if p[0] > headers[last].end {
add2bmap(headers[last].lang, fileName)
} else {
for i := 0; i < last; i++ {
if p[0] > headers[i].end && p[0] < headers[i+1].start {
add2bmap(headers[i].lang, fileName)
break
}
}
}
}
}
fmt.Println("Results:\n")
count := 0
for _, v := range bmap {
count += v.count
}
fmt.Printf(" %d bare language tags.\n\n", count)
for k, v := range bmap {
fmt.Printf(" %d in %-11s %v\n", v.count, k, *v.names)
}
}
|
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
|
Roots of a quadratic function
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle non-real roots, but it need not check that
a
≠
0
{\displaystyle a\neq 0}
.
The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic.
The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other.
In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with
a
=
1
{\displaystyle a=1}
,
b
=
−
10
5
{\displaystyle b=-10^{5}}
, and
c
=
1
{\displaystyle c=1}
.
(For double-precision floats, set
b
=
−
10
9
{\displaystyle b=-10^{9}}
.)
Consider the following implementation in Ada:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Quadratic_Equation is
type Roots is array (1..2) of Float;
function Solve (A, B, C : Float) return Roots is
SD : constant Float := sqrt (B**2 - 4.0 * A * C);
AA : constant Float := 2.0 * A;
begin
return ((- B + SD) / AA, (- B - SD) / AA);
end Solve;
R : constant Roots := Solve (1.0, -10.0E5, 1.0);
begin
Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2)));
end Quadratic_Equation;
Output:
X1 = 1.00000E+06 X2 = 0.00000E+00
As we can see, the second root has lost all significant figures. The right answer is that X2 is about
10
−
6
{\displaystyle 10^{-6}}
. The naive method is numerically unstable.
Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters
q
=
a
c
/
b
{\displaystyle q={\sqrt {ac}}/b}
and
f
=
1
/
2
+
1
−
4
q
2
/
2
{\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2}
and the two roots of the quardratic are:
−
b
a
f
{\displaystyle {\frac {-b}{a}}f}
and
−
c
b
f
{\displaystyle {\frac {-c}{bf}}}
Task: do it better. This means that given
a
=
1
{\displaystyle a=1}
,
b
=
−
10
9
{\displaystyle b=-10^{9}}
, and
c
=
1
{\displaystyle c=1}
, both of the roots your program returns should be greater than
10
−
11
{\displaystyle 10^{-11}}
. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle
b
=
−
10
6
{\displaystyle b=-10^{6}}
. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of
"What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <utility>
#include <complex>
typedef std::complex<double> complex;
std::pair<complex, complex>
solve_quadratic_equation(double a, double b, double c)
{
b /= a;
c /= a;
double discriminant = b*b-4*c;
if (discriminant < 0)
return std::make_pair(complex(-b/2, std::sqrt(-discriminant)/2),
complex(-b/2, -std::sqrt(-discriminant)/2));
double root = std::sqrt(discriminant);
double solution1 = (b > 0)? (-b - root)/2
: (-b + root)/2;
return std::make_pair(solution1, c/solution1);
}
int main()
{
std::pair<complex, complex> result = solve_quadratic_equation(1, -1e20, 1);
std::cout << result.first << ", " << result.second << std::endl;
}
|
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
|
#BaCon
|
BaCon
|
INPUT "String: ", s$
PRINT "Output: ", REPLACE$(s$, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", 2)
|
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 }
|
#J
|
J
|
NB.*rk4 a Solve function using Runge-Kutta method
NB. y is: y(ta) , ta , tb , tstep
NB. u is: function to solve
NB. eg: fyp rk4 1 0 10 0.1
rk4=: adverb define
'Y0 a b h'=. 4{. y
T=. a + i.@>:&.(%&h) b - a
Y=. Yt=. Y0
for_t. }: T do.
ty=. t,Yt
k1=. h * u ty
k2=. h * u ty + -: h,k1
k3=. h * u ty + -: h,k2
k4=. h * u ty + h,k3
Y=. Y, Yt=. Yt + (%6) * 1 2 2 1 +/@:* k1, k2, k3, k4
end.
T ,. Y
)
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#JavaScript
|
JavaScript
|
(function (strXPath) {
var xr = document.evaluate(
strXPath,
document,
null, 0, 0
),
oNode = xr.iterateNext(),
lstTasks = [];
while (oNode) {
lstTasks.push(oNode.title);
oNode = xr.iterateNext();
}
return [
lstTasks.length + " items found in " + document.title,
''
].concat(lstTasks).join('\n')
})(
'//*[@id="mw-content-text"]/div[2]/table/tbody/tr/td/ul/li/a'
);
|
http://rosettacode.org/wiki/S-expressions
|
S-expressions
|
S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
Newlines and other whitespace may be ignored unless contained within a quoted string.
“()” inside quoted strings are not interpreted, but treated as part of the string.
Handling escaped quotes inside a string is optional; thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error.
For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.
Languages that support it may treat unquoted strings as symbols.
Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.
The reader should be able to read the following input
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.)
The writer should be able to take the produced list and turn it into a new S-Expression.
Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted.
Extra Credit
Let the writer produce pretty printed output with indenting and line-breaks.
|
#J
|
J
|
NB. character classes: 0: paren, 1: quote, 2: whitespace, 3: wordforming (default)
chrMap=: '()';'"';' ',LF,TAB,CR
NB. state columns correspond to the above character classes
NB. first digit chooses next state.
NB. second digit is action 0: do nothing, 1: start token, 2: end token
states=: 10 10#: ".;._2]0 :0
11 21 00 31 NB. state 0: initial state
12 22 02 32 NB. state 1: after () or after closing "
40 10 40 40 NB. state 2: after opening "
12 22 02 30 NB. state 3: after word forming character
40 10 40 40 NB. state 4: between opening " and closing "
)
tokenize=: (0;states;<chrMap)&;:
rdSexpr=:3 :0 :.wrSexpr
s=. r=. '' [ 'L R'=. ;:'()'
for_token. tokenize y do.
select. token
case. L do. r=. '' [ s=. s,<r
case. R do. s=. }:s [ r=. (_1{::s),<r
case. do. r=. r,token
end.
end.
>{.r
)
wrSexpr=: ('(' , ;:^:_1 , ')'"_)^:L.L:1^:L. :.rdSexpr
fmt=: 3 :0 :.unfmt
if. '"' e. {.y do. }.,}: y NB. quoted string
elseif. 0=#$n=.".y do. n NB. number or character
elseif. do. s:<y NB. symbol
end.
)
unfmt=: 3 :0 :.fmt
select. 3!:0 y
case. 1;4;8;16;128 do. ":!.20 y
case. 2;131072 do.
select. #$y
case. 0 do. '''',y,''''
case. 1 do. '"',y,'"'
end.
case. 64 do. (":y),'x'
case. 65536 do. >s:inv y
end.
)
readSexpr=: fmt L:0 @rdSexpr :.writeSexpr
writeSexpr=: wrSexpr @(unfmt L:0) :.readSexpr
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#REXX
|
REXX
|
/*REXX program fixes (changes) depreciated HTML code tags with newer tags. */
@="<"; old.=; old.1 = @'%s>' ; new.1 = @"lang %s>"
old.2 = @'/%s>' ; new.2 = @"/lang>"
old.3 = @'code %s>' ; new.3 = @"lang %s>"
old.4 = @'/code>' ; new.4 = @"/lang>"
iFID = 'Wikisource.txt' /*the Input File IDentifier. */
oFID = 'converted.txt' /*the Output " " */
do while lines(iFID)\==0 /*keep reading the file until finished.*/
$= linein(iFID) /*read a record from the input file. */
do j=1 while old.j \== '' /*change old ──► new until finished. */
$= changestr(old.j,$,new.j) /*let REXX do the heavy lifting. */
end /*j*/
call lineout oFID,$ /*write re-formatted record to output. */
end /*while*/ /*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Ruby
|
Ruby
|
# get all stdin in one string
#text = $stdin.read
# for testing, use
text = DATA.read
slash_lang = '/lang'
langs = %w(foo bar baz) # actual list of languages declared here
for lang in langs
text.gsub!(Regexp.new("<(#{lang})>")) {"<lang #$1>"}
text.gsub!(Regexp.new("</#{lang}>"), "<#{slash_lang}>")
end
text.gsub!(/<code (.*?)>/, '<lang \1>')
text.gsub!(/<\/code>/, "<#{slash_lang}>")
print text
__END__
Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem
atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>,
ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel</bar>.
Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>. Eam volumus perpetua
constituto id, mea an omittam fierent vituperatoribus.
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “
n
{\displaystyle n}
” and “
e
{\displaystyle e}
” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “
d
{\displaystyle d}
” is kept secret, so that only the recipient can read the encrypted plaintext.
The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters
a
=
01
,
b
=
02
,
.
.
.
,
z
=
26
{\displaystyle a=01,b=02,...,z=26}
). This yields a string of numbers, generally referred to as "numerical plaintext", “
P
{\displaystyle P}
”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield
08051212152315181204
{\displaystyle 08051212152315181204}
.
The plaintext must also be split into blocks so that the numerical plaintext is smaller than
n
{\displaystyle n}
otherwise the decryption will fail.
The ciphertext,
C
{\displaystyle C}
, is then computed by taking each block of
P
{\displaystyle P}
, and computing
C
≡
P
e
mod
n
{\displaystyle C\equiv P^{e}\mod n}
Similarly, to decode, one computes
P
≡
C
d
mod
n
{\displaystyle P\equiv C^{d}\mod n}
To generate a key, one finds 2 (ideally large) primes
p
{\displaystyle p}
and
q
{\displaystyle q}
. the value “
n
{\displaystyle n}
” is simply:
n
=
p
×
q
{\displaystyle n=p\times q}
.
One must then choose an “
e
{\displaystyle e}
” such that
gcd
(
e
,
(
p
−
1
)
×
(
q
−
1
)
)
=
1
{\displaystyle \gcd(e,(p-1)\times (q-1))=1}
. That is to say,
e
{\displaystyle e}
and
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle (p-1)\times (q-1)}
are relatively prime to each other.
The decryption value
d
{\displaystyle d}
is then found by solving
d
×
e
≡
1
mod
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)}
The security of the code is based on the secrecy of the Private Key (decryption exponent) “
d
{\displaystyle d}
” and the difficulty in factoring “
n
{\displaystyle n}
”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes).
Summary of the task requirements:
Encrypt and Decrypt a short message or two using RSA with a demonstration key.
Implement RSA do not call a library.
Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine).
Either support blocking or give an error if the message would require blocking)
Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure:
n = 9516311845790656153499716760847001433441357
e = 65537
d = 5617843187844953170308463622230283376298685
Messages can be hard-coded into the program, there is no need for elaborate input coding.
Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
|
#Vlang
|
Vlang
|
/*import math.big
fn main() {
//var bb, ptn, etn, dtn big.Int
pt := "Rosetta Code"
println("Plain text: $pt")
// a key set big enough to hold 16 bytes of plain text in
// a single block (to simplify the example) and also big enough
// to demonstrate efficiency of modular exponentiation.
n := big.integer_from_string("9516311845790656153499716760847001433441357")?
e := big.integer_from_string("65537")?
d := big.integer_from_string("5617843187844953170308463622230283376298685")?
mut ptn := big.zero_int
// convert plain text to a number
for b in pt.bytes() {
bb := big.integer_from_i64(i64(b))
ptn = ptn.lshift(8).bitwise_or(bb)
}
if ptn >= n {
println("Plain text message too long")
return
}
println("Plain text as a number:$ptn")
// encode a single number
etn := ptn.big_mod_pow(e,n)
println("Encoded: $etn")
// decode a single number
mut dtn := etn.big_mod_pow(d,n)
println("Decoded: $dtn")
// convert number to text
mut db := [16]u8{}
mut dx := 16
bff := big.integer_from_int(0xff)
for dtn.bit_len() > 0 {
dx--
bb := dtn.bitwise_and(bff)
db[dx] = u8(i64(bb.int()))
dtn = dtn.rshift(8)
println('${db[0..].bytestr()} ${dtn.bit_len()}')
}
println("Decoded number as text: ${db[dx..].bytestr()}")
}*/
import math.big
fn main() {
//var bb, ptn, etn, dtn big.Int
pt := "Hello World"
println("Plain text: $pt")
// a key set big enough to hold 16 bytes of plain text in
// a single block (to simplify the example) and also big enough
// to demonstrate efficiency of modular exponentiation.
n := big.integer_from_string("9516311845790656153499716760847001433441357")?
e := big.integer_from_string("65537")?
d := big.integer_from_string("5617843187844953170308463622230283376298685")?
mut ptn := big.zero_int
// convert plain text to a number
for b in pt.bytes() {
bb := big.integer_from_i64(i64(b))
ptn = ptn.lshift(8).bitwise_or(bb)
}
if ptn >= n {
println("Plain text message too long")
return
}
println("Plain text as a number:$ptn")
// encode a single number
etn := ptn.big_mod_pow(e,n)
println("Encoded: $etn")
// decode a single number
mut dtn := etn.big_mod_pow(d,n)
println("Decoded: $dtn")
// convert number to text
mut db := [16]u8{}
mut dx := 16
bff := big.integer_from_int(0xff)
for dtn.bit_len() > 0 {
dx--
bb := dtn.bitwise_and(bff)
db[dx] = u8(i64(bb.int()))
dtn = dtn.rshift(8)
}
println("Decoded number as text: ${db[dx..].bytestr()}")
}
|
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.
|
#Java
|
Java
|
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class Rpg {
private static final Random random = new Random();
public static int genAttribute() {
return random.ints(1, 6 + 1) // Throw dices between 1 and 6
.limit(4) // Do 5 throws
.sorted() // Sort them
.limit(3) // Take the top 3
.sum(); // Sum them
}
public static void main(String[] args) {
while (true) {
List<Integer> stats =
Stream.generate(Rpg::genAttribute) // Generate some stats
.limit(6) // Take 6
.collect(toList()); // Save them in an array
int sum = stats.stream().mapToInt(Integer::intValue).sum();
long count = stats.stream().filter(v -> v >= 15).count();
if (count >= 2 && sum >= 75) {
System.out.printf("The 6 random numbers generated are: %s\n", stats);
System.out.printf("Their sum is %s and %s of them are >= 15\n", sum, count);
return;
}
}
}
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Run_BASIC
|
Run BASIC
|
input "Gimme the limit:"; limit
dim flags(limit)
for i = 2 to limit
for k = i*i to limit step i
flags(k) = 1
next k
if flags(i) = 0 then print i;", ";
next i
|
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
|
#Go
|
Go
|
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
fmt.Println(err) // connection or request fail
return ""
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
fmt.Println(err)
return ""
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
func main() {
taskQuery := "http://rosettacode.org/mw/api.php?action=query" +
"&format=xml&list=categorymembers&cmlimit=500" +
"&cmtitle=Category:Programming_Tasks"
continueAt := req(taskQuery, count)
for continueAt > "" {
continueAt = req(taskQuery+"&cmcontinue="+continueAt, count)
}
fmt.Printf("Total: %d examples.\n", total)
}
var marker = []byte("=={{header|")
var total int
func count(cm string) {
taskFmt := "http://rosettacode.org/mw/index.php?title=%s&action=raw"
taskEsc := url.QueryEscape(strings.Replace(cm, " ", "_", -1))
resp, err := http.Get(fmt.Sprintf(taskFmt, taskEsc))
var page []byte
if err == nil {
page, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
if err != nil {
fmt.Println(err)
return
}
examples := bytes.Count(page, marker)
fmt.Printf("%s: %d\n", cm, examples)
total += 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
|
#J
|
J
|
Haystack =: ;:'Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo'
Needles =: ;:'Washington Bush'
Haystack i. Needles NB. first positions
9 4
Haystack i: Needles NB. last positions
9 7
|
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.
|
#HicEst
|
HicEst
|
CHARACTER cats*50000, catlist*50000, sortedCat*50000, sample*100
DIMENSION RankNr(1)
READ(ClipBoard) cats
catlist = ' '
pos = 1 ! find language entries like * 100 doors (2 members)
nr = 0
! after next '*' find next "name" = '100 doors' and next "(...)" = '(2 members)' :
1 EDIT(Text=cats, SetPos=pos, Right='*', R, Mark1, R='(', Left, M2, Parse=name, R=2, P=members, GetPos=pos)
IF(pos > 0) THEN
READ(Text=members) count
IF(count > 0) THEN
nr = nr + 1
WRITE(Text=catlist, Format='i4, 1x, 2a', APPend) count, name, ';'
ENDIF
GOTO 1 ! no WHILE in HicEst
ENDIF ! catlist is now = " 1 ... User ; 2 100 doors ; 3 3D ; 8 4D ; ..."
ALLOCATE(RankNr, nr)
EDIT(Text=catlist, SePaRators=';', Option=1+4, SorTtoIndex=RankNr) ! case (1) and back (4)
sortedCat = ' ' ! get the sorted list in the sequence of RankNr:
ok = 0
DO i = 1, nr
EDIT(Text=catlist, SePaRators=';', ITeM=RankNr(i), CoPyto=sample)
discard = EDIT(Text=sample, LeXicon='user,attention,solutions,tasks,program,language,implementation,')
IF(discard == 0) THEN ! removes many of the non-language entries
ok = ok + 1
WRITE(Text=sortedCat, APPend, Format='F5.0, 2A') ok, TRIM(sample), $CRLF
ENDIF
ENDDO
DLG(Text=sortedCat, Format=$CRLF)
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
|
#11l
|
11l
|
F f(x)
R x^3 - 3 * x^2 + 2 * x
-V step = 0.001
-V start = -1.0
-V stop = 3.0
V sgn = f(start) > 0
V x = start
L x <= stop
V value = f(x)
I value == 0
print(‘Root found at ’x)
E I (value > 0) != sgn
print(‘Root found near ’x)
sgn = value > 0
x += step
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct stream_t stream_t, *stream;
struct stream_t {
/* get function is supposed to return a byte value (0-255),
or -1 to signify end of input */
int (*get)(stream);
/* put function does output, one byte at a time */
int (*put)(stream, int);
};
/* next two structs inherit from stream_t */
typedef struct {
int (*get)(stream);
int (*put)(stream, int);
char *string;
int pos;
} string_stream;
typedef struct {
int (*get)(stream);
int (*put)(stream, int);
FILE *fp;
} file_stream;
/* methods for above streams */
int sget(stream in)
{
int c;
string_stream* s = (string_stream*) in;
c = (unsigned char)(s->string[s->pos]);
if (c == '\0') return -1;
s->pos++;
return c;
}
int sput(stream out, int c)
{
string_stream* s = (string_stream*) out;
s->string[s->pos++] = (c == -1) ? '\0' : c;
if (c == -1) s->pos = 0;
return 0;
}
int file_put(stream out, int c)
{
file_stream *f = (file_stream*) out;
return fputc(c, f->fp);
}
/* helper function */
void output(stream out, unsigned char* buf, int len)
{
int i;
out->put(out, 128 + len);
for (i = 0; i < len; i++)
out->put(out, buf[i]);
}
/* Specification: encoded stream are unsigned bytes consisting of sequences.
* First byte of each sequence is the length, followed by a number of bytes.
* If length <=128, the next byte is to be repeated length times;
* If length > 128, the next (length - 128) bytes are not repeated.
* this is to improve efficiency for long non-repeating sequences.
* This scheme can encode arbitrary byte values efficiently.
* c.f. Adobe PDF spec RLE stream encoding (not exactly the same)
*/
void encode(stream in, stream out)
{
unsigned char buf[256];
int len = 0, repeat = 0, end = 0, c;
int (*get)(stream) = in->get;
int (*put)(stream, int) = out->put;
while (!end) {
end = ((c = get(in)) == -1);
if (!end) {
buf[len++] = c;
if (len <= 1) continue;
}
if (repeat) {
if (buf[len - 1] != buf[len - 2])
repeat = 0;
if (!repeat || len == 129 || end) {
/* write out repeating bytes */
put(out, end ? len : len - 1);
put(out, buf[0]);
buf[0] = buf[len - 1];
len = 1;
}
} else {
if (buf[len - 1] == buf[len - 2]) {
repeat = 1;
if (len > 2) {
output(out, buf, len - 2);
buf[0] = buf[1] = buf[len - 1];
len = 2;
}
continue;
}
if (len == 128 || end) {
output(out, buf, len);
len = 0;
repeat = 0;
}
}
}
put(out, -1);
}
void decode(stream in, stream out)
{
int c, i, cnt;
while (1) {
c = in->get(in);
if (c == -1) return;
if (c > 128) {
cnt = c - 128;
for (i = 0; i < cnt; i++)
out->put(out, in->get(in));
} else {
cnt = c;
c = in->get(in);
for (i = 0; i < cnt; i++)
out->put(out, c);
}
}
}
int main()
{
char buf[256];
string_stream str_in = { sget, 0,
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 0};
string_stream str_out = { sget, sput, buf, 0 };
file_stream file = { 0, file_put, stdout };
/* encode from str_in to str_out */
encode((stream)&str_in, (stream)&str_out);
/* decode from str_out to file (stdout) */
decode((stream)&str_out, (stream)&file);
return 0;
}
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#Crystal
|
Crystal
|
require "complex"
def roots_of_unity(n)
(0...n).map { |k| Math.exp((2 * Math::PI * k / n).i) }
end
p roots_of_unity(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.
|
#D
|
D
|
import std.stdio, std.range, std.algorithm, std.complex;
import std.math: PI;
auto nthRoots(in int n) pure nothrow {
return n.iota.map!(k => expi(PI * 2 * (k + 1) / n));
}
void main() {
foreach (immutable i; 1 .. 6)
writefln("#%d: [%(%5.2f, %)]", i, i.nthRoots);
}
|
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.
|
#Groovy
|
Groovy
|
import java.util.function.Predicate
import java.util.regex.Matcher
import java.util.regex.Pattern
class FindBareTags {
private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"")
private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==")
private static final Predicate<String> BARE_PREDICATE = Pattern.compile("<lang>").asPredicate()
static String download(URL target) {
URLConnection connection = target.openConnection()
connection.setRequestProperty("User-Agent", "Firefox/2.0.0.4")
InputStream is = connection.getInputStream()
return is.getText("UTF-8")
}
static void main(String[] args) {
URI titleUri = URI.create("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks")
String titleText = download(titleUri.toURL())
if (titleText != null) {
Matcher titleMatcher = TITLE_PATTERN.matcher(titleText)
Map<String, Integer> countMap = new HashMap<>()
while (titleMatcher.find()) {
String title = titleMatcher.group(1)
URI pageUri = new URI("http", null, "//rosettacode.org/wiki", "action=raw&title=$title", null)
String pageText = download(pageUri.toURL())
if (pageText != null) {
String language = "no language"
for (String line : pageText.readLines()) {
Matcher headerMatcher = HEADER_PATTERN.matcher(line)
if (headerMatcher.matches()) {
language = headerMatcher.group(1)
continue
}
if (BARE_PREDICATE.test(line)) {
int count = countMap.get(language, 0) + 1
countMap.put(language, count)
}
}
} else {
println("Got an error reading the task page")
}
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
println("$entry.value in $entry.key")
}
} else {
println("Got an error reading the title page")
}
}
}
|
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.
|
#Clojure
|
Clojure
|
(defn quadratic
"Compute the roots of a quadratic in the form ax^2 + bx + c = 1.
Returns any of nil, a float, or a vector."
[a b c]
(let [sq-d (Math/sqrt (- (* b b) (* 4 a c)))
f #(/ (% b sq-d) (* 2 a))]
(cond
(neg? sq-d) nil
(zero? sq-d) (f +)
(pos? sq-d) [(f +) (f -)]
:else nil))) ; maybe our number ended up as NaN
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun quadratic (a b c)
(list
(/ (+ (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 a))
(/ (- (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 a))))
|
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
|
#BASIC
|
BASIC
|
CLS
INPUT "Enter a string: ", s$
ans$ = ""
FOR a = 1 TO LEN(s$)
letter$ = MID$(s$, a, 1)
IF letter$ >= "A" AND letter$ <= "Z" THEN
char$ = CHR$(ASC(letter$) + 13)
IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26)
ELSEIF letter$ >= "a" AND letter$ <= "z" THEN
char$ = CHR$(ASC(letter$) + 13)
IF char$ > "z" THEN char$ = CHR$(ASC(char$) - 26)
ELSE
char$ = letter$
END IF
ans$ = ans$ + char$
NEXT a
PRINT ans$
|
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 }
|
#Java
|
Java
|
import static java.lang.Math.*;
import java.util.function.BiFunction;
public class RungeKutta {
static void runge(BiFunction<Double, Double, Double> yp_func, double[] t,
double[] y, double dt) {
for (int n = 0; n < t.length - 1; n++) {
double dy1 = dt * yp_func.apply(t[n], y[n]);
double dy2 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy1 / 2.0);
double dy3 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy2 / 2.0);
double dy4 = dt * yp_func.apply(t[n] + dt, y[n] + dy3);
t[n + 1] = t[n] + dt;
y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0;
}
}
static double calc_err(double t, double calc) {
double actual = pow(pow(t, 2.0) + 4.0, 2) / 16.0;
return abs(actual - calc);
}
public static void main(String[] args) {
double dt = 0.10;
double[] t_arr = new double[101];
double[] y_arr = new double[101];
y_arr[0] = 1.0;
runge((t, y) -> t * sqrt(y), t_arr, y_arr, dt);
for (int i = 0; i < t_arr.length; i++)
if (i % 10 == 0)
System.out.printf("y(%.1f) = %.8f Error: %.6f%n",
t_arr[i], y_arr[i],
calc_err(t_arr[i], y_arr[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
|
#Julia
|
Julia
|
using HTTP, JSON
const baseuri = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:"
const enduri = "&cmlimit=500&format=json"
queries(x) = baseuri * HTTP.Strings.escapehtml(x) * enduri
function getimplemented(query)
tasksdone = Vector{String}()
request = query
while (resp = HTTP.request("GET", request)).status == 200
fromjson = JSON.parse(String(resp.body))
for d in fromjson["query"]["categorymembers"]
if haskey(d, "title")
push!(tasksdone, d["title"])
end
end
if haskey(fromjson, "continue")
cmcont, cont = fromjson["continue"]["cmcontinue"], fromjson["continue"]["continue"]
request = query * "&cmcontinue=$cmcont&continue=$cont"
else
break
end
end
tasksdone
end
alltasks = getimplemented(queries("Programming_Tasks"))
showunimp(x) = (println("\nUnimplemented in $x:"); for t in setdiff(alltasks,
getimplemented(queries(x))) println(t) end)
showunimp("Julia")
showunimp("C++")
|
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
|
#Lua
|
Lua
|
local requests = require('requests')
local lang = arg[1]
local function merge_tables(existing, from_req)
local result = existing
for _, v in ipairs(from_req) do
result[v.title] = true
end
return result
end
local function get_task_list(category)
local url = 'http://www.rosettacode.org/mw/api.php'
local query = {
action = 'query',
list = 'categorymembers',
cmtitle = string.format('Category:%s', category),
cmlimit = 500,
cmtype = 'page',
format = 'json'
}
local categories = {}
while true do
local resp = assert(requests.get({ url, params = query }).json())
categories = merge_tables(categories, resp.query.categorymembers)
if resp.continue then
query.cmcontinue = resp.continue.cmcontinue
else
break
end
end
return categories
end
local function get_open_tasks(lang)
if not lang then error('Language missing!') end
local all_tasks = get_task_list('Programming_Tasks')
local lang_tasks = get_task_list(lang)
local task_list = {}
for t, _ in pairs(all_tasks) do
if not lang_tasks[t] then
table.insert(task_list, t)
end
end
table.sort(task_list)
return task_list
end
local open_tasks = get_open_tasks(lang)
io.write(string.format('%s has %d unimplemented programming tasks: \n', lang, #open_tasks))
for _, t in ipairs(open_tasks) do
io.write(string.format(' %s\n', t))
end
|
http://rosettacode.org/wiki/S-expressions
|
S-expressions
|
S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
Newlines and other whitespace may be ignored unless contained within a quoted string.
“()” inside quoted strings are not interpreted, but treated as part of the string.
Handling escaped quotes inside a string is optional; thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error.
For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.
Languages that support it may treat unquoted strings as symbols.
Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.
The reader should be able to read the following input
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.)
The writer should be able to take the produced list and turn it into a new S-Expression.
Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted.
Extra Credit
Let the writer produce pretty printed output with indenting and line-breaks.
|
#Java
|
Java
|
package jfkbits;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.Iterator;
public class LispTokenizer implements Iterator<Token>
{
// Instance variables have default access to allow unit tests access.
StreamTokenizer m_tokenizer;
IOException m_ioexn;
/** Constructs a tokenizer that scans input from the given string.
* @param src A string containing S-expressions.
*/
public LispTokenizer(String src)
{
this(new StringReader(src));
}
/** Constructs a tokenizer that scans input from the given Reader.
* @param r Reader for the character input source
*/
public LispTokenizer(Reader r)
{
if(r == null)
r = new StringReader("");
BufferedReader buffrdr = new BufferedReader(r);
m_tokenizer = new StreamTokenizer(buffrdr);
m_tokenizer.resetSyntax(); // We don't like the default settings
m_tokenizer.whitespaceChars(0, ' ');
m_tokenizer.wordChars(' '+1,255);
m_tokenizer.ordinaryChar('(');
m_tokenizer.ordinaryChar(')');
m_tokenizer.ordinaryChar('\'');
m_tokenizer.commentChar(';');
m_tokenizer.quoteChar('"');
}
public Token peekToken()
{
if(m_ioexn != null)
return null;
try
{
m_tokenizer.nextToken();
}
catch(IOException e)
{
m_ioexn = e;
return null;
}
if(m_tokenizer.ttype == StreamTokenizer.TT_EOF)
return null;
Token token = new Token(m_tokenizer);
m_tokenizer.pushBack();
return token;
}
public boolean hasNext()
{
if(m_ioexn != null)
return false;
try
{
m_tokenizer.nextToken();
}
catch(IOException e)
{
m_ioexn = e;
return false;
}
if(m_tokenizer.ttype == StreamTokenizer.TT_EOF)
return false;
m_tokenizer.pushBack();
return true;
}
/** Return the most recently caught IOException, if any,
*
* @return
*/
public IOException getIOException()
{
return m_ioexn;
}
public Token next()
{
try
{
m_tokenizer.nextToken();
}
catch(IOException e)
{
m_ioexn = e;
return null;
}
Token token = new Token(m_tokenizer);
return token;
}
public void remove()
{
}
}
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Rust
|
Rust
|
extern crate regex;
use std::io;
use std::io::prelude::*;
use regex::Regex;
const LANGUAGES: &str =
"_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit \
avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp \
cpp-qt csharp css d delphi diff dos dot eiffel email fortran freebasic genero gettext glsl \
gml gnuplot groovy haskell hq9plus html4strict idl ini inno intercal io java java5 \
javascript kixtart klonec klonecpp latex lisp lolcode lotusformulas lotusscript lscript lua \
m68k make matlab mirc modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 \
oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray powershell progress \
prolog providex python qbasic rails reg robots ruby rust sas scala scheme scilab sdlbasic \
smalltalk smarty sql tcl teraterm text thinbasic tsql typoscript vb vbnet verilog vhdl vim \
visualfoxpro visualprolog whitespace winbatch xml xorg_conf xpp z80";
fn fix_tags(languages: &[&str], text: &str) -> String {
let mut replaced_text = text.to_owned();
for lang in languages.iter() {
let bad_open = Regex::new(&format!("<{lang}>|<code {lang}>", lang = lang)).unwrap();
let bad_close = Regex::new(&format!("</{lang}>|</code>", lang = lang)).unwrap();
let open = format!("<lang {}>", lang);
let close = "</lang>";
replaced_text = bad_open.replace_all(&replaced_text, &open[..]).into_owned();
replaced_text = bad_close
.replace_all(&replaced_text, &close[..])
.into_owned();
}
replaced_text
}
fn main() {
let stdin = io::stdin();
let mut buf = String::new();
stdin.lock().read_to_string(&mut buf).unwrap();
println!(
"{}",
fix_tags(&LANGUAGES.split_whitespace().collect::<Vec<_>>(), &buf)
);
}
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Scala
|
Scala
|
object FixCodeTags extends App {
val rx = // See for regex explanation: https://regex101.com/r/N8X4x7/3/
// Flags ignore case, dot matching line breaks, unicode support
s"(?is)<(?:(?:code\\s+)?(${langs.mkString("|")}))>(.+?|)<\\/(?:code|\\1)>".r
def langs = // Real list of langs goes here
Seq("bar", "baz", "foo", "Scala", "உயிர்/Uyir", "Müller")
def markDown =
"""Lorem ipsum <Code foo>saepe audire</code> elaboraret ne quo, id equidem
|atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, ius
|ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
|altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel
|</bar>. Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>.
|Eam volumus perpetua constituto id, mea an omittam fierent vituperatoribus.
|Empty element: <Müller></Müller><scaLa></Scala><உயிர்/Uyir></உயிர்/Uyir>""".stripMargin
println(rx.replaceAllIn(markDown, _ match {
case rx(langName, langCode) => s"<lang ${langName.capitalize}>${langCode}<${"/lan"}g>"
})) // ${"/lan"}g is the <noWiki> escape.
}
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “
n
{\displaystyle n}
” and “
e
{\displaystyle e}
” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “
d
{\displaystyle d}
” is kept secret, so that only the recipient can read the encrypted plaintext.
The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters
a
=
01
,
b
=
02
,
.
.
.
,
z
=
26
{\displaystyle a=01,b=02,...,z=26}
). This yields a string of numbers, generally referred to as "numerical plaintext", “
P
{\displaystyle P}
”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield
08051212152315181204
{\displaystyle 08051212152315181204}
.
The plaintext must also be split into blocks so that the numerical plaintext is smaller than
n
{\displaystyle n}
otherwise the decryption will fail.
The ciphertext,
C
{\displaystyle C}
, is then computed by taking each block of
P
{\displaystyle P}
, and computing
C
≡
P
e
mod
n
{\displaystyle C\equiv P^{e}\mod n}
Similarly, to decode, one computes
P
≡
C
d
mod
n
{\displaystyle P\equiv C^{d}\mod n}
To generate a key, one finds 2 (ideally large) primes
p
{\displaystyle p}
and
q
{\displaystyle q}
. the value “
n
{\displaystyle n}
” is simply:
n
=
p
×
q
{\displaystyle n=p\times q}
.
One must then choose an “
e
{\displaystyle e}
” such that
gcd
(
e
,
(
p
−
1
)
×
(
q
−
1
)
)
=
1
{\displaystyle \gcd(e,(p-1)\times (q-1))=1}
. That is to say,
e
{\displaystyle e}
and
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle (p-1)\times (q-1)}
are relatively prime to each other.
The decryption value
d
{\displaystyle d}
is then found by solving
d
×
e
≡
1
mod
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)}
The security of the code is based on the secrecy of the Private Key (decryption exponent) “
d
{\displaystyle d}
” and the difficulty in factoring “
n
{\displaystyle n}
”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes).
Summary of the task requirements:
Encrypt and Decrypt a short message or two using RSA with a demonstration key.
Implement RSA do not call a library.
Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine).
Either support blocking or give an error if the message would require blocking)
Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure:
n = 9516311845790656153499716760847001433441357
e = 65537
d = 5617843187844953170308463622230283376298685
Messages can be hard-coded into the program, there is no need for elaborate input coding.
Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
|
#Wren
|
Wren
|
import "/big" for BigInt
var pt = "Rosetta Code"
System.print("Plain text: : %(pt)")
var n = BigInt.new("9516311845790656153499716760847001433441357")
var e = BigInt.new("65537")
var d = BigInt.new("5617843187844953170308463622230283376298685")
var ptn = BigInt.zero
// convert plain text to a number
for (b in pt.bytes) {
ptn = (ptn << 8) | BigInt.new(b)
}
if (ptn >= n) {
System.print("Plain text message too long")
return
}
System.print("Plain text as a number : %(ptn)")
// encode a single number
var etn = ptn.modPow(e, n)
System.print("Encoded : %(etn)")
// decode a single number
var dtn = etn.modPow(d, n)
System.print("Decoded : %(dtn)")
// convert number to text
var db = List.filled(16, 0)
var dx = 16
var bff = BigInt.new(255)
while (dtn.bitLength > 0) {
dx = dx - 1
db[dx] = (dtn & bff).toSmall
dtn = dtn >> 8
}
var s = ""
for (i in dx..15) s = s + String.fromByte(db[i])
System.print("Decoded number as text : %(s)")
|
http://rosettacode.org/wiki/RPG_attributes_generator
|
RPG attributes generator
|
RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three 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.
|
#JavaScript
|
JavaScript
|
function roll() {
const stats = {
total: 0,
rolls: []
}
let count = 0;
for(let i=0;i<=5;i++) {
let d6s = [];
for(let j=0;j<=3;j++) {
d6s.push(Math.ceil(Math.random() * 6))
}
d6s.sort().splice(0, 1);
rollTotal = d6s.reduce((a, b) => a+b, 0);
stats.rolls.push(rollTotal);
stats.total += rollTotal;
}
return stats;
}
let rolledCharacter = roll();
while(rolledCharacter.total < 75 || rolledCharacter.rolls.filter(a => a >= 15).length < 2){
rolledCharacter = roll();
}
console.log(`The 6 random numbers generated are:
${rolledCharacter.rolls.join(', ')}
Their sum is ${rolledCharacter.total} and ${rolledCharacter.rolls.filter(a => a >= 15).length} of them are >= 15`);
|
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
|
#Rust
|
Rust
|
fn primes(n: usize) -> impl Iterator<Item = usize> {
const START: usize = 2;
if n < START {
Vec::new()
} else {
let mut is_prime = vec![true; n + 1 - START];
let limit = (n as f64).sqrt() as usize;
for i in START..limit + 1 {
let mut it = is_prime[i - START..].iter_mut().step_by(i);
if let Some(true) = it.next() {
it.for_each(|x| *x = false);
}
}
is_prime
}
.into_iter()
.enumerate()
.filter_map(|(e, b)| if b { Some(e + START) } else { None })
}
|
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
|
#Haskell
|
Haskell
|
import Network.Browser
import Network.HTTP
import Network.URI
import Data.List
import Data.Maybe
import Text.XML.Light
import Control.Arrow
justifyR w = foldl ((.return).(++).tail) (replicate w ' ')
showFormatted t n = t ++ ": " ++ justifyR 4 (show n)
getRespons url = do
rsp <- Network.Browser.browse $ do
setAllowRedirects True
setOutHandler $ const (return ()) -- quiet
request $ getRequest url
return $ rspBody $ snd rsp
getNumbOfExampels p = do
let pg = intercalate "_" $ words p
rsp <- getRespons $ "http://www.rosettacode.org/w/index.php?title=" ++ pg ++ "&action=raw"
let taskPage = rsp
countEx = length $ filter (=="=={{header|") $ takeWhile(not.null) $ unfoldr (Just. (take 11 &&& drop 1)) taskPage
return countEx
progTaskExamples = do
rsp <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
let xmls = onlyElems $ parseXML $ rsp
tasks = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xmls
taskxx <- mapM getNumbOfExampels tasks
let ns = taskxx
tot = sum ns
mapM_ putStrLn $ zipWith showFormatted tasks ns
putStrLn $ ("Total: " ++) $ show tot
|
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
|
#Java
|
Java
|
import java.util.List;
import java.util.Arrays;
List<String> haystack = Arrays.asList("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
for (String needle : new String[]{"Washington","Bush"}) {
int index = haystack.indexOf(needle);
if (index < 0)
System.out.println(needle + " is not in haystack");
else
System.out.println(index + " " + needle);
}
|
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
|
Rosetta Code/Rank languages by popularity
|
Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,540 entries) Phix
Rank: 2 (1,531 entries) Wren
Rank: 3 (1,507 entries) Julia
Rank: 4 (1,494 entries) Go
Rank: 5 (1,488 entries) Raku
Rank: 6 (1,448 entries) Perl
Rank: 7 (1,402 entries) Nim
Rank: 8 (1,382 entries) Python
Rank: 9 (1,204 entries) C
Rank: 10 (1,152 entries) REXX
...
Notes
Each language typically demonstrates one or two methods of accessing the data:
with web scraping (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)
with the API method (examples below for Awk, Perl, Ruby, Tcl, etc).
The scraping and API solutions can be separate subsections, see the Tcl example.
Filtering wrong results is optional. You can check against Special:MostLinkedCategories (if using web scraping)
If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.
A complete ranked listing of all 813 languages (from the REXX example) is included here ──► output from the REXX program.
|
#Icon_and_Unicon
|
Icon and Unicon
|
$define RCLANGS "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo"
$define RCUA "User-Agent: Unicon Rosetta 0.1"
$define RCXUA "X-Unicon: http://unicon.org/"
link strings
link hexcvt
procedure main()
cnt := create seq()
last := -1
every pair := !reverse(sort(langs := tallyPages(),2)) do {
n := if last ~=:= pair[2] then @cnt else (@cnt,"")
write(right(n,4),": ",left(pair[1],30,". "),right(pair[2],10,". "))
}
write(*langs, " languages")
end
# Generate page counts for each language
procedure tallyPages(url)
/url := RCLANGS
counts := table()
continue := ""
while \(txt := ReadURL(url||continue)) do {
txt ? {
if tab(find("gcmcontinue=")) then {
continue := "&"||tab(upto('"'))
move(1)
continue ||:= tab(upto('"'))
}
else continue := ""
while tab(find("<page ") & find(s := "title=\"Category:")+*s) do {
lang := tab(upto('"'))
tab(find(s := "pages=\"")+*s)
counts[lang] := numeric(tab(upto('"')))
}
if continue == "" then return counts
}
}
end
procedure ReadURL(url) #: read URL into string
page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url)
text := ""
if page["Status-Code"] < 300 then while text ||:= reads(page,-1)
else write(&errout,image(url),": ",
page["Status-Code"]," ",page["Reason-Phrase"])
close(page)
return text
end
|
http://rosettacode.org/wiki/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
|
#Ada
|
Ada
|
with Ada.Text_Io; use Ada.Text_Io;
procedure Roots_Of_Function is
package Real_Io is new Ada.Text_Io.Float_Io(Long_Float);
use Real_Io;
function F(X : Long_Float) return Long_Float is
begin
return (X**3 - 3.0*X*X + 2.0*X);
end F;
Step : constant Long_Float := 1.0E-6;
Start : constant Long_Float := -1.0;
Stop : constant Long_Float := 3.0;
Value : Long_Float := F(Start);
Sign : Boolean := Value > 0.0;
X : Long_Float := Start + Step;
begin
if Value = 0.0 then
Put("Root found at ");
Put(Item => Start, Fore => 1, Aft => 6, Exp => 0);
New_Line;
end if;
while X <= Stop loop
Value := F(X);
if (Value > 0.0) /= Sign then
Put("Root found near ");
Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
New_Line;
elsif Value = 0.0 then
Put("Root found at ");
Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
New_Line;
end if;
Sign := Value > 0.0;
X := X + Step;
end loop;
end Roots_Of_Function;
|
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.
|
#C.23
|
C#
|
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using static System.Linq.Enumerable;
namespace RunLengthEncoding
{
static class Program
{
public static string Encode(string input) => input.Length ==0 ? "" : input.Skip(1)
.Aggregate((t:input[0].ToString(),o:Empty<string>()),
(a,c)=>a.t[0]==c ? (a.t+c,a.o) : (c.ToString(),a.o.Append(a.t)),
a=>a.o.Append(a.t).Select(p => (key: p.Length, chr: p[0])))
.Select(p=> $"{p.key}{p.chr}")
.StringConcat();
public static string Decode(string input) => input
.Aggregate((t: "", o: Empty<string>()), (a, c) => !char.IsDigit(c) ? ("", a.o.Append(a.t+c)) : (a.t + c,a.o)).o
.Select(p => new string(p.Last(), int.Parse(string.Concat(p.Where(char.IsDigit)))))
.StringConcat();
private static string StringConcat(this IEnumerable<string> seq) => string.Concat(seq);
public static void Main(string[] args)
{
const string raw = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
const string encoded = "12W1B12W3B24W1B14W";
WriteLine($"raw = {raw}");
WriteLine($"encoded = {encoded}");
WriteLine($"Encode(raw) = encoded = {Encode(raw)}");
WriteLine($"Decode(encode) = {Decode(encoded)}");
WriteLine($"Decode(Encode(raw)) = {Decode(Encode(raw)) == raw}");
ReadLine();
}
}
}
|
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.
|
#Delphi
|
Delphi
|
program Roots_of_unity;
{$APPTYPE CONSOLE}
uses
System.VarCmplx;
function RootOfUnity(degree: integer): Tarray<Variant>;
var
k: Integer;
begin
SetLength(result, degree);
for k := 0 to degree - 1 do
Result[k] := VarComplexFromPolar(1, 2 * pi * k / degree);
end;
const
n = 3;
var
num: Variant;
begin
Writeln('Root of unity from ', n, ':'#10);
for num in RootOfUnity(n) do
Writeln(num);
Readln;
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.
|
#Haskell
|
Haskell
|
import System.Environment
import Network.HTTP
import Text.Printf
import Text.Regex.TDFA
import Data.List
import Data.Array
import qualified Data.Map as Map
{-| Takes a string and cuts out the text matched in the MatchText array. -}
splitByMatches :: String -> [MatchText String] -> [String]
splitByMatches str matches = foldr splitHead [str] matches
where splitHead match acc = before:after:(tail acc)
where before = take (matchOffset).head$ acc
after = drop (matchOffset + matchLen).head$ acc
matchOffset = fst.snd.(!0)$ match
matchLen = snd.snd.(!0)$ match
{-| Takes a string and counts the number of time a valid, but bare, lang tag
appears. It does not attempt to ignore valid tags inside lang blocks. -}
countBareLangTags :: String -> Int
countBareLangTags = matchCount (makeRegex "<lang[[:space:]]*>" :: Regex)
{-| Takes a string and counts the number of bare lang tags per section of the
text. All tags before the first section are put into the key "". -}
countByLanguage :: String -> Map.Map String Int
countByLanguage str = Map.fromList.filter ((>0).snd)$ zip langs counts
where counts = map countBareLangTags.splitByMatches str$ allMatches
langs = "":(map (fst.(!1)) allMatches)
allMatches = matchAllText (makeRegex headerRegex :: Regex) str
headerRegex = "==[[:space:]]*{{[[:space:]]*header[[:space:]]*\\|[[:space:]]*([^ }]*)[[:space:]]*}}[^=]*=="
main = do
args <- getArgs
(contents, files) <- if length args == 0 then do
-- If there aren't arguments, read from stdin
content <- getContents
return ([content],[""])
else if length args == 1 then do
-- If there's only one argument, read the file, but don't display
-- the filename in the results.
content <- readFile (head args)
return ([content],[""])
else if (args !! 0) == "-w" then do
-- If there's more than one argument and the first one is the -w option,
-- use the rest of the arguments as page titles and load them from the wiki.
contents <- mapM getPageContent.tail$ args
return (contents, if length args > 2 then tail args else [""])
else do
-- Otherwise, read all the files and display their file names.
contents <- mapM readFile args
return (contents, args)
let tagsPerLang = map countByLanguage contents
let tagsWithFiles = zipWith addFileToTags files tagsPerLang
let combinedFiles = Map.unionsWith combine tagsWithFiles
printBareTags combinedFiles
where addFileToTags file = Map.map (flip (,) [file])
combine cur next = (fst cur + fst next, snd cur ++ snd next)
printBareTags :: Map.Map String (Int,[String]) -> IO ()
printBareTags tags = do
let numBare = Map.foldr ((+).fst) 0 tags
printf "%d bare language tags:\n\n" numBare
mapM_ (\(lang,(count,files)) ->
printf "%d in %s%s\n" count
(if lang == "" then "no language" else lang)
(filesString files)
) (Map.toAscList tags)
filesString :: [String] -> String
filesString [] = ""
filesString ("":rest) = filesString rest
filesString files = " ("++listString files++")"
where listString [file] = "[["++file++"]]"
listString (file:files) = "[["++file++"]], "++listString files
getPageContent :: String -> IO String
getPageContent title = do
response <- simpleHTTP.getRequest$ url
getResponseBody response
where url = "http://rosettacode.org/mw/index.php?action=raw&title="++title
|
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.
|
#D
|
D
|
import std.math, std.traits;
CommonType!(T1, T2, T3)[] naiveQR(T1, T2, T3)
(in T1 a, in T2 b, in T3 c)
pure nothrow if (isFloatingPoint!T1) {
alias ReturnT = typeof(typeof(return).init[0]);
if (a == 0)
return [ReturnT(c / b)]; // It's a linear function.
immutable ReturnT det = b ^^ 2 - 4 * a * c;
if (det < 0)
return []; // No real number root.
immutable SD = sqrt(det);
return [(-b + SD) / 2 * a, (-b - SD) / 2 * a];
}
CommonType!(T1, T2, T3)[] cautiQR(T1, T2, T3)
(in T1 a, in T2 b, in T3 c)
pure nothrow if (isFloatingPoint!T1) {
alias ReturnT = typeof(typeof(return).init[0]);
if (a == 0)
return [ReturnT(c / b)]; // It's a linear function.
immutable ReturnT det = b ^^ 2 - 4 * a * c;
if (det < 0)
return []; // No real number root.
immutable SD = sqrt(det);
if (b * a < 0) {
immutable x = (-b + SD) / 2 * a;
return [x, c / (a * x)];
} else {
immutable x = (-b - SD) / 2 * a;
return [c / (a * x), x];
}
}
void main() {
import std.stdio;
writeln("With 32 bit float type:");
writefln(" Naive: [%(%g, %)]", naiveQR(1.0f, -10e5f, 1.0f));
writefln("Cautious: [%(%g, %)]", cautiQR(1.0f, -10e5f, 1.0f));
writeln("\nWith 64 bit double type:");
writefln(" Naive: [%(%g, %)]", naiveQR(1.0, -10e5, 1.0));
writefln("Cautious: [%(%g, %)]", cautiQR(1.0, -10e5, 1.0));
writeln("\nWith real type:");
writefln(" Naive: [%(%g, %)]", naiveQR(1.0L, -10e5L, 1.0L));
writefln("Cautious: [%(%g, %)]", cautiQR(1.0L, -10e5L, 1.0L));
}
|
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
|
#BASIC256
|
BASIC256
|
# rot13 Cipher v2.0
# basic256 1.1.4.0
# 2101031238
dec$ = ""
TYPE$ = "cleartext "
ctext$ = ""
sp = 0
iOffset = 13 #offset assumed TO be 13 - uncomment LINE 11 TO change
INPUT "For decrypt enter " + "<d> " + " -- else press enter > ",dec$
# INPUT "Enter offset > ", iOffset
IF dec$ = "d" OR dec$ = "D" THEN
iOffset = 26 - iOffset
TYPE$ = "ciphertext "
END IF
INPUT "Enter " + TYPE$ + "> ", STR$
STR$ = upper(STR$)
FOR i = 1 TO length(STR$)
iTemp = ASC(mid(STR$,i,1))
IF iTemp > 64 AND iTemp < 91 THEN
iTemp = ((iTemp - 65) + iOffset) % 26
PRINT chr(iTemp + 65);
sp = sp + 1
IF sp = 5 THEN
PRINT(' ');
sp = 0
endif
endif
NEXT i
|
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 }
|
#JavaScript
|
JavaScript
|
function rk4(y, x, dx, f) {
var k1 = dx * f(x, y),
k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0),
k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0),
k4 = dx * f(x + dx, +y + k3);
return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;
}
function f(x, y) {
return x * Math.sqrt(y);
}
function actual(x) {
return (1/16) * (x*x+4)*(x*x+4);
}
var y = 1.0,
x = 0.0,
step = 0.1,
steps = 0,
maxSteps = 101,
sampleEveryN = 10;
while (steps < maxSteps) {
if (steps%sampleEveryN === 0) {
console.log("y(" + x + ") = \t" + y + "\t ± " + (actual(x) - y).toExponential());
}
y = rk4(y, x, step, f);
// using integer math for the step addition
// to prevent floating point errors as 0.2 + 0.1 != 0.3
x = ((x * 10) + (step * 10)) / 10;
steps += 1;
}
|
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
|
Rosetta Code/Find unimplemented tasks
|
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Maple
|
Maple
|
#Example with the Maple Language
lan := "Maple":
x := URL:-Get(cat("http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_", StringTools:-SubstituteAll(lan, " ", "_")), output = content):
x := StringTools:-StringSplit(x, "<h2><span class=\"mw-headline\" id=\"Not_implemented\">Not implemented</span>")[2]:
x := StringTools:-StringSplit(x, "<span class=\"mw-headline\" id=\"Draft_tasks_without_implementation\">Draft tasks without implementation</span>")[1]:
x := StringTools:-StringSplit(x,"<li><a href=\"/wiki/")[2..]:
for problem in x do
printf("%s\n", StringTools:-SubstituteAll(StringTools:-Decode(StringTools:-StringSplit(problem, "\" title=")[1], 'percent'), "_", " "));
end do:
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[ImportAll]
ImportAll[lang_String] :=
Module[{data, continue, cmcontinue, extra, xml, next},
data = {};
continue = True;
cmcontinue = "";
While[continue,
extra = If[cmcontinue =!= "", "&cmcontinue=" <> cmcontinue, ""];
xml = Import["http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:" <> lang <> "&cmlimit=500&format=xml" <> extra, "XML"];
AppendTo[data, Cases[xml, XMLElement["cm", _, {}], \[Infinity]]];
next = Flatten[Cases[xml, {"cmcontinue" -> _}, \[Infinity]]];
If[Length[next] > 0,
next = First[next];
cmcontinue = "cmcontinue" /. next;
,
continue = False;
];
];
Cases[Flatten[data], HoldPattern["title" -> x_] :> x, \[Infinity]]
]
Complement[ImportAll["Programming_Tasks"], ImportAll["Mathematica"]]
|
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.
|
#JavaScript
|
JavaScript
|
String.prototype.parseSexpr = function() {
var t = this.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g)
for (var o, c=0, i=t.length-1; i>=0; i--) {
var n, ti = t[i].trim()
if (ti == '"') return
else if (ti == '(') t[i]='[', c+=1
else if (ti == ')') t[i]=']', c-=1
else if ((n=+ti) == ti) t[i]=n
else t[i] = '\'' + ti.replace('\'', '\\\'') + '\''
if (i>0 && ti!=']' && t[i-1].trim()!='(' ) t.splice(i,0, ',')
if (!c) if (!o) o=true; else return
}
return c ? undefined : eval(t.join(''))
}
Array.prototype.toString = function() {
var s=''; for (var i=0, e=this.length; i<e; i++) s+=(s?' ':'')+this[i]
return '('+s+')'
}
Array.prototype.toPretty = function(s) {
if (!s) s = ''
var r = s + '(<br>'
var s2 = s + Array(6).join(' ')
for (var i=0, e=this.length; i<e; i+=1) {
var ai = this[i]
r += ai.constructor != Array ? s2+ai+'<br>' : ai.toPretty(s2)
}
return r + s + ')<br>'
}
var str = '((data "quoted data" 123 4.5)\n (data (!@# (4.5) "(more" "data)")))'
document.write('text:<br>', str.replace(/\n/g,'<br>').replace(/ /g,' '), '<br><br>')
var sexpr = str.parseSexpr()
if (sexpr === undefined)
document.write('Invalid s-expr!', '<br>')
else
document.write('s-expr:<br>', sexpr, '<br><br>', sexpr.constructor != Array ? '' : 'pretty print:<br>' + sexpr.toPretty())
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Sidef
|
Sidef
|
var langs = %w(ada cpp-qt pascal lscript z80 visualprolog
html4strict cil objc asm progress teraterm hq9plus genero tsql
email pic16 tcl apt_sources io apache vhdl avisynth winbatch
vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf
cobol powershell php kixtart visualfoxpro mirc make javascript
cpp sdlbasic cadlisp php-brief rails verilog xml csharp
actionscript nsis bash typoscript freebasic dot applescript
haskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec
ruby ocaml smarty python oracle11 caddcl robots groovy smalltalk
diff fortran cfm lua modula3 vb autoit java text scala
lotusformulas pixelbender reg _div whitespace providex asp css
lolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf
gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap
intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel
povray c gettext).join('|');
var text = ARGF.slurp;
text.gsub!(Regex.new('<(' + langs + ')>'), {|s1| "<lang #{s1}>" });
text.gsub!(Regex.new('</(' + langs + ')>'), "</" + "lang>");
text.gsub!(
Regex.new('<code\h+(' + langs + ')>(.*?)</code>', 's'),
{|s1,s2| "<lang #{s1}>#{s2}</" + "lang>"}
);
print text;
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “
n
{\displaystyle n}
” and “
e
{\displaystyle e}
” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “
d
{\displaystyle d}
” is kept secret, so that only the recipient can read the encrypted plaintext.
The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters
a
=
01
,
b
=
02
,
.
.
.
,
z
=
26
{\displaystyle a=01,b=02,...,z=26}
). This yields a string of numbers, generally referred to as "numerical plaintext", “
P
{\displaystyle P}
”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield
08051212152315181204
{\displaystyle 08051212152315181204}
.
The plaintext must also be split into blocks so that the numerical plaintext is smaller than
n
{\displaystyle n}
otherwise the decryption will fail.
The ciphertext,
C
{\displaystyle C}
, is then computed by taking each block of
P
{\displaystyle P}
, and computing
C
≡
P
e
mod
n
{\displaystyle C\equiv P^{e}\mod n}
Similarly, to decode, one computes
P
≡
C
d
mod
n
{\displaystyle P\equiv C^{d}\mod n}
To generate a key, one finds 2 (ideally large) primes
p
{\displaystyle p}
and
q
{\displaystyle q}
. the value “
n
{\displaystyle n}
” is simply:
n
=
p
×
q
{\displaystyle n=p\times q}
.
One must then choose an “
e
{\displaystyle e}
” such that
gcd
(
e
,
(
p
−
1
)
×
(
q
−
1
)
)
=
1
{\displaystyle \gcd(e,(p-1)\times (q-1))=1}
. That is to say,
e
{\displaystyle e}
and
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle (p-1)\times (q-1)}
are relatively prime to each other.
The decryption value
d
{\displaystyle d}
is then found by solving
d
×
e
≡
1
mod
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)}
The security of the code is based on the secrecy of the Private Key (decryption exponent) “
d
{\displaystyle d}
” and the difficulty in factoring “
n
{\displaystyle n}
”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes).
Summary of the task requirements:
Encrypt and Decrypt a short message or two using RSA with a demonstration key.
Implement RSA do not call a library.
Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine).
Either support blocking or give an error if the message would require blocking)
Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure:
n = 9516311845790656153499716760847001433441357
e = 65537
d = 5617843187844953170308463622230283376298685
Messages can be hard-coded into the program, there is no need for elaborate input coding.
Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
|
#zkl
|
zkl
|
var BN=Import.lib("zklBigNum");
n:=BN("9516311845790656153499716760847001433441357");
e:=BN("65537");
d:=BN("5617843187844953170308463622230283376298685");
const plaintext="Rossetta Code";
pt:=BN(Data(Int,0,plaintext)); // convert string (as stream of bytes) to big int
if(pt>n) throw(Exception.ValueError("Message is too large"));
println("Plain text: ",plaintext);
println("As Int: ",pt);
ct:=pt.powm(e,n); println("Encoded: ",ct);
pt =ct.powm(d,n); println("Decoded: ",pt);
txt:=pt.toData().text; // convert big int to bytes, treat as string
println("As String: ",txt);
|
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.
|
#Julia
|
Julia
|
roll_skip_lowest(dice, sides) = (r = rand(collect(1:sides), dice); sum(r) - minimum(r))
function rollRPGtoon()
attributes = zeros(Int, 6)
attsum = 0
gte15 = 0
while attsum < 75 || gte15 < 2
for i in 1:6
attributes[i] = roll_skip_lowest(4, 6)
end
attsum = sum(attributes)
gte15 = mapreduce(x -> x >= 15, +, attributes)
end
println("New RPG character roll: $attributes. Sum is $attsum, and $gte15 are >= 15.")
end
rollRPGtoon()
rollRPGtoon()
rollRPGtoon()
|
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
|
#S-BASIC
|
S-BASIC
|
comment
Find primes up to the specified limit (here 1,000) using
classic Sieve of Eratosthenes
end
$constant limit = 1000
$constant false = 0
$constant true = FFFFH
var i, k, count, col = integer
dim integer flags(limit)
print "Finding primes from 2 to";limit
rem - initialize table
for i = 1 to limit
flags(i) = true
next i
rem - sieve for primes
for i = 2 to int(sqr(limit))
if flags(i) = true then
for k = (i*i) to limit step i
flags(k) = false
next k
next i
rem - write out primes 10 per line
count = 0
col = 1
for i = 2 to limit
if flags(i) = true then
begin
print using "#####";i;
count = count + 1
col = col + 1
if col > 10 then
begin
print
col = 1
end
end
next i
print
print count; " primes were found."
end
|
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
|
Rosetta Code/Count examples
|
task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query
|
#Icon_and_Unicon
|
Icon and Unicon
|
$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500"
$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title="
$define RCUA "User-Agent: Unicon Rosetta 0.1"
$define RCXUA "X-Unicon: http://unicon.org/"
$define TASKTOT "* Total Tasks *"
$define TOTTOT "* Total Headers*"
link strings
link hexcvt
procedure main(A) # simple single threaded read all at once implementation
Tasks := table(0)
every task := taskNames() do {
Tasks[TASKTOT] +:= 1 # count tasks
every lang := languages(task) do { # count languages
Tasks[task] +:= 1
Tasks[TOTTOT] +:= 1
}
}
every insert(O := set(),key(Tasks)) # extract & sort keys
O := put(sort(O--set(TOTTOT,TASKTOT)),TASKTOT,TOTTOT) # move totals to end
every write(k := !O, " : ", Tasks[k]," examples.") # report
end
# Generate task names
procedure taskNames()
continue := ""
while \(txt := ReadURL(RCINDEX||continue)) do {
txt ? {
while tab(find("<cm ") & find(s :="title=\"")+*s) do
suspend tab(find("\""))\1
if tab(find("cmcontinue=")) then {
continue := "&"||tab(upto(' \t'))
}
else break
}
}
end
# Generate language headers in a task
procedure languages(task)
static WS
initial WS := ' \t'
page := ReadURL(RCTASK||CleanURI(task))
page ? while (tab(find("\n==")),tab(many(WS))|"",tab(find("{{"))) do {
header := tab(find("=="))
header ? {
while tab(find("{{header|")) do {
suspend 2(="{{header|",tab(find("}}")))\1
}
}
}
end
procedure CleanURI(u) #: clean up a URI
static tr,dxml # xml & http translation
initial {
tr := table()
every c := !string(~(&digits++&letters++'-_.!~*()/\'`')) do
tr[c] := "%"||hexstring(ord(c),2)
every /tr[c := !string(&cset)] := c
tr[" "] := "_" # wiki convention
every push(dxml := [],"&#"||right(ord(c := !"&<>'\""),3,"0")||";",c)
}
dxml[1] := u # insert URI as 1st arg
u := replacem!dxml # de-xml it
every (c := "") ||:= tr[!u] # reencode everything
c := replace(c,"%3E","'") # Hack to put single quotes back in
c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in
return c
end
procedure ReadURL(url) #: read URL into string
page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url)
text := ""
if page["Status-Code"] < 300 then while text ||:= reads(page,-1)
else write(&errout,image(url),": ",
page["Status-Code"]," ",page["Reason-Phrase"])
close(page)
return text
end
|
http://rosettacode.org/wiki/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
|
#JavaScript
|
JavaScript
|
var haystack = ['Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo']
var needles = ['Bush', 'Washington']
for (var i in needles) {
var found = false;
for (var j in haystack) {
if (haystack[j] == needles[i]) {
found = true;
break;
}
}
if (found)
print(needles[i] + " appears at index " + j + " in the haystack");
else
throw needles[i] + " does not appear in the 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.
|
#J
|
J
|
require 'web/gethttp xml/sax/x2j regex'
x2jclass 'rcPopLang'
rx =: (<0 1) {:: (2#a:) ,~ rxmatches rxfrom ]
'Popular Languages' x2jDefn
/ := langs : langs =: 0 2 $ a:
html/body/div/div/div/ul/li := langs =: langs ,^:(a:~:{.@[)~ lang ; ' \((\d+) members?\)' rx y
html/body/div/div/div/ul/li/a := lang =: '^\s*((?:.(?!User|Tasks|Omit|attention|operations|by))+)\s*$' rx y
)
cocurrent'base'
sortTab =. \: __ ". [: ;:^:_1: {:"1
formatTab =: [: ;:^:_1: [: (20 A. (<'-') , |. , [: ('.' <"1@:,.~ ":) 1 + 1 i.@,~ 1{$)&.|: sortTab f.
rcPopLangs =: formatTab@:process_rcPopLang_@:gethttp
|
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.
|
#11l
|
11l
|
V roman_values = [(‘I’, 1), (‘IV’, 4), (‘V’, 5), (‘IX’, 9), (‘X’, 10),
(‘XL’, 40), (‘L’, 50), (‘XC’, 90), (‘C’, 100),
(‘CD’, 400), (‘D’, 500), (‘CM’, 900), (‘M’, 1000)]
F roman_value(=roman)
V total = 0
L(symbol, value) reversed(:roman_values)
L roman.starts_with(symbol)
total += value
roman = roman[symbol.len..]
R total
L(value) [‘MCMXC’, ‘MMVIII’, ‘MDCLXVI’]
print(value‘ = ’roman_value(value))
|
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
|
#ALGOL_68
|
ALGOL 68
|
MODE DBL = LONG REAL;
FORMAT dbl = $g(-long real width, long real width-6, -2)$;
MODE XY = STRUCT(DBL x, y);
FORMAT xy root = $f(dbl)" ("b("Exactly", "Approximately")")"$;
MODE DBLOPT = UNION(DBL, VOID);
MODE XYRES = UNION(XY, VOID);
PROC find root = (PROC (DBL)DBL f, DBLOPT in x1, in x2, in x error, in y error)XYRES:(
INT limit = ENTIER (long real width / log(2)); # worst case of a binary search) #
DBL x1 := (in x1|(DBL x1):x1|-5.0), # if x1 is EMPTY then -5.0 #
x2 := (in x2|(DBL x2):x2|+5.0),
x error := (in x error|(DBL x error):x error|small real),
y error := (in y error|(DBL y error):y error|small real);
DBL y1 := f(x1), y2;
DBL dx := x1 - x2, dy;
IF y1 = 0 THEN
XY(x1, y1) # we already have a solution! #
ELSE
FOR i WHILE
y2 := f(x2);
IF y2 = 0 THEN stop iteration FI;
IF i = limit THEN value error FI;
IF y1 = y2 THEN value error FI;
dy := y1 - y2;
dx := dx / dy * y2;
x1 := x2; y1 := y2; # retain for next iteration #
x2 -:= dx;
# WHILE # ABS dx > x error AND ABS dy > y error DO
SKIP
OD;
stop iteration:
XY(x2, y2) EXIT
value error:
EMPTY
FI
);
PROC f = (DBL x)DBL: x UP 3 - LONG 3.1 * x UP 2 + LONG 2.0 * x;
DBL first root, second root, third root;
XYRES first result = find root(f, LENG -1.0, LENG 3.0, EMPTY, EMPTY);
CASE first result IN
(XY first result): (
printf(($"1st root found at x = "f(xy root)l$, x OF first result, y OF first result=0));
first root := x OF first result
)
OUT printf($"No first root found"l$); stop
ESAC;
XYRES second result = find root( (DBL x)DBL: f(x) / (x - first root), EMPTY, EMPTY, EMPTY, EMPTY);
CASE second result IN
(XY second result): (
printf(($"2nd root found at x = "f(xy root)l$, x OF second result, y OF second result=0));
second root := x OF second result
)
OUT printf($"No second root found"l$); stop
ESAC;
XYRES third result = find root( (DBL x)DBL: f(x) / (x - first root) / ( x - second root ), EMPTY, EMPTY, EMPTY, EMPTY);
CASE third result IN
(XY third result): (
printf(($"3rd root found at x = "f(xy root)l$, x OF third result, y OF third result=0));
third root := x OF third result
)
OUT printf($"No third root found"l$); stop
ESAC
|
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.
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <array>
#include <iterator>
#include <limits>
#include <tuple>
namespace detail_ {
// For constexpr digit<->number conversions.
constexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'};
// Helper function to encode a run-length.
template <typename OutputIterator>
constexpr auto encode_run_length(std::size_t n, OutputIterator out)
{
constexpr auto base = digits.size();
// Determine the number of digits needed.
auto const num_digits = [base](auto n)
{
auto d = std::size_t{1};
while ((n /= digits.size()))
++d;
return d;
}(n);
// Helper lambda to raise the base to an integer power.
auto base_power = [base](auto n)
{
auto res = decltype(base){1};
for (auto i = decltype(n){1}; i < n; ++i)
res *= base;
return res;
};
// From the most significant digit to the least, output the digit.
for (auto i = decltype(num_digits){0}; i < num_digits; ++i)
*out++ = digits[(n / base_power(num_digits - i)) % base];
return out;
}
// Helper function to decode a run-length.
// As of C++20, this can be constexpr, because std::find() is constexpr.
// Before C++20, it can be constexpr by emulating std::find().
template <typename InputIterator>
auto decode_run_length(InputIterator first, InputIterator last)
{
auto count = std::size_t{0};
while (first != last)
{
// If the next input character is not a digit, we're done.
auto const p = std::find(digits.begin(), digits.end(), *first);
if (p == digits.end())
break;
// Convert the digit to a number, and append it to the size.
count *= digits.size();
count += std::distance(digits.begin(), p);
// Move on to the next input character.
++first;
}
return std::tuple{count, first};
}
} // namespace detail_
template <typename InputIterator, typename OutputIterator>
constexpr auto encode(InputIterator first, InputIterator last, OutputIterator out)
{
while (first != last)
{
// Read the next value.
auto const value = *first++;
// Increase the count as long as the next value is the same.
auto count = std::size_t{1};
while (first != last && *first == value)
{
++count;
++first;
}
// Write the value and its run length.
out = detail_::encode_run_length(count, out);
*out++ = value;
}
return out;
}
// As of C++20, this can be constexpr, because std::find() and
// std::fill_n() are constexpr (and decode_run_length() can be
// constexpr, too).
// Before C++20, it can be constexpr by emulating std::find() and
// std::fill_n().
template <typename InputIterator, typename OutputIterator>
auto decode(InputIterator first, InputIterator last, OutputIterator out)
{
while (first != last)
{
using detail_::digits;
// Assume a run-length of 1, then try to decode the actual
// run-length, if any.
auto count = std::size_t{1};
if (std::find(digits.begin(), digits.end(), *first) != digits.end())
std::tie(count, first) = detail_::decode_run_length(first, last);
// Write the run.
out = std::fill_n(out, count, *first++);
}
return out;
}
template <typename Range, typename OutputIterator>
constexpr auto encode(Range&& range, OutputIterator out)
{
using std::begin;
using std::end;
return encode(begin(range), end(range), out);
}
template <typename Range, typename OutputIterator>
auto decode(Range&& range, OutputIterator out)
{
using std::begin;
using std::end;
return decode(begin(range), end(range), out);
}
// Sample application and checking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream>
#include <string_view>
int main()
{
using namespace std::literals;
constexpr auto test_string = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"sv;
std::cout << "Input: \"" << test_string << "\"\n";
std::cout << "Output: \"";
// No need for a temporary string - can encode directly to cout.
encode(test_string, std::ostreambuf_iterator<char>{std::cout});
std::cout << "\"\n";
auto encoded_str = std::string{};
auto decoded_str = std::string{};
encode(test_string, std::back_inserter(encoded_str));
decode(encoded_str, std::back_inserter(decoded_str));
std::cout.setf(std::cout.boolalpha);
std::cout << "Round trip works: " << (test_string == decoded_str) << '\n';
}
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#EchoLisp
|
EchoLisp
|
(define (roots-1 n)
(define theta (// (* 2 PI) n))
(for/list ((i n))
(polar 1. (* theta i))))
(roots-1 2)
→ (1+0i -1+0i)
(roots-1 3)
→ (1+0i -0.4999999999999998+0.8660254037844388i -0.5000000000000004-0.8660254037844384i)
(roots-1 4)
→ (1+0i 0+i -1+0i 0-i)
|
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.
|
#ERRE
|
ERRE
|
PROGRAM UNITY_ROOTS
!
! for rosettacode.org
!
BEGIN
PRINT(CHR$(12);) !CLS
N=5 ! this can be changed for any desired n
ANGLE=0 ! start at ANGLE 0
REPEAT
REAL=COS(ANGLE) ! real axis is the x axis
IF (ABS(REAL)<10^-5) THEN REAL=0 END IF ! get rid of annoying sci notation
IMAG=SIN(ANGLE) ! imaginary axis is the y axis
IF (ABS(IMAG)<10^-5) THEN IMAG=0 END IF ! get rid of annoying sci notation
PRINT(REAL;"+";IMAG;"i") ! answer on every line
ANGLE+=(2*π)/N
! all the way around the circle at even intervals
UNTIL ANGLE>=2*π
END PROGRAM
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
import Utils # To get the FindFirst class
procedure main()
keys := ["{{header|","<lang>"]
lang := "No language"
tags := table(0)
total := 0
ff := FindFirst(keys)
f := reads(&input, -1)
f ? while tab(ff.locate()) do {
if "{{header|" == 1(ff.getMatch(), ff.moveMatch()) then lang := map(tab(upto("}}")))
else (tags[lang] +:= 1, total +:= 1)
}
write(total," bare language tags:\n")
every pair := !sort(tags) do write(pair[2]," in ",pair[1])
end
|
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.
|
#Delphi
|
Delphi
|
defmodule Quadratic do
def roots(a, b, c) do
IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})"
d = b * b - 4 * a * c
a2 = a * 2
cond do
d > 0 ->
sd = :math.sqrt(d)
IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}"
d == 0 ->
IO.puts " the single root is #{- b / a2}"
true ->
sd = :math.sqrt(-d)
IO.puts " the complex roots are #{- b / a2} +/- #{sd / a2}*i"
end
end
end
Quadratic.roots(1, -2, 1)
Quadratic.roots(1, -3, 2)
Quadratic.roots(1, 0, 1)
Quadratic.roots(1, -1.0e10, 1)
Quadratic.roots(1, 2, 3)
Quadratic.roots(2, -1, -6)
|
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.
|
#Elixir
|
Elixir
|
defmodule Quadratic do
def roots(a, b, c) do
IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})"
d = b * b - 4 * a * c
a2 = a * 2
cond do
d > 0 ->
sd = :math.sqrt(d)
IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}"
d == 0 ->
IO.puts " the single root is #{- b / a2}"
true ->
sd = :math.sqrt(-d)
IO.puts " the complex roots are #{- b / a2} +/- #{sd / a2}*i"
end
end
end
Quadratic.roots(1, -2, 1)
Quadratic.roots(1, -3, 2)
Quadratic.roots(1, 0, 1)
Quadratic.roots(1, -1.0e10, 1)
Quadratic.roots(1, 2, 3)
Quadratic.roots(2, -1, -6)
|
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
|
#Batch_File
|
Batch File
|
@echo off & setlocal enabledelayedexpansion
:: ROT13 obfuscator Michael Sanders - 2017
::
:: example: rot13.cmd Rire abgvpr cflpuvpf arire jva gur ybggrel?
:setup
set str=%*
set buf=%str%
set len=0
:getlength
if not defined buf goto :start
set buf=%buf:~1%
set /a len+=1
goto :getlength
:start
if %len% leq 0 (echo rot13: zero length string & exit /b 1)
set abc=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
set nop=NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm
set r13=
set num=0
set /a len-=1
:rot13
for /l %%x in (!num!,1,%len%) do (
set log=0
for /l %%y in (0,1,51) do (
if "!str:~%%x,1!"=="!abc:~%%y,1!" (
call set r13=!r13!!nop:~%%y,1!
set /a num=%%x+1
set /a log+=1
if !num! lss %len% goto :rot13
)
)
if !log!==0 call set r13=!r13!!str:~%%x,1!
)
:done
echo !r13!
endlocal & exit /b 0
|
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 }
|
#jq
|
jq
|
def until(cond; next):
def _until: if cond then . else (next|_until) end;
_until;
def while(cond; update):
def _while: if cond then ., (update | _while) else empty end;
_while;
|
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
|
#Nim
|
Nim
|
import httpclient, strutils, xmltree, xmlparser, cgi, os
proc findrc(category: string): seq[string] =
var
name = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:$#&cmlimit=500&format=xml" % encodeUrl(category)
cmcontinue = ""
client = newHttpClient()
while true:
var x = client.getContent(name & cmcontinue).parseXml()
for node in x.findAll("cm"):
result.add node.attr("title")
cmcontinue.setLen(0)
for node in x.findAll("categorymembers"):
let u = node.attr("cmcontinue")
if u.len != 0: cmcontinue = u.encodeUrl()
if cmcontinue.len > 0: cmcontinue = "&cmcontinue=" & cmcontinue
else: break
proc chooselang(): string =
if paramCount() < 1: "Nim" else: paramStr(1)
let alltasks = findrc("Programming_Tasks")
let lang = chooselang()
let langTasks = lang.findrc()
echo "Unimplemented tasks for language ", lang, ':'
for task in alltasks:
if task notin langTasks:
echo " ", 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
|
#Oz
|
Oz
|
declare
[HTTPClient] = {Link ['x-ozlib://mesaros/net/HTTPClient.ozf']}
[XMLParser] = {Link ['x-oz://system/xml/Parser.ozf']}
fun {FindUnimplementedTasks Language}
AllTasks = {FindCategory "Programming Tasks"}
LangTasks = {FindCategory Language}
in
{ListDiff AllTasks LangTasks}
end
fun {FindCategory Cat}
CatUrl = "http://www.rosettacode.org/mw/api.php?action=query"
#"&list=categorymembers"
#"&cmtitle=Category:"#{PercentEncode Cat}
#"&cmlimit=500&format=xml"
fun {Loop CMContinue}
[_ Doc] = {Parse {GetPage CatUrl#CMContinue}}
Titles = {XPath Doc
[api query categorymembers cm {Attribute title}]}
in
case {XPath Doc
[api 'query-continue' categorymembers {Attribute cmcontinue}]}
of nil then Titles
[] [NewCMContinueAtom] then
NewCMContinue = {PercentEncode {Atom.toString NewCMContinueAtom}}
in
{Append Titles
{Loop "&cmcontinue="#NewCMContinue}}
end
end
in
{Loop nil}
end
%% XPath emulation
fun {XPath Doc Path}
P|Pr = Path
in
Doc.name = P %% assert
{FoldL Pr XPathStep [Doc]}
end
Nothing = {NewName}
fun {NotNothing X} X \= Nothing end
fun {XPathStep Elements P}
if {Atom.is P} then
{FilteredChildren Elements P}
elseif {Procedure.is P} then
{Filter {Map Elements P} NotNothing}
end
end
%% A flat list of all Type-children of all Elements.
fun {FilteredChildren Elements Type}
{Flatten
{Map Elements
fun {$ E}
{Filter E.children
fun {$ X}
case X of element(name:!Type ...) then true
else false
end
end}
end}}
end
fun {Attribute Attr}
fun {$ Element}
case {Filter Element.attributes fun {$ A} A.name == Attr end}
of [A] then A.value
else Nothing
end
end
end
%% GetPage
Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)}
fun {GetPage RawUrl}
Url = {VirtualString.toString RawUrl}
OutParams
in
{Client getService(Url ?OutParams ?_)}
OutParams.sOut
end
fun {PercentEncode Xs}
case Xs of nil then nil
[] X|Xr then
if {Char.isDigit X} orelse {Member X [&- &_ &. &~]}
orelse X >= &a andthen X =< &z
orelse X >= &z andthen X =< &Z then
X|{PercentEncode Xr}
else
{Append &%|{ToHex2 X} {PercentEncode Xr}}
end
end
end
fun {ToHex2 X}
[{ToHex1 X div 16} {ToHex1 X mod 16}]
end
fun {ToHex1 X}
if X >= 0 andthen X =< 9 then &0 + X
elseif X >= 10 andthen X =< 15 then &A + X - 10
end
end
%% Parse
local
Parser = {New XMLParser.parser init}
in
fun {Parse Xs} {Parser parseVS(Xs $)} end
end
fun {ListDiff Xs Ys}
{FoldL Ys List.subtract Xs}
end
in
%% show tasks not implemented in Oz
{ForAll {FindUnimplementedTasks "Oz"} System.showInfo}
|
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.
|
#Julia
|
Julia
|
function rewritequotedparen(s)
segments = split(s, "\"")
for i in 1:length(segments)
if i & 1 == 0 # even i
ret = replace(segments[i], r"\(", s"_O_PAREN")
segments[i] = replace(ret, r"\)", s"_C_PAREN")
end
end
join(segments, "\"")
end
function reconsdata(n, s)
if n > 1
print(" ")
end
if s isa String && ismatch(r"[\$\%\!\$\#]", s) == false
print("\"$s\"")
else
print(s)
end
end
function printAny(anyarr)
print("(")
for (i, el) in enumerate(anyarr)
if el isa Array
print("(")
for (j, el2) in enumerate(el)
if el2 isa Array
print("(")
for(k, el3) in enumerate(el2)
if el3 isa Array
print(" (")
for(n, el4) in enumerate(el3)
reconsdata(n, el4)
end
print(")")
else
reconsdata(k, el3)
end
end
print(")")
else
reconsdata(j, el2)
end
end
if i == 1
print(")\n ")
else
print(")")
end
end
end
println(")")
end
removewhitespace(s) = replace(replace(s, r"\n", " "), r"^\s*(\S.*\S)\s*$", s"\1")
quote3op(s) = replace(s, r"([\$\!\@\#\%]{3})", s"\"\1\"")
paren2bracket(s) = replace(replace(s, r"\(", s"["), r"\)", s"]")
data2symbol(s) = replace(s, "[data", "[:data")
unrewriteparens(s) = replace(replace(s, "_C_PAREN", ")"), "_O_PAREN", "(")
addcommas(s) = replace(replace(s, r"\]\s*\[", "],["), r" (?![a-z])", ",")
inputstring = """
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
"""
println("The input string is:\n", inputstring)
processed = (inputstring |> removewhitespace |> rewritequotedparen |> quote3op
|> paren2bracket |> data2symbol |> unrewriteparens |> addcommas)
nat = eval(parse("""$processed"""))
println("The processed native structure is:\n", nat)
println("The reconstructed string is:\n"), printAny(nat)
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Tcl
|
Tcl
|
set langs {
ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm
hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet
ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart
visualfoxpro mirc make javascript cpp sdlbasic cadlisp php-brief rails verilog xml
csharp actionscript nsis bash typoscript freebasic dot applescript haskell dos oracle8
cfdg glsl lotusscript mpasm latex sql klonec ruby ocaml smarty python oracle11 caddcl
robots groovy smalltalk diff fortran cfm lua modula3 vb autoit java text scala lotusformulas
pixelbender reg _div whitespace providex asp css lolcode lisp inno mysql plsql matlab
oobas vim delphi xorg_conf gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl
abap intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel povray c gettext
}
set text [read stdin]
set slang /lang
foreach lang $langs {
set text [regsub -all "<$lang>" $text "<lang $lang>"]
set text [regsub -all "</$lang>" $text "<$slang>"]
}
set text [regsub -all "<code (.+?)>(.+?)</code>" $text "<lang \\1>\\2<$slang>"]
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#Wren
|
Wren
|
import "./pattern" for Pattern
var source = """
Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem
atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>,
ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu
altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel</bar>.
Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>. Eam volumus perpetua
constituto id, mea an omittam fierent vituperatoribus.
"""
// to avoid problems dispaying code on RC
var entag = Fn.new { |s| "<%(s)>" }
var langs = ["foo", "bar", "baz"] // in principle these can be anything
for (lang in langs) {
var s = "[%(lang)]"
var pairs = [
["<%(s)>", entag.call("lang $1")],
["<//%(s)>", entag.call("/lang")],
["<code %(s)>", entag.call("lang $1")],
["<//code>", entag.call("/lang")]
]
for (pair in pairs) {
var p = Pattern.new(pair[0])
source = p.replaceAll(source, pair[1])
}
}
System.print(source)
|
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.
|
#Kotlin
|
Kotlin
|
import kotlin.random.Random
fun main() {
while (true) {
val values = List(6) {
val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4)
rolls.sorted().take(3).sum()
}
val vsum = values.sum()
val vcount = values.count { it >= 15 }
if (vsum < 75 || vcount < 2) continue
println("The 6 random numbers generated are: $values")
println("Their sum is $vsum and $vcount of them are >= 15")
break
}
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#SAS
|
SAS
|
proc iml;
start sieve(n);
a = J(n,1);
a[1] = 0;
do i = 1 to n;
if a[i] then do;
if i*i>n then return(a);
a[i*(i:int(n/i))] = 0;
end;
end;
finish;
a = loc(sieve(1000))`;
create primes from a;
append from a;
close primes;
quit;
|
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
|
#J
|
J
|
require 'web/gethttp'
getAllTaskSolnCounts=: monad define
tasks=. getCategoryMembers 'Programming_Tasks'
counts=. getTaskSolnCounts &> tasks
tasks;counts
)
getTaskSolnCounts=: monad define
makeuri=. 'http://www.rosettacode.org/w/index.php?title=' , ,&'&action=raw'
wikidata=. gethttp makeuri urlencode y
([: +/ '{{header|'&E.) wikidata
)
formatSolnCounts=: monad define
'tasks counts'=. y
tasks=. tasks , &.>':'
res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.'
res , 'Total examples: ' , ": +/counts
)
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#jq
|
jq
|
["a","b","c"] | index("b")
# => 1
["a","b","c","b"] | index("b")
# => 1
["a","b","c","b"]
| index("x") // error("element not found")
# => jq: error: element not found
# Extra task - the last element of an array can be retrieved
# using `rindex/` or by using -1 as an index into the array produced by `indices/1`:
["a","b","c","b","d"] | rindex("b")
# => 3
["a","b","c","b","d"] | indices("b")[-1]
# => 3
|
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.
|
#Java
|
Java
|
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
// Custom sort Comparator for sorting the language list
// assumes the first character is the page count and the rest is the language name
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
// as we "know" we will be comparaing languages, we will assume the Strings have the appropriate format
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
// the counts are the same - compare the names
result = a.compareTo( b );
} // if result == 0
return result;
} // compare
} // LanguageComparator
// get the string following marker in text
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
// the marker is in the string
result = text.substring( pos + 1 );
} // if pos >= 0
return result;
} // after
// read and parse the content of path
// results returned in gcmcontinue and languageList
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
// Rosetta Code objects to the default Java user agant so use a blank one
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
// have a programming language - should look like "[title] => Category:languageName"
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
// number of pages the language has (probably)
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
// haven't got "[pages] => Array" - must be a number of pages
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
} // if [pageCount.compareTo( "Array" ) != 0
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
// have an indication of wether there is more data or not
gcmcontinue[0] = after( line, '>' ).trim();
} // if various line starts
line = bfr.readLine();
} // while line != null
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
} // try-catch
} // parseContent
public static void main( String[] args )
{
// get the languages
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http://www.rosettacode.org/mw/api.php?action=query"
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
// sort the languages
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
// print the languages
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
} // if count != lastCount
} // for lPos
} // main
} // GetRCLanguages
|
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.
|
#360_Assembly
|
360 Assembly
|
* Roman numerals Decode - 17/04/2019
ROMADEC CSECT
USING ROMADEC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(NV)) do i=1 to hbound(vals)
LR R1,R6 i
SLA R1,3 ~
LA R4,VALS-L'VALS(R1) @vals(i)
MVC X,0(R4) x=vals(i)
SR R9,R9 prev=0
ST R9,Y y=0
LA R7,L'X j=1
DO WHILE=(C,R7,GE,=A(1)) do j=length(x) to 1 by -1
LA R4,X-1 @x
AR R4,R7 +j
MVC C,0(R4) c=substr(x,j,1)
IF CLI,C,NE,C' ' THEN if c^=' ' then
SR R1,R1 r1=0
LA R2,1 k=1
DO WHILE=(C,R2,LE,=A(L'ROMAN)) do k=1 to length(roman)
LA R3,ROMAN-1 @roman
AR R3,R2 +k
IF CLC,0(L'C,R3),EQ,C THEN if substr(roman,k,1)=c
LR R1,R2 index=k
B REINDEX leave k
ENDIF , endif
LA R2,1(R2) k=k+1
ENDDO , enddo k
REINDEX EQU * r1=index(roman,c)
SLA R1,2 ~
L R8,DECIM-4(R1) n=decim(index(roman,c))
IF CR,R8,LT,R9 THEN if n<prev then
LCR R8,R8 n=-n
ENDIF , endif
L R2,Y y
AR R2,R8 +n
ST R2,Y y=y+n
LR R9,R8 prev=n
ENDIF , endif
BCTR R7,0 j--
ENDDO , enddo j
MVC PG(8),X x
L R1,Y y
XDECO R1,XDEC edit y
MVC PG+12(4),XDEC+8 output y
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
NV EQU (X-VALS)/L'VALS
ROMAN DC CL7'MDCLXVI'
DECIM DC F'1000',F'500',F'100',F'50',F'10',F'5',F'1'
VALS DC CL8'XIV',CL8'CMI',CL8'MIC',CL8'MCMXC',CL8'MDCLXVI'
DC CL8'MMVIII',CL8'MMXIX',CL8'MMMCMXCV'
X DS CL(L'VALS)
Y DS F
C DS CL1
PG DC CL80'........ -> ....'
XDEC DS CL12
REGEQU
END ROMADEC
|
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
|
#ATS
|
ATS
|
#include
"share/atspre_staload.hats"
typedef d = double
fun
findRoots
(
start: d, stop: d, step: d, f: (d) -> d, nrts: int, A: d
) : void = (
//
if
start < stop
then let
val A2 = f(start)
var nrts: int = nrts
val () =
if A2 = 0.0
then (
nrts := nrts + 1;
$extfcall(void, "printf", "An exact root is found at %12.9f\n", start)
) (* end of [then] *)
// end of [if]
val () =
if A * A2 < 0.0
then (
nrts := nrts + 1;
$extfcall(void, "printf", "An approximate root is found at %12.9f\n", start)
) (* end of [then] *)
// end of [if]
in
findRoots(start+step, stop, step, f, nrts, A2)
end // end of [then]
else (
if nrts = 0
then $extfcall(void, "printf", "There are no roots found!\n")
// end of [if]
) (* end of [else] *)
//
) (* end of [findRoots] *)
(* ****** ****** *)
implement
main0 () =
findRoots (~1.0, 3.0, 0.001, lam (x) => x*x*x - 3.0*x*x + 2.0*x, 0, 0.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.
|
#11l
|
11l
|
V rules = [‘rock’ = ‘paper’, ‘scissors’ = ‘rock’, ‘paper’ = ‘scissors’]
V previous = [‘rock’, ‘paper’, ‘scissors’]
L
V human = input("\nchoose your weapon: ")
V computer = rules[random:choice(previous)]
I human C (‘quit’, ‘exit’)
L.break
E I human C rules
previous.append(human)
print(‘the computer played ’computer, end' ‘; ’)
I rules[computer] == human
print(‘yay you win!’)
E I rules[human] == computer
print(‘the computer beat you... :(’)
E
print(‘it's a tie!’)
E
print(‘that's not a valid choice’)
|
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.
|
#Ceylon
|
Ceylon
|
shared void run() {
"Takes a string such as aaaabbbbbbcc and returns 4a6b2c"
String compress(String string) {
if (exists firstChar = string.first) {
if (exists index = string.firstIndexWhere((char) => char != firstChar)) {
return "``index````firstChar````compress(string[index...])``";
}
else {
return "``string.size````firstChar``";
}
}
else {
return "";
}
}
"Takes a string such as 4a6b2c and returns aaaabbbbbbcc"
String decompress(String string) =>
let (runs = string.split(Character.letter, false).paired)
"".join {
for ([length, char] in runs)
if (is Integer int = Integer.parse(length))
char.repeat(int)
};
assert (compress("aaaabbbbbaa") == "4a5b2a");
assert (decompress("4a6b2c") == "aaaabbbbbbcc");
assert (compress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") == "12W1B12W3B24W1B14W");
assert (decompress("24a") == "aaaaaaaaaaaaaaaaaaaaaaaa");
}
|
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.
|
#Factor
|
Factor
|
USING: math.functions prettyprint ;
1 3 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.
|
#Forth
|
Forth
|
: f0. ( f -- )
fdup 0e 0.001e f~ if fdrop 0e then f. ;
: .roots ( n -- )
dup 1 do
pi i 2* 0 d>f f* dup 0 d>f f/ ( F: radians )
fsincos cr ." real " f0. ." imag " f0.
loop drop ;
3 set-precision
5 .roots
|
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.
|
#Java
|
Java
|
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FindBareTags {
private static final String BASE = "http://rosettacode.org";
private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"");
private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==");
private static final Predicate<String> BARE_PREDICATE = Pattern.compile("<lang>").asPredicate();
public static void main(String[] args) throws Exception {
var client = HttpClient.newBuilder().build();
URI titleUri = URI.create(BASE + "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks");
var titleRequest = HttpRequest.newBuilder(titleUri).GET().build();
var titleResponse = client.send(titleRequest, HttpResponse.BodyHandlers.ofString());
if (titleResponse.statusCode() == 200) {
var titleBody = titleResponse.body();
var titleMatcher = TITLE_PATTERN.matcher(titleBody);
var titleList = titleMatcher.results().map(mr -> mr.group(1)).collect(Collectors.toList());
var countMap = new HashMap<String, Integer>();
for (String title : titleList) {
var pageUri = new URI("http", null, "//rosettacode.org/wiki", "action=raw&title=" + title, null);
var pageRequest = HttpRequest.newBuilder(pageUri).GET().build();
var pageResponse = client.send(pageRequest, HttpResponse.BodyHandlers.ofString());
if (pageResponse.statusCode() == 200) {
var pageBody = pageResponse.body();
AtomicReference<String> language = new AtomicReference<>("no language");
pageBody.lines().forEach(line -> {
var headerMatcher = HEADER_PATTERN.matcher(line);
if (headerMatcher.matches()) {
language.set(headerMatcher.group(1));
} else if (BARE_PREDICATE.test(line)) {
int count = countMap.getOrDefault(language.get(), 0) + 1;
countMap.put(language.get(), count);
}
});
} else {
System.out.printf("Got a %d status code%n", pageResponse.statusCode());
}
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
System.out.printf("%d in %s%n", entry.getValue(), entry.getKey());
}
} else {
System.out.printf("Got a %d status code%n", titleResponse.statusCode());
}
}
}
|
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.
|
#ERRE
|
ERRE
|
PROGRAM QUADRATIC
PROCEDURE SOLVE_QUADRATIC
D=B*B-4*A*C
IF ABS(D)<1D-6 THEN D=0 END IF
CASE SGN(D) OF
0->
PRINT("the single root is ";-B/2/A)
END ->
1->
F=(1+SQR(1-4*A*C/(B*B)))/2
PRINT("the real roots are ";-F*B/A;"and ";-C/B/F)
END ->
-1->
PRINT("the complex roots are ";-B/2/A;"+/-";SQR(-D)/2/A;"*i")
END ->
END CASE
END PROCEDURE
BEGIN
PRINT(CHR$(12);) ! CLS
FOR TEST%=1 TO 7 DO
READ(A,B,C)
PRINT("For a=";A;",b=";B;",c=";C;TAB(32);)
SOLVE_QUADRATIC
END FOR
DATA(1,-1E9,1)
DATA(1,0,1)
DATA(2,-1,-6)
DATA(1,2,-2)
DATA(0.5,1.4142135,1)
DATA(1,3,2)
DATA(3,4,5)
END PROGRAM
|
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.
|
#Factor
|
Factor
|
:: quadratic-equation ( a b c -- x1 x2 )
b sq a c * 4 * - sqrt :> sd
b 0 <
[ b neg sd + a 2 * / ]
[ b neg sd - a 2 * / ] if :> x
x c a x * / ;
|
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
|
#BBC_BASIC
|
BBC BASIC
|
REPEAT
INPUT A$
PRINT FNrot13(A$)
UNTIL FALSE
END
DEF FNrot13(A$)
LOCAL A%,B$,C$
IF A$="" THEN =""
FOR A%=1 TO LEN A$
C$=MID$(A$,A%,1)
IF C$<"A" OR (C$>"Z" AND C$<"a") OR C$>"z" THEN
B$=B$+C$
ELSE
IF (ASC(C$) AND &DF)<ASC("N") THEN
B$=B$+CHR$(ASC(C$)+13)
ELSE
B$=B$+CHR$(ASC(C$)-13)
ENDIF
ENDIF
NEXT A%
=B$
|
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 }
|
#Julia
|
Julia
|
f(x, y) = x * sqrt(y)
theoric(t) = (t ^ 2 + 4.0) ^ 2 / 16.0
rk4(f) = (t, y, δt) -> # 1st (result) lambda
((δy1) -> # 2nd lambda
((δy2) -> # 3rd lambda
((δy3) -> # 4th lambda
((δy4) -> ( δy1 + 2δy2 + 2δy3 + δy4 ) / 6 # 5th and deepest lambda: calc y_{n+1}
)(δt * f(t + δt, y + δy3)) # calc δy₄
)(δt * f(t + δt / 2, y + δy2 / 2)) # calc δy₃
)(δt * f(t + δt / 2, y + δy1 / 2)) # calc δy₂
)(δt * f(t, y)) # calc δy₁
δy = rk4(f)
t₀, δt, tmax = 0.0, 0.1, 10.0
y₀ = 1.0
t, y = t₀, y₀
while t ≤ tmax
if t ≈ round(t) @printf("y(%4.1f) = %10.6f\terror: %12.6e\n", t, y, abs(y - theoric(t))) end
y += δy(t, y, δt)
t += δt
end
|
http://rosettacode.org/wiki/Runge-Kutta_method
|
Runge-Kutta method
|
Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
y
(
t
)
=
1
16
(
t
2
+
4
)
2
{\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}}
Task
Demonstrate the commonly used explicit fourth-order Runge–Kutta method to solve the above differential equation.
Solve the given differential equation over the range
t
=
0
…
10
{\displaystyle t=0\ldots 10}
with a step value of
δ
t
=
0.1
{\displaystyle \delta t=0.1}
(101 total points, the first being given)
Print the calculated values of
y
{\displaystyle y}
at whole numbered
t
{\displaystyle t}
's (
0.0
,
1.0
,
…
10.0
{\displaystyle 0.0,1.0,\ldots 10.0}
) along with error as compared to the exact solution.
Method summary
Starting with a given
y
n
{\displaystyle y_{n}}
and
t
n
{\displaystyle t_{n}}
calculate:
δ
y
1
=
δ
t
×
y
′
(
t
n
,
y
n
)
{\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad }
δ
y
2
=
δ
t
×
y
′
(
t
n
+
1
2
δ
t
,
y
n
+
1
2
δ
y
1
)
{\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})}
δ
y
3
=
δ
t
×
y
′
(
t
n
+
1
2
δ
t
,
y
n
+
1
2
δ
y
2
)
{\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})}
δ
y
4
=
δ
t
×
y
′
(
t
n
+
δ
t
,
y
n
+
δ
y
3
)
{\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad }
then:
y
n
+
1
=
y
n
+
1
6
(
δ
y
1
+
2
δ
y
2
+
2
δ
y
3
+
δ
y
4
)
{\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})}
t
n
+
1
=
t
n
+
δ
t
{\displaystyle t_{n+1}=t_{n}+\delta t\quad }
|
#Kotlin
|
Kotlin
|
// version 1.1.2
typealias Y = (Double) -> Double
typealias Yd = (Double, Double) -> Double
fun rungeKutta4(t0: Double, tz: Double, dt: Double, y: Y, yd: Yd) {
var tn = t0
var yn = y(tn)
val z = ((tz - t0) / dt).toInt()
for (i in 0..z) {
if (i % 10 == 0) {
val exact = y(tn)
val error = yn - exact
println("%4.1f %10f %10f %9f".format(tn, yn, exact, error))
}
if (i == z) break
val dy1 = dt * yd(tn, yn)
val dy2 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy1)
val dy3 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy2)
val dy4 = dt * yd(tn + dt, yn + dy3)
yn += (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0
tn += dt
}
}
fun main(args: Array<String>) {
println(" T RK4 Exact Error")
println("---- ---------- ---------- ---------")
val y = fun(t: Double): Double {
val x = t * t + 4.0
return x * x / 16.0
}
val yd = fun(t: Double, yt: Double) = t * Math.sqrt(yt)
rungeKutta4(0.0, 10.0, 0.1, y, yd)
}
|
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
|
#Perl
|
Perl
|
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent('');
sub enc { join '', map {sprintf '%%%02x', ord} split //, shift }
sub get { $ua->request( HTTP::Request->new( GET => shift))->content }
sub tasks {
my($category) = shift;
my $fmt = 'http://www.rosettacode.org/mw/api.php?' .
'action=query&generator=categorymembers&gcmtitle=Category:%s&gcmlimit=500&format=json&rawcontinue=';
my @tasks;
my $json = get(sprintf $fmt, $category);
while (1) {
push @tasks, $json =~ /"title":"(.+?)"\}/g;
$json =~ /"gcmcontinue":"(.+?)"\}/ or last;
$json = get(sprintf $fmt . '&gcmcontinue=%s', $category, enc $1);
}
@tasks;
}
my %language = map {$_, 1} tasks shift || 'perl';
$language{$_} or print "$_\n" foreach tasks('Programming_Tasks'), tasks('Draft_Programming_Tasks');
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.2.31
const val INDENT = 2
fun String.parseSExpr(): List<String>? {
val r = Regex("""\s*("[^"]*"|\(|\)|"|[^\s()"]+)""")
val t = r.findAll(this).map { it.value }.toMutableList()
if (t.size == 0) return null
var o = false
var c = 0
for (i in t.size - 1 downTo 0) {
val ti = t[i].trim()
val nd = ti.toDoubleOrNull()
if (ti == "\"") return null
if (ti == "(") {
t[i] = "["
c++
}
else if (ti == ")") {
t[i] = "]"
c--
}
else if (nd != null) {
val ni = ti.toIntOrNull()
if (ni != null) t[i] = ni.toString()
else t[i] = nd.toString()
}
else if (ti.startsWith("\"")) { // escape embedded double quotes
var temp = ti.drop(1).dropLast(1)
t[i] = "\"" + temp.replace("\"", "\\\"") + "\""
}
if (i > 0 && t[i] != "]" && t[i - 1].trim() != "(") t.add(i, ", ")
if (c == 0) {
if (!o) o = true else return null
}
}
return if (c != 0) null else t
}
fun MutableList<String>.toSExpr(): String {
for (i in 0 until this.size) {
this[i] = when (this[i]) {
"[" -> "("
"]" -> ")"
", " -> " "
else -> {
if (this[i].startsWith("\"")) { // unescape embedded quotes
var temp = this[i].drop(1).dropLast(1)
"\"" + temp.replace("\\\"", "\"") + "\""
}
else this[i]
}
}
}
return this.joinToString("")
}
fun List<String>.prettyPrint() {
var level = 0
loop@for (t in this) {
var n: Int
when(t) {
", ", " " -> continue@loop
"[", "(" -> {
n = level * INDENT + 1
level++
}
"]", ")" -> {
level--
n = level * INDENT + 1
}
else -> {
n = level * INDENT + t.length
}
}
println("%${n}s".format(t))
}
}
fun main(args: Array<String>) {
val str = """((data "quoted data" 123 4.5)""" + "\n" +
""" (data (!@# (4.5) "(more" "data)")))"""
val tokens = str.parseSExpr()
if (tokens == null)
println("Invalid s-expr!")
else {
println("Native data structure:")
println(tokens.joinToString(""))
println("\nNative data structure (pretty print):")
tokens.prettyPrint()
val tokens2 = tokens.toMutableList()
println("\nRecovered S-Expression:")
println(tokens2.toSExpr())
println("\nRecovered S-Expression (pretty print):")
tokens2.prettyPrint()
}
}
|
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
|
Rosetta Code/Fix code tags
|
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
|
#zkl
|
zkl
|
fcn replace(data,src,dstpat){
re,n,buf:=RegExp(src),0,Data();
while(re.search(data,True,n)){
matched:=re.matched; // L(L(12,3),"c")
data[matched[0].xplode()]=re.sub(data,dstpat,buf); // "\1" --> "c"
n=matched[0].sum(0); // move past change
}
}
data:=File.stdin.read();
foreach src,dst in (T(
T(0'|<(\w+)>|, 0'|<lang \1>|), T(0'|</(\w+)>|,"</" "lang>"),
T(0'|<code (\w+)>|,0'|<lang \1>|) )){
replace(data,src,dst)
}
print(data.text);
|
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.
|
#Ksh
|
Ksh
|
#!/bin/ksh
# RPG attributes generator
# # Variables:
#
typeset -a attribs=( strength dexterity constitution intelligence wisdom charisma )
integer MINTOT=75 MIN15S=2
# # Functions:
#
# # Function _diceroll(sides, number, reportAs) - roll number of side-sided
# # dice, report (s)sum or (a)array (pseudo) of results
#
function _diceroll {
typeset _sides ; integer _sides=$1 # Number of sides of dice
typeset _numDice ; integer _numDice=$2 # Number of dice to roll
typeset _rep ; typeset -l -L1 _rep="$3" # Report type: (sum || array)
typeset _seed ; (( _seed = SECONDS / $$ )) ; _seed=${_seed#*\.}
typeset _i _sum ; integer _i _sum=0
typeset _arr ; typeset -a _arr
RANDOM=${_seed}
for (( _i=0; _i<_numDice; _i++ )); do
(( _arr[_i] = (RANDOM % _sides) + 1 ))
[[ ${_rep} == s ]] && (( _sum += _arr[_i] ))
done
if [[ ${_rep} == s ]]; then
echo ${_sum}
else
echo "${_arr[@]}"
fi
}
# # Function _sumarr(n arr) - Return the sum of the first n arr elements
#
function _sumarr {
typeset _n ; integer _n=$1
typeset _arr ; nameref _arr="$2"
typeset _i _sum ; integer _i _sum
for ((_i=0; _i<_n; _i++)); do
(( _sum+=_arr[_i] ))
done
echo ${_sum}
}
######
# main #
######
until (( total >= MINTOT )) && (( cnt15 >= MIN15S )); do
integer total=0 cnt15=0
unset attrval ; typeset -A attrval
for attr in ${attribs[*]}; do
unset darr ; typeset -a darr=( $(_diceroll 6 4 a) )
set -sK:nr -A darr
attrval[${attr}]=$(_sumarr 3 darr)
(( total += attrval[${attr}] ))
(( attrval[${attr}] > 14 )) && (( cnt15++ ))
done
done
for attr in ${attribs[*]}; do
printf "%12s: %2d\n" ${attr} ${attrval[${attr}]}
done
print "Attribute value total: ${total}"
print "Attribule count >= 15: ${cnt15}"
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
valid = False;
While[! valid,
try = Map[Total[TakeLargest[#, 3]] &,
RandomInteger[{1, 6}, {6, 4}]];
If[Total[try] > 75 && Count[try, _?(GreaterEqualThan[15])] >= 2,
valid = True;
]
]
{Total[try], try}
|
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
|
#SASL
|
SASL
|
show primes
WHERE
primes = sieve (2...)
sieve (p : x ) = p : sieve {a <- x; a REM p > 0}
?
|
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
|
#Java
|
Java
|
import java.util.ArrayList;
import ScreenScrape;
public class CountProgramExamples {
private static final String baseURL = "http://rosettacode.org/wiki/";
private static final String rootURL = "http://www.rosettacode.org/w/"
+ "api.php?action=query&list=categorymembers"
+ "&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";
private static final String taskBegin = "title=\"";
private static final String taskEnd = "\"";
private static final String exmplBegin = "<span class=\"tocnumber\">";
private static final String exmplEnd = "</span>";
private static final String editBegin = "<span class=\"editsection\">";
/**
* @param args
*/
public static void main(String[] args) {
int exTotal = 0;
try {
// Get root query results
ArrayList<String> tasks = new ArrayList<String>();
ScreenScrape ss = new ScreenScrape();
String rootPage = ss.read(rootURL);
while (rootPage.contains(taskBegin)) {
rootPage = rootPage.substring(rootPage.indexOf(taskBegin)
+ taskBegin.length());
String title = rootPage.substring(0, rootPage.indexOf(taskEnd));
if (!title.contains("Category:")) {
tasks.add(title);
}
rootPage = rootPage.substring(rootPage.indexOf(taskEnd));
}
// Loop through each task and print count
for (String task : tasks) {
String title = task.replaceAll("'", "'");
String taskPage = ss.read(baseURL + title.replaceAll(" ", "_"));
int exSubTot;
if (taskPage.contains(exmplBegin)) {
int startPos = taskPage.lastIndexOf(exmplBegin)
+ exmplBegin.length();
String countStr = taskPage.substring(startPos,
taskPage.indexOf(exmplEnd, startPos));
exSubTot = Integer
.parseInt(countStr.contains(".") ? countStr
.substring(0, countStr.indexOf("."))
: countStr);
} else {
exSubTot = 0;
while (taskPage.contains(editBegin)) {
taskPage = taskPage.substring(taskPage
.indexOf(editBegin) + editBegin.length());
exSubTot++;
}
}
exTotal += exSubTot;
System.out.println(title + ": " + exSubTot + " examples.");
}
// Print total
System.out.println("\nTotal: " + exTotal + " examples.");
} catch (Exception e) {
System.out.println(title);
System.out.println(startPos + ":"
+ taskPage.indexOf(exmplEnd, startPos));
System.out.println(taskPage);
e.printStackTrace(System.out);
}
}
}
|
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
|
#Julia
|
Julia
|
@show findfirst(["no", "?", "yes", "maybe", "yes"], "yes")
@show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"])
@show findin(["no", "?", "yes", "maybe", "yes"], ["yes"])
@show find(["no", "?", "yes", "maybe", "yes"] .== "yes")
|
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.
|
#jq
|
jq
|
#!/bin/bash
# produce lines of the form: [ "language", n ]
function categories {
curl -Ss 'http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000' |\
grep "/wiki/Category:" | grep member | grep -v '(.*(' |\
grep -v ' User</a>' |\
sed -e 's/.*title="Category://' -e 's/member.*//' |\
sed 's:^\([^"]*\)"[^(]*(\(.*\):["\1", \2]:'
}
# produce lines of the form: "language"
function languages {
curl -Ss 'http://rosettacode.org/wiki/Category:Programming_Languages' |\
sed '/Pages in category "Programming Languages"/,$d' |\
grep '<li><a href="/wiki/Category:' | fgrep title= |\
sed 's/.*Category:\([^"]*\)".*/"\1"/'
}
categories |\
/usr/local/bin/jq --argfile languages <(languages) -s -r '
# input: array of [score, _] sorted by score
# output: array of [ranking, score, _]
def ranking:
reduce .[] as $x
([]; # array of [count, rank, score, _]
if length == 0 then [[1, 1] + $x]
else .[length - 1] as $previous
| if $x[0] == $previous[2]
then . + [ [$previous[0] + 1, $previous[1]] + $x ]
else . + [ [$previous[0] + 1, $previous[0] + 1] + $x ]
end
end)
| [ .[] | .[1:] ];
# Every language page has three category pages that should be excluded
(reduce .[] as $pair
({};
($pair[1] as $n | if $n > 3 then . + {($pair[0]): ($n - 3)} else . end ))) as $freq
| [ $languages[] | select($freq[.] != null) | [$freq[.], .]]
| sort
| reverse
| ranking[]
| "\(.[0]). \(.[1]) - \(.[2])" '
|
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
|
#11l
|
11l
|
V anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
V rnums = ‘M CM D CD C XC L XL X IX V IV I’.split(‘ ’)
F to_roman(=x)
V ret = ‘’
L(a, r) zip(:anums, :rnums)
(V n, x) = divmod(x, a)
ret ‘’= r * n
R ret
V test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 40,
50, 60, 69, 70, 80, 90, 99, 100, 200, 300, 400, 500, 600, 666, 700, 800, 900, 1000,
1009, 1444, 1666, 1945, 1997, 1999, 2000, 2008, 2010, 2011, 2500, 3000, 3999]
L(val) test
print(val‘ - ’to_roman(val))
|
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.
|
#8080_Assembly
|
8080 Assembly
|
org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes a zero-terminated Roman numeral string in BC
;; and returns 16-bit integer in HL.
;; All registers destroyed.
roman: dcx b
romanfindend: inx b ; load next character
ldax b
inr e
ana a ; are we there yet
jnz romanfindend
lxi h,0 ; zero HL to hold the total
push h ; stack holds the previous roman numeral
romanloop: dcx b ; get next roman numeral
ldax b ; (work backwards)
call romandgt
jc romandone ; carry set = not Roman anymore
xthl ; load previous roman numeral
call cmpdehl ; DE < HL?
mov h,d ; in any case, DE is now the previous
mov l,e ; Roman numeral
xthl ; bring back the total
jnc romanadd
mov a,d ; DE (current) < HL (previous)
cma ; so this Roman digit must be subtracted
mov d,a ; from the total.
mov a,e ; so we negate it before adding it
cma ; two's complement: -de = (~de)+1
mov e,a
inx d
romanadd: dad d ; add to running total
jmp romanloop
romandone: pop d ; remove temporary variable from stack
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 16-bit compare DE with HL, set flags
;; accordingly. A destroyed.
cmpdehl: mov a,d
cmp h
rnz
mov a,e
cmp l
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes a single Roman 'digit' in A,
;; and returns its value in DE (0 if invalid)
;; All other registers preserved.
romandgt: push h ; preserve hl for the caller
lxi h,romantab
mvi e,7 ; e=counter
romandgtl: cmp m ; check table entry
jz romanfound
inx h ; move to next table entry
inx h
inx h
dcr e ; decrease counter
jnz romandgtl
pop h ; we didn't find it
stc ; set carry
ret ; return with DE=0
romanfound: inx h ; we did find it
mov e,m ; load it into DE
inx h
mov d,m
pop h
ana a ; clear carry
ret
romantab: db 'I',1,0 ; 16-bit little endian values
db 'V',5,0
db 'X',10,0
db 'L',50,0
db 'C',100,0
db 'D',0f4h,1
db 'M',0e8h,3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The following is testing and I/O code.
test: mvi c,10 ; read string from console
lxi d,bufdef
call 5
mvi c,9 ; print newline
lxi d,nl
call 5
lxi b,buf ; run `roman' on the input string
call roman ; the result is now in hl
lxi d,-10000
call numout ; print 10000s digit
lxi d,-1000
call numout ; print 1000s digit
lxi d,-100
call numout ; print 100s digit
lxi d,-10
call numout ; print 10s digit
lxi d,-1 ; ...print 1s digit
numout: mvi a,-1
push h
numloop: inr a
pop b
push h
dad d
jc numloop
adi '0'
mvi c,2
mov e,a
call 5
pop h
ret
nl: db 13,10,'$'
bufdef: db 16,0
buf: ds 17
|
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
|
#AutoHotkey
|
AutoHotkey
|
MsgBox % roots("poly", -0.99, 2, 0.1, 1.0e-5)
MsgBox % roots("poly", -1, 3, 0.1, 1.0e-5)
roots(f,x1,x2,step,tol) { ; search for roots in intervals of length "step", within tolerance "tol"
x := x1, y := %f%(x), s := (y>0)-(y<0)
Loop % ceil((x2-x1)/step) {
x += step, y := %f%(x), t := (y>0)-(y<0)
If (s=0 || s!=t)
res .= root(f, x-step, x, tol) " [" ErrorLevel "]`n"
s := t
}
Sort res, UN ; remove duplicate endpoints
Return res
}
root(f,x1,x2,d) { ; find x in [x1,x2]: f(x)=0 within tolerance d, by bisection
If (!y1 := %f%(x1))
Return x1, ErrorLevel := "Exact"
If (!y2 := %f%(x2))
Return x2, ErrorLevel := "Exact"
If (y1*y2>0)
Return "", ErrorLevel := "Need different sign ends!"
Loop {
x := (x2+x1)/2, y := %f%(x)
If (y = 0 || x2-x1 < d)
Return x, ErrorLevel := y ? "Approximate" : "Exact"
If ((y>0) = (y1>0))
x1 := x, y1 := y
Else
x2 := x, y2 := y
}
}
poly(x) {
Return ((x-3)*x+2)*x
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.