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/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
|
#Bracmat
|
Bracmat
|
( ( encode
= indian roman cifr tenfoldroman letter tenfold
. !arg:#?indian
& :?roman
& whl
' ( @(!indian:#%?cifr ?indian)
& :?tenfoldroman
& whl
' ( !roman:%?letter ?roman
& !tenfoldroman
( (I.X)
(V.L)
(X.C)
(L.D)
(C.M)
: ? (!letter.?tenfold) ?
& !tenfold
| "*"
)
: ?tenfoldroman
)
& !tenfoldroman:?roman
& ( !cifr:9&!roman I X:?roman
| !cifr:~<4
& !roman
(!cifr:4&I|)
V
: ?roman
& !cifr+-5:?cifr
& ~
| whl
' ( !cifr+-1:~<0:?cifr
& !roman I:?roman
)
)
)
& ( !roman:? "*" ?&~`
| str$!roman
)
)
& 1990 2008 1666 3888 3999 4000:?NS
& whl
' ( !NS:%?N ?NS
& out
$ ( encode$!N:?K&!N !K
| str$("Can't convert " !N " to Roman numeral")
)
)
);
|
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.
|
#Ceylon
|
Ceylon
|
shared void run() {
value numerals = map {
'I' -> 1,
'V' -> 5,
'X' -> 10,
'L' -> 50,
'C' -> 100,
'D' -> 500,
'M' -> 1000
};
function toHindu(String roman) {
variable value total = 0;
for(i->c in roman.indexed) {
assert(exists currentValue = numerals[c]);
/* Look at the next letter to see if we're looking
at a IV or CM or whatever. If so subtract the
current number from the total. */
if(exists next = roman[i + 1],
exists nextValue = numerals[next],
currentValue < nextValue) {
total -= currentValue;
} else {
total += currentValue;
}
}
return total;
}
assert(toHindu("I") == 1);
assert(toHindu("II") == 2);
assert(toHindu("IV") == 4);
assert(toHindu("MDCLXVI") == 1666);
assert(toHindu("MCMXC") == 1990);
assert(toHindu("MMVIII") == 2008);
}
|
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
|
#J
|
J
|
1{::p. 0 2 _3 1
2 1 0
|
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
|
#Java
|
Java
|
public class Roots {
public interface Function {
public double f(double x);
}
private static int sign(double x) {
return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}
public static void printRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, ox = x;
double y = f.f(x), oy = y;
int s = sign(y), os = s;
for (; x <= upperBound ; x += step) {
s = sign(y = f.f(x));
if (s == 0) {
System.out.println(x);
} else if (s != os) {
double dx = x - ox;
double dy = y - oy;
double cx = x - dx * (y / dy);
System.out.println("~" + cx);
}
ox = x; oy = y; os = s;
}
}
public static void main(String[] args) {
Function poly = new Function () {
public double f(double x) {
return x*x*x - 3*x*x + 2*x;
}
};
printRoots(poly, -1.0, 4, 0.002);
}
}
|
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.
|
#Fortran
|
Fortran
|
! compilation
! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
! EXAMPLE
!
!$ ./f
!rock, paper, scissors? papier
!scoring computer choice (r) and your choice (p)
!rock, paper, scissors? sizzerz
!scoring computer choice (s) and your choice (s)
!rock, paper, scissors? quit
!scoring computer choice (r) and your choice (q)
! Who's keeping score anyway???
! 0.5 1.5
! you won!
!$
program rpsgame
integer, parameter :: COMPUTER=1, HAPLESSUSER=2
integer, dimension(3) :: rps = (/1,1,1/)
real, dimension(3) :: p
character :: answer, cc ! computer choice
integer :: exhaustion, i
real, dimension(2) :: score = (/0, 0/)
character(len=8), dimension(3) :: choices = (/'rock ','paper ','scissors'/)
real :: harvest
do exhaustion = 1, 30
p = rps/real(sum(rps))
p(2) = p(2) + p(1)
p(3) = p(3) + p(2)
call random_number(harvest)
i = sum(merge(1,0,harvest.le.p)) ! In memory of Ken Iverson, logical is more useful as integer.
cc = 'rsp'(i:i)
write(6, "(2(A,', '),A,'? ')", advance='no')(trim(choices(i)),i=1,size(choices))
read(5, *) answer
write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer
if (answer.eq.cc) then
score = score + 0.5
else
i = HAPLESSUSER
if (answer.eq.'r') then
if (cc.eq.'p') i = COMPUTER
else if (answer.eq.'p') then
if (cc.eq.'s') i = COMPUTER
else if (answer.eq.'s') then
if (cc.eq.'r') i = COMPUTER
else
exit
endif
score(i) = score(i) + 1
end if
i = scan('rps',answer)
rps(i) = rps(i) + 1
end do
if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull"
write(6, *)"Who's keeping score anyway???"
write(6, '(2f5.1)') score
if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won!'
end program rpsgame
|
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.
|
#Go
|
Go
|
package main
import "fmt"
// encoding scheme:
// encode to byte array
// byte value < 26 means single character: byte value + 'A'
// byte value 26..255 means (byte value - 24) copies of next byte
func rllEncode(s string) (r []byte) {
if s == "" {
return
}
c := s[0]
if c < 'A' || c > 'Z' {
panic("invalid")
}
nc := byte(1)
for i := 1; i < len(s); i++ {
d := s[i]
switch {
case d != c:
case nc < (255 - 24):
nc++
continue
}
if nc > 1 {
r = append(r, nc+24)
}
r = append(r, c-'A')
if d < 'A' || d > 'Z' {
panic("invalid")
}
c = d
nc = 1
}
if nc > 1 {
r = append(r, nc+24)
}
r = append(r, c-'A')
return
}
func main() {
s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
fmt.Println("source: ", len(s), "bytes:", s)
e := rllEncode(s)
fmt.Println("encoded:", len(e), "bytes:", e)
d := rllDecode(e)
fmt.Println("decoded:", len(d), "bytes:", d)
fmt.Println("decoded = source:", d == s)
}
func rllDecode(e []byte) string {
var c byte
var d []byte
for i := 0; i < len(e); i++ {
b := e[i]
if b < 26 {
c = 1
} else {
c = b - 24
i++
b = e[i]
}
for c > 0 {
d = append(d, b+'A')
c--
}
}
return string(d)
}
|
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.
|
#R
|
R
|
for(j in 2:10) {
r <- sprintf("%d: ", j)
for(n in 1:j) {
r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", ""))
}
print(r)
}
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#Racket
|
Racket
|
#lang racket
(define (roots-of-unity n)
(for/list ([k n])
(make-polar 1 (* k (/ (* 2 pi) 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.
|
#Raku
|
Raku
|
constant n = 10;
for ^n -> \k {
say cis(k*τ/n);
}
|
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
|
Roots of a quadratic function
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle non-real roots, but it need not check that
a
≠
0
{\displaystyle a\neq 0}
.
The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic.
The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other.
In their classic textbook on numeric methods Computer Methods for Mathematical Computations, George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with
a
=
1
{\displaystyle a=1}
,
b
=
−
10
5
{\displaystyle b=-10^{5}}
, and
c
=
1
{\displaystyle c=1}
.
(For double-precision floats, set
b
=
−
10
9
{\displaystyle b=-10^{9}}
.)
Consider the following implementation in Ada:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Quadratic_Equation is
type Roots is array (1..2) of Float;
function Solve (A, B, C : Float) return Roots is
SD : constant Float := sqrt (B**2 - 4.0 * A * C);
AA : constant Float := 2.0 * A;
begin
return ((- B + SD) / AA, (- B - SD) / AA);
end Solve;
R : constant Roots := Solve (1.0, -10.0E5, 1.0);
begin
Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2)));
end Quadratic_Equation;
Output:
X1 = 1.00000E+06 X2 = 0.00000E+00
As we can see, the second root has lost all significant figures. The right answer is that X2 is about
10
−
6
{\displaystyle 10^{-6}}
. The naive method is numerically unstable.
Suggested by Middlebrook (D-OA), a better numerical method: to define two parameters
q
=
a
c
/
b
{\displaystyle q={\sqrt {ac}}/b}
and
f
=
1
/
2
+
1
−
4
q
2
/
2
{\displaystyle f=1/2+{\sqrt {1-4q^{2}}}/2}
and the two roots of the quardratic are:
−
b
a
f
{\displaystyle {\frac {-b}{a}}f}
and
−
c
b
f
{\displaystyle {\frac {-c}{bf}}}
Task: do it better. This means that given
a
=
1
{\displaystyle a=1}
,
b
=
−
10
9
{\displaystyle b=-10^{9}}
, and
c
=
1
{\displaystyle c=1}
, both of the roots your program returns should be greater than
10
−
11
{\displaystyle 10^{-11}}
. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle
b
=
−
10
6
{\displaystyle b=-10^{6}}
. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of
"What Every Scientist Should Know About Floating-Point Arithmetic" for a possible algorithm.
|
#R
|
R
|
qroots <- function(a, b, c) {
r <- sqrt(b * b - 4 * a * c + 0i)
if (abs(b - r) > abs(b + r)) {
z <- (-b + r) / (2 * a)
} else {
z <- (-b - r) / (2 * a)
}
c(z, c / (z * a))
}
qroots(1, 0, 2i)
[1] -1+1i 1-1i
qroots(1, -1e9, 1)
[1] 1e+09+0i 1e-09+0i
|
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.
|
#Racket
|
Racket
|
#lang racket
(define (quadratic a b c)
(let* ((-b (- b))
(delta (- (expt b 2) (* 4 a c)))
(denominator (* 2 a)))
(list
(/ (+ -b (sqrt delta)) denominator)
(/ (- -b (sqrt delta)) denominator))))
;(quadratic 1 0.0000000000001 -1)
;'(0.99999999999995 -1.00000000000005)
;(quadratic 1 0.0000000000001 1)
;'(-5e-014+1.0i -5e-014-1.0i)
|
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
|
#ERRE
|
ERRE
|
PROGRAM ROT13
BEGIN
INPUT("Enter a string ",TEXT$)
FOR C%=1 TO LEN(TEXT$) DO
A%=ASC(MID$(TEXT$,C%,1))
CASE A% OF
65..90->
MID$(TEXT$,C%,1)=CHR$(65+(A%-65+13) MOD 26)
END ->
97..122->
MID$(TEXT$,C%,1)=CHR$(97+(A%-97+13) MOD 26)
END ->
END CASE
END FOR
PRINT("Converted: ";TEXT$)
END PROGRAM
|
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 }
|
#Standard_ML
|
Standard ML
|
fun step y' (tn,yn) dt =
let
val dy1 = dt * y'(tn,yn)
val dy2 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy1)
val dy3 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy2)
val dy4 = dt * y'(tn + dt, yn + dy3)
in
(tn + dt, yn + (1.0 / 6.0) * (dy1 + 2.0*dy2 + 2.0*dy3 + dy4))
end
(* Suggested test case *)
fun testy' (t,y) =
t * Math.sqrt y
fun testy t =
(1.0 / 16.0) * Math.pow(Math.pow(t,2.0) + 4.0, 2.0)
(* Test-runner that iterates the step function and prints the results. *)
fun test t0 y0 dt steps print_freq y y' =
let
fun loop i (tn,yn) =
if i = steps then ()
else
let
val (t1,y1) = step y' (tn,yn) dt
val y1' = y tn
val () = if i mod print_freq = 0 then
(print ("Time: " ^ Real.toString tn ^ "\n");
print ("Exact: " ^ Real.toString y1' ^ "\n");
print ("Approx: " ^ Real.toString yn ^ "\n");
print ("Error: " ^ Real.toString (y1' - yn) ^ "\n\n"))
else ()
in
loop (i+1) (t1,y1)
end
in
loop 0 (t0,y0)
end
(* Run the suggested test case *)
val () = test 0.0 1.0 0.1 101 10 testy testy'
|
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 }
|
#Stata
|
Stata
|
function rk4(f, t0, y0, t1, n) {
h = (t1-t0)/(n-1)
a = J(n, 2, 0)
a[1, 1] = t = t0
a[1, 2] = y = y0
for (i=2; i<=n; i++) {
k1 = h*(*f)(t, y)
k2 = h*(*f)(t+0.5*h, y+0.5*k1)
k3 = h*(*f)(t+0.5*h, y+0.5*k2)
k4 = h*(*f)(t+h, y+k3)
t = t+h
y = y+(k1+2*k2+2*k3+k4)/6
a[i, 1] = t
a[i, 2] = y
}
return(a)
}
function f(t, y) {
return(t*sqrt(y))
}
a = rk4(&f(), 0, 1, 10, 101)
t = a[., 1]
a = a, a[., 2]:-(t:^2:+4):^2:/16
a[range(1,101,10), .]
1 2 3
+----------------------------------------------+
1 | 0 1 0 |
2 | 1 1.562499854 -1.45722e-07 |
3 | 2 3.999999081 -9.19479e-07 |
4 | 3 10.56249709 -2.90956e-06 |
5 | 4 24.99999377 -6.23491e-06 |
6 | 5 52.56248918 -.0000108197 |
7 | 6 99.99998341 -.0000165946 |
8 | 7 175.5624765 -.0000235177 |
9 | 8 288.9999684 -.0000315652 |
10 | 9 451.5624593 -.0000407232 |
11 | 10 675.999949 -.0000509833 |
+----------------------------------------------+
|
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.
|
#XPL0
|
XPL0
|
func Gen; \Return sum of the three largest of four random values
int I, R, Min, SI, Sum, Die(4);
[Min:= 7; Sum:= 0;
for I:= 0 to 4-1 do
[R:= Ran(6)+1; \R = 1..6
if R < Min then
[Min:= R; SI:= I];
Sum:= Sum+R;
Die(I):= R;
];
return Sum - Die(SI);
];
int Total, Count, J, Value(6);
[repeat Total:= 0; Count:= 0;
for J:= 0 to 6-1 do
[Value(J):= Gen;
if Value(J) >= 15 then Count:= Count+1;
Total:= Total + Value(J);
];
until Total >= 75 and Count >= 2;
Text(0, "Total: "); IntOut(0, Total); CrLf(0);
for J:= 0 to 6-1 do
[IntOut(0, Value(J)); ChOut(0, ^ )];
CrLf(0);
]
|
http://rosettacode.org/wiki/RPG_attributes_generator
|
RPG attributes generator
|
RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
The total of all character attributes must be at least 75.
At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
Task
Write a program that:
Generates 4 random, whole values between 1 and 6.
Saves the sum of the 3 largest values.
Generates a total of 6 values this way.
Displays the total, and all 6 values once finished.
The order in which each value was generated must be preserved.
The total of all 6 values must be at least 75.
At least 2 of the values must be 15 or more.
|
#Yabasic
|
Yabasic
|
sub d6()
//simulates a marked regular hexahedron coming to rest on a plane
return 1 + int(ran(6))
end sub
sub roll_stat()
//rolls four dice, returns the sum of the three highest
a = d6() : b = d6(): c = d6(): d = d6()
return a + b + c + d - min(min(a, b), min(c, d))
end sub
dim statnames$(6)
statnames$(1) = "STR"
statnames$(2) = "CON"
statnames$(3) = "DEX"
statnames$(4) = "INT"
statnames$(5) = "WIS"
statnames$(6) = "CHA"
dim stat(6)
acceptable = false
repeat
sum = 0
n15 = 0
for i = 1 to 6
stat(i) = roll_stat()
sum = sum + stat(i)
if stat(i) >= 15 then n15 = n15 + 1 : fi
next i
if sum >= 75 and n15 >= 2 then acceptable = true : fi
until acceptable
for i = 1 to 6
print statnames$(i), ": ", stat(i) using "##"
next i
print "-------\nTOT: ", sum
end
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Vedit_macro_language
|
Vedit macro language
|
#10 = Get_Num("Enter number to search to: ", STATLINE)
Buf_Switch(Buf_Free) // Use edit buffer as flags array
Ins_Text("--") // 0 and 1 are not primes
Ins_Char('P', COUNT, #10-1) // init rest of the flags to "prime"
for (#1 = 2; #1*#1 < #10; #1++) {
Goto_Pos(#1)
if (Cur_Char=='P') { // this is a prime number
for (#2 = #1*#1; #2 <= #10; #2 += #1) {
Goto_Pos(#2)
Ins_Char('-', OVERWRITE)
}
}
}
|
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
|
#PARI.2FGP
|
PARI/GP
|
find(v,n)={
my(i=setsearch(v,n));
if(i,
while(i>1, if(v[i-1]==n,i--))
,
error("Could not find")
);
i
};
|
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.
|
#Ring
|
Ring
|
# Project: Rosetta Code/Rank languages by popularity
load "stdlib.ring"
ros= download("http://rosettacode.org/wiki/Category:Programming_Languages")
pos = 1
totalros = 0
rosname = ""
rosnameold = ""
rostitle = ""
roslist = []
for n = 1 to len(ros)
nr = searchstring(ros,'<li><a href="/wiki/',pos)
if nr = 0
exit
else
pos = nr + 1
ok
nr = searchname(nr)
nr = searchtitle(nr)
next
roslist = sortfirst(roslist)
roslist = reverse(roslist)
see nl
for n = 1 to len(roslist)
see "rank: " + n + " (" + roslist[n][1] + " entries) " + roslist[n][2] + nl
next
func searchstring(str,substr,n)
newstr=right(str,len(str)-n+1)
nr = substr(newstr, substr)
if nr = 0
return 0
else
return n + nr -1
ok
func count(cstring,dstring)
sum = 0
while substr(cstring,dstring) > 0
sum = sum + 1
cstring = substr(cstring,substr(cstring,dstring)+len(string(sum)))
end
return sum
func searchname(sn)
nr2 = searchstring(ros,"/wiki/Category:",sn)
nr3 = searchstring(ros,"title=",sn)
nr4 = searchstring(ros,'">',sn)
nr5 = searchstring(ros,"</a></li>",sn)
rosname = substr(ros,nr2+15,nr3-nr2-17)
rosnameold = substr(ros,nr4+2,nr5-nr4-2)
return sn
func searchtitle(sn)
rostitle = "rosettacode.org/wiki/Category:" + rosname
rostitle = download(rostitle)
nr2 = 0
roscount = count(rostitle,"The following")
if roscount > 0
rp = 1
for rc = 1 to roscount
nr2 = searchstring(rostitle,"The following",rp)
rp = nr2 + 1
next
ok
nr3 = searchstring(rostitle,"pages are in this category",nr2)
if nr2 > 0 and nr3 > 0
rosnr = substr(rostitle,nr2+14,nr3-nr2-15)
rosnr = substr(rosnr,",","")
add(roslist,[rosnr,rosnameold])
ok
return sn
func sortfirst(alist)
for n = 1 to len(alist) - 1
for m = n + 1 to len(alist)
if alist[m][1] < alist[n][1]
swap(alist,m,n)
ok
if alist[m][1] = alist[n][1] and strcmp(alist[m][2],alist[n][2]) > 0
swap(alist,m,n)
ok
next
next
return alist
|
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
|
#C
|
C
|
#include <stdio.h>
int main() {
int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
// There is a bug: "XL\0" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long...
// Should be "XL" without \0 etc.
//
char roman[13][3] = {"M\0", "CM\0", "D\0", "CD\0", "C\0", "XC\0", "L\0", "XL\0", "X\0", "IX\0", "V\0", "IV\0", "I\0"};
int N;
printf("Enter arabic number:\n");
scanf("%d", &N);
printf("\nRoman number:\n");
for (int i = 0; i < 13; i++) {
while (N >= arabic[i]) {
printf("%s", roman[i]);
N -= arabic[i];
}
}
return 0;
}
|
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.
|
#Clojure
|
Clojure
|
;; Incorporated some improvements from the alternative implementation below
(defn ro2ar [r]
(->> (reverse (.toUpperCase r))
(map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
(partition-by identity)
(map (partial apply +))
(reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))
;; alternative
(def numerals { \I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000})
(defn from-roman [s]
(->> s .toUpperCase
(map numerals)
(reduce (fn [[sum lastv] curr] [(+ sum curr (if (< lastv curr) (* -2 lastv) 0)) curr]) [0,0])
first))
|
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
|
#JavaScript
|
JavaScript
|
// This function notation is sorta new, but useful here
// Part of the EcmaScript 6 Draft
// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
var poly = (x => x*x*x - 3*x*x + 2*x);
function sign(x) {
return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}
function printRoots(f, lowerBound, upperBound, step) {
var x = lowerBound, ox = x,
y = f(x), oy = y,
s = sign(y), os = s;
for (; x <= upperBound ; x += step) {
s = sign(y = f(x));
if (s == 0) {
console.log(x);
}
else if (s != os) {
var dx = x - ox;
var dy = y - oy;
var cx = x - dx * (y / dy);
console.log("~" + cx);
}
ox = x; oy = y; os = s;
}
}
printRoots(poly, -1.0, 4, 0.002);
|
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.
|
#FreeBASIC
|
FreeBASIC
|
Dim Shared As Byte ganador = 1, accion = 2, perdedor = 3, wp, wc
Dim Shared As String word(10, 3)
For n As Byte = 0 To 9
Read word(n, ganador), word(n, accion), word(n, perdedor)
Next n
Sub SimonSay(n As Byte)
Print Using "\ \ \ \ "; word(n, ganador); word(n, accion); word(n, perdedor)
End Sub
Sub Puntuacion()
Print !"\nPlayer = "; wp; !"\tComputer = "; wc; !"\n"
End Sub
Dim As Byte n
Dim As String*1 k
Dim As String eleccionCPU, eleccionJUG
Randomize Timer
Do
Cls
eleccionCPU = word(Rnd *10, ganador)
Print !"'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
For n = 0 To 9
SimonSay(n)
Next n
Print !"\nType your choice letter:"
Input !"(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit ", k
k = Ucase(k)
Select Case k
Case "Q"
Exit Do
Case "R"
eleccionJUG = "Rock"
Case "P"
eleccionJUG = "Paper"
Case "S"
eleccionJUG = "Scissors"
Case "L"
eleccionJUG = "Lizard"
Case "K"
eleccionJUG = "Spock"
End Select
Print !"\nPlayer chose "; eleccionJUG; " and Computer chose "; eleccionCPU
For n = 0 To 9
If word(n, ganador) = eleccionJUG And word(n, perdedor) = eleccionCPU Then
SimonSay(n)
Print !"\nWinner was Player"
wp += 1
Exit For
Elseif word(n, ganador) = eleccionCPU And word(n, perdedor) = eleccionJUG Then
SimonSay(n)
Print !"\nWinner was Computer"
wc += 1
Exit For
End If
Next n
If n = 10 Then Print !"\nOuch!"
Puntuacion()
Print "Press <SPACE> to continue"
Sleep
Loop Until(k = "Q")
Cls
Puntuacion()
If wp > wc Then
Print "Player win"
Elseif wc > wp Then
Print "Computer win"
Else
Print "Tie"
End If
Sleep
End
Data "Scissors","cuts","Paper"
Data "Paper","covers","Rock"
Data "Rock","crushes","Lizard"
Data "Lizard","poisons","Spock"
Data "Spock","smashes","Scissors"
Data "Scissors","decapites","Lizard"
Data "Lizard","eats","Paper"
Data "Paper","disproves","Spock"
Data "Spock","vaporizes","Rock"
Data "Rock","blunts","Scissors"
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Groovy
|
Groovy
|
def rleEncode(text) {
def encoded = new StringBuilder()
(text =~ /(([A-Z])\2*)/).each { matcher ->
encoded.append(matcher[1].size()).append(matcher[2])
}
encoded.toString()
}
def rleDecode(text) {
def decoded = new StringBuilder()
(text =~ /([0-9]+)([A-Z])/).each { matcher ->
decoded.append(matcher[2] * Integer.parseInt(matcher[1]))
}
decoded.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.
|
#REXX
|
REXX
|
/*REXX program computes the K roots of unity (which usually includes complex roots).*/
numeric digits length( pi() ) - length(.) /*use number of decimal digits in pi. */
parse arg n frac . /*get optional arguments from the C.L. */
if n=='' | n=="," then n= 1 /*Not specified? Then use the default.*/
if frac='' | frac=="," then frac= 5 /* " " " " " " */
start= abs(n) /*assume only one K is wanted. */
if n<0 then start= 1 /*Negative? Then use a range of K's. */
do #=start to abs(n) /*show unity roots (for a range or 1).*/
say right(# 'roots of unity', 40, "─") ' (showing' frac "fractional decimal digits)"
do angle=0 by pi*2/# for # /*compute the angle for each root. */
Rp= adj( cos(angle) ) /*the real part via COS function.*/
Ip= adj( sin(angle) ) /* " imaginary " " SIN " */
if Rp>=0 then Rp= ' 'Rp /*Not neg? Then pad with a blank char.*/
if Ip>=0 then Ip= '+'Ip /* " " " " " " plus " */
if Ip =0 then say Rp /*Only real part? Ignore imaginary part*/
else say left(Rp,frac+4)Ip'i' /*display the real and imaginary part. */
end /*angle*/
end /*#*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
adj: parse arg x; if abs(x) < ('1e-')(digits()*9%10) then x= 0; return format(x,,frac)/1
pi: pi=3.141592653589793238462643383279502884197169399375105820974944592307816; return pi
r2r: pi2= pi() + pi; return arg(1) // pi2 /*reduce #radians: -2pi ─► +2pi radians*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x= r2r(x); a= abs(x); numeric fuzz min(9, digits() - 9)
pi1_3=pi/3; if a=pi1_3 then return .5; if a=pi*.5 | a=pi2 then return 0
if a=pi then return -1; if a=pi1_3*2 then return -.5; z= 1; _= 1; $x= x * x
do k=2 by 2 until p=z; p=z; _= -_ * $x / (k*(k-1)); z= z + _; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x= r2r(x); numeric fuzz min(5, digits() - 3)
if abs(x)=pi then return 0; $x= x * x; z= x; _= x
do k=2 by 2 until p=z; p=z; _= -_ * $x / (k*(k+1)); z= z + _; end; return z
|
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.
|
#Raku
|
Raku
|
for
[1, 2, 1],
[1, 2, 3],
[1, -2, 1],
[1, 0, -4],
[1, -10**6, 1]
-> @coefficients {
printf "Roots for %d, %d, %d\t=> (%s, %s)\n",
|@coefficients, |quadroots(@coefficients);
}
sub quadroots (*[$a, $b, $c]) {
( -$b + $_ ) / (2 * $a),
( -$b - $_ ) / (2 * $a)
given
($b ** 2 - 4 * $a * $c ).Complex.sqrt.narrow
}
|
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
|
#Euphoria
|
Euphoria
|
include std/types.e
include std/text.e
atom FALSE = 0
atom TRUE = not FALSE
function Rot13( object oStuff )
integer iOffset
integer bIsUpper
object oResult
sequence sAlphabet = "abcdefghijklmnopqrstuvwxyz"
if sequence(oStuff) then
oResult = repeat( 0, length( oStuff ) )
for i = 1 to length( oStuff ) do
oResult[ i ] = Rot13( oStuff[ i ] )
end for
else
bIsUpper = FALSE
if t_upper( oStuff ) then
bIsUpper = TRUE
oStuff = lower( oStuff )
end if
iOffset = find( oStuff, sAlphabet )
if iOffset != 0 then
iOffset += 13
iOffset = remainder( iOffset, 26 )
if iOffset = 0 then iOffset = 1 end if
oResult = sAlphabet[iOffset]
if bIsUpper then
oResult = upper(oResult)
end if
else
oResult = oStuff --sprintf( "%s", oStuff )
end if
end if
return oResult
end function
puts( 1, Rot13( "abjurer NOWHERE." ) & "\n" )
|
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 }
|
#Swift
|
Swift
|
import Foundation
func rk4(dx: Double, x: Double, y: Double, f: (Double, Double) -> Double) -> Double {
let k1 = dx * f(x, y)
let k2 = dx * f(x + dx / 2, y + k1 / 2)
let k3 = dx * f(x + dx / 2, y + k2 / 2)
let k4 = dx * f(x + dx, y + k3)
return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6
}
var y = [Double]()
var x: Double = 0.0
var y2: Double = 0.0
var x0: Double = 0.0
var x1: Double = 10.0
var dx: Double = 0.1
var i = 0
var n = Int(1 + (x1 - x0) / dx)
y.append(1)
for i in 1..<n {
y.append(rk4(dx, x: x0 + dx * (Double(i) - 1), y: y[i - 1]) { (x: Double, y: Double) -> Double in
return x * sqrt(y)
})
}
print(" x y rel. err.")
print("------------------------------")
for (var i = 0; i < n; i += 10) {
x = x0 + dx * Double(i)
y2 = pow(x * x / 4 + 1, 2)
print(String(format: "%2g %11.6g %11.5g", x, y[i], y[i]/y2 - 1))
}
|
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 }
|
#Tcl
|
Tcl
|
package require Tcl 8.5
# Hack to bring argument function into expression
proc tcl::mathfunc::dy {t y} {upvar 1 dyFn dyFn; $dyFn $t $y}
proc rk4step {dyFn y* t* dt} {
upvar 1 ${y*} y ${t*} t
set dy1 [expr {$dt * dy($t, $y)}]
set dy2 [expr {$dt * dy($t+$dt/2, $y+$dy1/2)}]
set dy3 [expr {$dt * dy($t+$dt/2, $y+$dy2/2)}]
set dy4 [expr {$dt * dy($t+$dt, $y+$dy3)}]
set y [expr {$y + ($dy1 + 2*$dy2 + 2*$dy3 + $dy4)/6.0}]
set t [expr {$t + $dt}]
}
proc y {t} {expr {($t**2 + 4)**2 / 16}}
proc δy {t y} {expr {$t * sqrt($y)}}
proc printvals {t y} {
set err [expr {abs($y - [y $t])}]
puts [format "y(%.1f) = %.8f\tError: %.8e" $t $y $err]
}
set t 0.0
set y 1.0
set dt 0.1
printvals $t $y
for {set i 1} {$i <= 101} {incr i} {
rk4step δy y t $dt
if {$i%10 == 0} {
printvals $t $y
}
}
|
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.
|
#zkl
|
zkl
|
reg attrs=List(), S,N;
do{
attrs.clear();
do(6){
abcd:=(4).pump(List,(0).random.fp(1,7)); // list of 4 [1..6] randoms
attrs.append(abcd.sum(0) - (0).min(abcd)); // sum and substract min
}
}while((S=attrs.sum(0))<75 or (N=attrs.filter('>=(15)).len())<2);
println("Random numbers: %s\nSums to %d, with %d >= 15"
.fmt(attrs.concat(","),S,N));
|
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
|
#Visual_Basic
|
Visual Basic
|
Sub Eratost()
Dim sieve() As Boolean
Dim n As Integer, i As Integer, j As Integer
n = InputBox("limit:", n)
ReDim sieve(n)
For i = 1 To n
sieve(i) = True
Next i
For i = 2 To n
If sieve(i) Then
For j = i * 2 To n Step i
sieve(j) = False
Next j
End If
Next i
For i = 2 To n
If sieve(i) Then Debug.Print i
Next i
End Sub 'Eratost
|
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
|
#Pascal
|
Pascal
|
use List::Util qw(first);
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
foreach my $needle (qw(Washington Bush)) {
my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
# you would use "==" for numbers
if (defined $index) {
print "$index $needle\n";
} else {
print "$needle is not in haystack\n";
}
}
|
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.
|
#Ruby
|
Ruby
|
require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
# API has trouble with long titles= values.
# To prevent skipping languages, use short slices of 20 titles.
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are #{langcount.length} languages"
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "#{i+1}. #{count} - #{lang.sub(/Category:/, '')}"
end
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#C.23
|
C#
|
using System;
class Program
{
static uint[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static string[] rum = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
static string ToRoman(uint number)
{
string value = "";
for (int i = 0; i < nums.Length && number != 0; i++)
{
while (number >= nums[i])
{
number -= nums[i];
value += rum[i];
}
}
return value;
}
static void Main()
{
for (uint number = 1; number <= 1 << 10; number *= 2)
{
Console.WriteLine("{0} = {1}", number, ToRoman(number));
}
}
}
|
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.
|
#CLU
|
CLU
|
roman = cluster is decode
rep = null
digit_value = proc (c: char) returns (int) signals (invalid)
if c < 'a' then c := char$i2c(char$c2i(c) + 32) end
if c = 'm' then return(1000)
elseif c = 'd' then return(500)
elseif c = 'c' then return(100)
elseif c = 'l' then return(50)
elseif c = 'x' then return(10)
elseif c = 'v' then return(5)
elseif c = 'i' then return(1)
else signal invalid
end
end digit_value
decode = proc (s: string) returns (int) signals (invalid)
acc: int := 0
for i: int in int$from_to(1, string$size(s)) do
d: int := digit_value(s[i])
if i < string$size(s) cand d < digit_value(s[i+1]) then
acc := acc - d
else
acc := acc + d
end
end resignal invalid
return(acc)
end decode
end roman
start_up = proc ()
po: stream := stream$primary_output()
tests: array[string] := array[string]$
["MCMXC", "mdclxvi", "MmViI", "mmXXi", "INVALID"]
for test: string in array[string]$elements(tests) do
stream$puts(po, test || ": ")
stream$putl(po, int$unparse(roman$decode(test))) except when invalid:
stream$putl(po, "not a valid Roman numeral!")
end
end
end start_up
|
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
|
#jq
|
jq
|
def sign:
if . < 0 then -1 elif . > 0 then 1 else 0 end;
def printRoots(f; lowerBound; upperBound; step):
lowerBound as $x
| ($x|f) as $y
| ($y|sign) as $s
| reduce range($x; upperBound+step; step) as $x
# state: [ox, oy, os, roots]
( [$x, $y, $s, [] ];
.[0] as $ox | .[1] as $oy | .[2] as $os
| ($x|f) as $y
| ($y | sign) as $s
| if $s == 0 then [$x, $y, $s, (.[3] + [$x] )]
elif $s != $os and $os != 0 then
($x - $ox) as $dx
| ($y - $oy) as $dy
| ($x - ($dx * $y / $dy)) as $cx # by geometry
| [$x, $y, $s, (.[3] + [ "~\($cx)" ])] # an approximation
else [$x, $y, $s, .[3] ]
end )
| .[3] ;
|
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.
|
#GlovePIE
|
GlovePIE
|
if var.end=0 then
var.end=0
var.computerchoice=random(3) // 1 is rock, 2 is paper, and 3 is scissors.
debug="Press the R key for rock, the P key for paper, or the S key for scissors:"
endif
if pressed(Key.R)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="You chose rock, which the computer also chose, so it's a tie!"
else
if var.computerchoice=2 then
debug="The computer chose paper, covering your choice of rock, so you lose!"
else
debug="You chose rock, smashing the computer's choice of scissors, so you win!"
endif
endif
endif
if pressed(Key.P)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="You chose paper, covering the computer's choice of rock, so you win!"
else
if var.computerchoice=2 then
debug="You chose paper, which the computer also chose, so it's a tie!"
else
debug="The computer chose scissors, cutting your choice of paper, so you lose!"
endif
endif
endif
if pressed(Key.S)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="The computer chose rock, smashing your choice of scissors, so you lose!"
else
if var.computerchoice=2 then
debug="You chose scissors, cutting the computer's choice of paper, so you win!"
else
debug="You chose scissors, which the computer also chose, so it's a tie!"
endif
endif
endif
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string // player input
var aScore, pScore int
sl := 3 // for output alignment
pcf := make([]int, 3) // pcf = player choice frequency
var plays int
aChoice := rand.Intn(3) // ai choice for first play is completely random
for {
// get player choice
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi) // lazy
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
// show result of play
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
// show score
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
// compute ai choice for next play
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Haskell
|
Haskell
|
import Data.List (group)
-- Datatypes
type Encoded = [(Int, Char)] -- An encoded String with form [(times, char), ...]
type Decoded = String
-- Takes a decoded string and returns an encoded list of tuples
rlencode :: Decoded -> Encoded
rlencode = fmap ((,) <$> length <*> head) . group
-- Takes an encoded list of tuples and returns the associated decoded String
rldecode :: Encoded -> Decoded
rldecode = concatMap (uncurry replicate)
main :: IO ()
main = do
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
-- Output encoded and decoded versions of input
encoded = rlencode input
decoded = rldecode encoded
putStrLn $ "Encoded: " <> show encoded <> "\nDecoded: " <> show decoded
|
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.
|
#Ring
|
Ring
|
decimals(4)
for n = 2 to 5
see string(n) + " : "
for root = 0 to n-1
real = cos(2*3.14 * root / n)
imag = sin(2*3.14 * root / n)
see "" + real + " " + imag + "i"
if root != n-1 see ", " ok
next
see nl
next
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#RLaB
|
RLaB
|
// specify polynomial
>> n = 10;
>> a = zeros(1,n+1); a[1] = 1; a[n+1] = -1;
>> polyroots(a)
radius roots success
>> polyroots(a).roots
-0.309016994 + 0.951056516i
-0.809016994 + 0.587785252i
-1 + 5.95570041e-23i
-0.809016994 - 0.587785252i
-0.309016994 - 0.951056516i
0.309016994 - 0.951056516i
0.809016994 - 0.587785252i
1 + 0i
0.809016994 + 0.587785252i
0.309016994 + 0.951056516i
|
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.
|
#REXX
|
REXX
|
/*REXX program finds the roots (which may be complex) of a quadratic function. */
parse arg a b c . /*obtain the specified arguments: A B C*/
call quad a,b,c /*solve quadratic function via the sub.*/
r1= r1/1; r2= r2/1; a= a/1; b= b/1; c= c/1 /*normalize numbers to a new precision.*/
if r1j\=0 then r1=r1||left('+',r1j>0)(r1j/1)"i" /*Imaginary part? Handle complex number*/
if r2j\=0 then r2=r2||left('+',r2j>0)(r2j/1)"i" /* " " " " " */
say ' a =' a /*display the normalized value of A. */
say ' b =' b /* " " " " " B. */
say ' c =' c /* " " " " " C. */
say; say 'root1 =' r1 /* " " " " 1st root*/
say 'root2 =' r2 /* " " " " 2nd root*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
quad: parse arg aa,bb,cc; numeric digits 200 /*obtain 3 args; use enough dec. digits*/
$= sqrt(bb**2-4*aa*cc); L= length($) /*compute SQRT (which may be complex).*/
r= 1 /(aa+aa); ?= right($, 1)=='i' /*compute reciprocal of 2*aa; Complex?*/
if ? then do; r1= -bb *r; r2=r1; r1j= left($,L-1)*r; r2j=-r1j; end
else do; r1=(-bb+$)*r; r2=(-bb-$)*r; r1j= 0; r2j= 0; end
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x 1 ox; if x=0 then return 0; d= digits(); m.= 9; numeric form
numeric digits 9; h= d+6; x=abs(x); parse value format(x,2,1,,0) 'E0' with g 'E' _ .
g=g*.5'e'_%2; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return (g/1)left('i', ox<0) /*make complex if OX<0. */
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#F.23
|
F#
|
let rot13 (s : string) =
let rot c =
match c with
| c when c > 64 && c < 91 -> ((c - 65 + 13) % 26) + 65
| c when c > 96 && c < 123 -> ((c - 97 + 13) % 26) + 97
| _ -> c
s |> Array.of_seq
|> Array.map(int >> rot >> char)
|> (fun seq -> new string(seq))
|
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 }
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var rungeKutta4 = Fn.new { |t0, tz, dt, y, yd|
var tn = t0
var yn = y.call(tn)
var z = ((tz - t0)/dt).truncate
for (i in 0..z) {
if (i % 10 == 0) {
var exact = y.call(tn)
var error = yn - exact
Fmt.print("$4.1f $10f $10f $9f", tn, yn, exact, error)
}
if (i == z) break
var dy1 = dt * yd.call(tn, yn)
var dy2 = dt * yd.call(tn + 0.5 * dt, yn + 0.5 * dy1)
var dy3 = dt * yd.call(tn + 0.5 * dt, yn + 0.5 * dy2)
var dy4 = dt * yd.call(tn + dt, yn + dy3)
yn = yn + (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0
tn = tn + dt
}
}
System.print(" T RK4 Exact Error")
System.print("---- --------- ---------- ---------")
var y = Fn.new { |t|
var x = t * t + 4.0
return x * x / 16.0
}
var yd = Fn.new { |t, yt| t * yt.sqrt }
rungeKutta4.call(0, 10, 0.1, y, yd)
|
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
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Dim n As Integer, k As Integer, limit As Integer
Console.WriteLine("Enter number to search to: ")
limit = Console.ReadLine
Dim flags(limit) As Integer
For n = 2 To Math.Sqrt(limit)
If flags(n) = 0 Then
For k = n * n To limit Step n
flags(k) = 1
Next k
End If
Next n
' Display the primes
For n = 2 To limit
If flags(n) = 0 Then
Console.WriteLine(n)
End If
Next n
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Perl
|
Perl
|
use List::Util qw(first);
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
foreach my $needle (qw(Washington Bush)) {
my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
# you would use "==" for numbers
if (defined $index) {
print "$index $needle\n";
} else {
print "$needle is not in haystack\n";
}
}
|
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.
|
#Run_BASIC
|
Run BASIC
|
sqliteconnect #mem, ":memory:" ' make memory DB
#mem execute("CREATE TABLE stats(lang,cnt)")
a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages")
aa$ = httpGet$("http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000")
i = instr(a$,"/wiki/Category:")
while i > 0 and lang$ <> "Languages"
j = instr(a$,"""",i)
lang$ = mid$(a$,i+15,j - i-15)
ii = instr(aa$,"Category:";lang$;"""")
jj = instr(aa$,"(",ii)
kk = instr(aa$," ",jj+1)
if ii = 0 then cnt = 0 else cnt = val(mid$(aa$,jj+1,kk-jj))
k = instr(lang$,"%") ' convert hex values to characters
while k > 0
lang$ = left$(lang$,k-1) + chr$(hexdec(mid$(lang$,k+1,2))) + mid$(lang$,k+3)
k = instr(lang$,"%")
wend
#mem execute("insert into stats values ('";lang$;"',";cnt;")")
i = instr(a$,"/wiki/Category:",i+10)
wend
html "<table border=2>"
#mem execute("SELECT * FROM stats ORDER BY cnt desc") ' order list by count descending
WHILE #mem hasanswer()
#row = #mem #nextrow()
rank = rank + 1
html "<TR><TD align=right>";rank;"</td><td>";#row lang$();"</td><td align=right>";#row cnt();"</td></tr>"
WEND
html "</table>"
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
std::string to_roman(int value)
{
struct romandata_t { int value; char const* numeral; };
static romandata_t const romandata[] =
{ 1000, "M",
900, "CM",
500, "D",
400, "CD",
100, "C",
90, "XC",
50, "L",
40, "XL",
10, "X",
9, "IX",
5, "V",
4, "IV",
1, "I",
0, NULL }; // end marker
std::string result;
for (romandata_t const* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
result += current->numeral;
value -= current->value;
}
}
return result;
}
int main()
{
for (int i = 1; i <= 4000; ++i)
{
std::cout << to_roman(i) << std::endl;
}
}
|
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.
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. UNROMAN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 filler.
03 i pic 9(02) comp.
03 j pic 9(02) comp.
03 k pic 9(02) comp.
03 l pic 9(02) comp.
01 inp-roman.
03 inp-rom-ch pic x(01) occurs 20 times.
01 inp-roman-digits.
03 inp-rom-digit pic 9(01) occurs 20 times.
01 ws-search-idx pic 9(02) comp.
01 ws-tbl-table-def.
03 filler pic x(05) value '1000M'.
03 filler pic x(05) value '0500D'.
03 filler pic x(05) value '0100C'.
03 filler pic x(05) value '0050L'.
03 filler pic x(05) value '0010X'.
03 filler pic x(05) value '0005V'.
03 filler pic x(05) value '0001I'.
01 filler redefines ws-tbl-table-def.
03 ws-tbl-roman occurs 07 times indexed by rx.
05 ws-tbl-rom-val pic 9(04).
05 ws-tbl-rom-ch pic x(01).
01 ws-number pic s9(05) value 0.
01 ws-number-pic pic zzzz9-.
PROCEDURE DIVISION.
accept inp-roman
perform
until inp-roman = ' '
move zeroes to inp-roman-digits
perform
varying i from 1 by +1 until inp-rom-ch (i) = ' '
set rx to 1
search ws-tbl-roman
at end
move 0 to inp-rom-digit (i)
when ws-tbl-rom-ch (rx) = inp-rom-ch (i)
set inp-rom-digit (i) to rx
end-search
end-perform
compute l = i - 1
move 0 to ws-number
perform
varying i from 1 by +1
until i > l or inp-rom-digit (i) = 0
compute j = inp-rom-digit (i)
compute k = inp-rom-digit (i + 1)
if ws-tbl-rom-val (k)
> ws-tbl-rom-val (j)
compute ws-number
= ws-number
- ws-tbl-rom-val (j)
else
compute ws-number
= ws-number
+ ws-tbl-rom-val (j)
end-if
end-perform
move ws-number to ws-number-pic
display '----------'
display 'roman=' inp-roman
display 'arabic=' ws-number-pic
if i < l or ws-number = 0
display 'invalid/incomplete roman numeral at pos 'i
' found ' inp-rom-ch (i)
end-if
accept inp-roman
end-perform
stop run
.
END PROGRAM UNROMAN.
|
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
|
#Julia
|
Julia
|
using Roots
println(find_zero(x -> x^3 - 3x^2 + 2x, (-100, 100)))
|
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.
|
#Haskell
|
Haskell
|
import System.Random (randomRIO)
data Choice
= Rock
| Paper
| Scissors
deriving (Show, Eq)
beats :: Choice -> Choice -> Bool
beats Paper Rock = True
beats Scissors Paper = True
beats Rock Scissors = True
beats _ _ = False
genrps :: (Int, Int, Int) -> IO Choice
genrps (r, p, s) = rps <$> rand
where
rps x
| x <= s = Rock
| x <= s + r = Paper
| otherwise = Scissors
rand = randomRIO (1, r + p + s) :: IO Int
getrps :: IO Choice
getrps = rps <$> getLine
where
rps "scissors" = Scissors
rps "rock" = Rock
rps "paper" = Paper
rps _ = error "invalid input"
game :: (Int, Int, Int) -> IO a
game (r, p, s) = do
putStrLn "rock, paper or scissors?"
h <- getrps
c <- genrps (r, p, s)
putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c)
putStrLn
(if beats h c
then "player wins\n"
else if beats c h
then "player loses\n"
else "draw\n")
let rr =
if h == Rock
then r + 1
else r
pp =
if h == Paper
then p + 1
else p
ss =
if h == Scissors
then s + 1
else s
game (rr, pp, ss)
main :: IO a
main = game (1, 1, 1)
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(arglist)
s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
write(" s=",image(s))
write("s1=",image(s1 := rle_encode(s)))
write("s2=",image(s2 := rle_decode(s1)))
if s ~== s2 then write("Encode/Decode problem.")
else write("Encode/Decode worked.")
end
procedure rle_encode(s)
es := ""
s ? while c := move(1) do es ||:= *(move(-1),tab(many(c))) || c
return es
end
procedure rle_decode(es)
s := ""
es ? while s ||:= Repl(tab(many(&digits)),move(1))
return s
end
procedure Repl(n, c)
return repl(c,n)
end
|
http://rosettacode.org/wiki/Roots_of_unity
|
Roots of unity
|
The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
|
#Ruby
|
Ruby
|
def roots_of_unity(n)
(0...n).map {|k| Complex.polar(1, 2 * Math::PI * k / n)}
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.
|
#Run_BASIC
|
Run BASIC
|
PI = 3.1415926535
FOR n = 2 TO 5
PRINT n;":" ;
FOR root = 0 TO n-1
real = COS(2*PI * root / n)
imag = SIN(2*PI * root / n)
PRINT using("-##.#####",real);using("-##.#####",imag);"i";
IF root <> n-1 then PRINT "," ;
NEXT
PRINT
NEXT
|
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.
|
#Ring
|
Ring
|
x1 = 0
x2 = 0
quadratic(3, 4, 4/3.0) # [-2/3]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(3, 2, -1) # [1/3, -1]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(-2, 7, 15) # [-3/2, 5]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(1, -2, 1) # [1]
see "x1 = " + x1 + " x2 = " + x2 + nl
func quadratic a, b, c
sqrtDiscriminant = sqrt(pow(b,2) - 4*a*c)
x1 = (-b + sqrtDiscriminant) / (2.0*a)
x2 = (-b - sqrtDiscriminant) / (2.0*a)
return [x1, x2]
|
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.
|
#Ruby
|
Ruby
|
require 'cmath'
def quadratic(a, b, c)
sqrt_discriminant = CMath.sqrt(b**2 - 4*a*c)
[(-b + sqrt_discriminant) / (2.0*a), (-b - sqrt_discriminant) / (2.0*a)]
end
p quadratic(3, 4, 4/3.0) # [-2/3]
p quadratic(3, 2, -1) # [1/3, -1]
p quadratic(3, 2, 1) # [(-1/3 + sqrt(2/9)i), (-1/3 - sqrt(2/9)i)]
p quadratic(1, 0, 1) # [(0+i), (0-i)]
p quadratic(1, -1e6, 1) # [1e6, 1e-6]
p quadratic(-2, 7, 15) # [-3/2, 5]
p quadratic(1, -2, 1) # [1]
p quadratic(1, 3, 3) # [(-3 + sqrt(3)i)/2), (-3 - sqrt(3)i)/2)]
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Factor
|
Factor
|
#! /usr/bin/env factor
USING: kernel io ascii math combinators sequences ;
IN: rot13
: rot-base ( ch ch -- ch ) [ - 13 + 26 mod ] keep + ;
: rot13-ch ( ch -- ch )
{
{ [ dup letter? ] [ CHAR: a rot-base ] }
{ [ dup LETTER? ] [ CHAR: A rot-base ] }
[ ]
}
cond ;
: rot13 ( str -- str ) [ rot13-ch ] map ;
: main ( -- )
[ readln dup ]
[ rot13 print flush ]
while
drop ;
MAIN: main
|
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 }
|
#zkl
|
zkl
|
fcn yp(t,y) { t * y.sqrt() }
fcn exact(t){ u:=0.25*t*t + 1.0; u*u }
fcn rk4_step([(y,t)],h){
k1:=h * yp(t,y);
k2:=h * yp(t + 0.5*h, y + 0.5*k1);
k3:=h * yp(t + 0.5*h, y + 0.5*k2);
k4:=h * yp(t + h, y + k3);
T(y + (k1+k4)/6.0 + (k2+k3)/3.0, t + h);
}
fcn loop(h,n,[(y,t)]){
if(n % 10 == 1)
print("t = %f,\ty = %f,\terr = %g\n".fmt(t,y,(y - exact(t)).abs()));
if(n < 102) return(loop(h,(n+1),rk4_step(T(y,t),h))) //tail recursion
}
|
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
|
#Vlang
|
Vlang
|
fn main() {
limit := 201 // means sieve numbers < 201
// sieve
mut c := []bool{len: limit} // c for composite. false means prime candidate
c[1] = true // 1 not considered prime
mut p := 2
for {
// first allowed optimization: outer loop only goes to sqrt(limit)
p2 := p * p
if p2 >= limit {
break
}
// second allowed optimization: inner loop starts at sqr(p)
for i := p2; i < limit; i += p {
c[i] = true // it's a composite
}
// scan to get next prime for outer loop
for {
p++
if !c[p] {
break
}
}
}
// sieve complete. now print a representation.
for n in 1..limit {
if c[n] {
print(" .")
} else {
print("${n:3}")
}
if n%20 == 0 {
println("")
}
}
}
|
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
|
#Phix
|
Phix
|
constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"}
integer r = find("Zag",s) ?r -- 2 (first)
r = find("Zag",s,r+1) ?r -- 10 (next)
r = find("Zag",s,r+1) ?r -- 0 (no more)
r = rfind("Zag",s) ?r -- 10 (last)
r = find("Zog",s) ?r -- 0 (none)
|
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.
|
#Scala
|
Scala
|
import akka.actor.{Actor, ActorSystem, Props}
import scala.collection.immutable.TreeSet
import scala.xml.XML
// Reports a list with all languages recorded in the Wiki
private object Acquisition {
val (endPoint, prefix) = ("http://rosettacode.org/mw/api.php", "Category:")
val (maxPlaces, correction) = (50, 2)
def convertPathArgsToURL(endPoint: String, pathArgs: Map[String, String]) = {
pathArgs.map(argPair => argPair._1 + "=" + argPair._2)
.mkString(endPoint + (if (pathArgs.nonEmpty) "?" else ""), "&", "")
}
/* The categories include a page for the language and a count of the pages
* linked therein, this count is the data we need to scrape.
* Reports a list with language, count pair recorded in the Wiki
* All strings starts with the prefixes "Category:"
*/
def mineCatos = {
val endPoint = "http://rosettacode.org/mw/index.php"
Concurrent.logInfo("Acquisition of categories started.")
val categories =
(XML.load(convertPathArgsToURL(endPoint,
Map("title" -> "Special:Categories", "limit" -> "5000"))) \\ "ul" \ "li")
.withFilter(p => (p \ "a" \ "@title").text.startsWith(prefix))
.map // Create a tuple pair, eg. ("Category:Erlang", 195)
{ cat =>
((cat \ "a" \ "@title").text, // Takes the sibling of "a" and extracts the number
"[0-9]+".r.findFirstIn(cat.child.drop(1).text).getOrElse("0").toInt)
}
Concurrent.logInfo(s"Got ${categories.size} categories..")
categories
}
// The languages
// All strings starts with the prefixes "Category:"
def mineLangs = {
Concurrent.logInfo("Acquisition of languages started...")
def getLangs(first: Boolean = true, continue: String = ""): TreeSet[String] = (first, continue) match {
case (false, "") => TreeSet[String]()
case _ => {
val xml = XML.load(convertPathArgsToURL(endPoint, Map(
"action" -> "query",
"list" -> "categorymembers",
"cmtitle" -> (prefix + "Programming_Languages"),
"cmlimit" -> "500",
"rawcontinue" -> "",
"format" -> "xml",
"cmcontinue" -> continue)))
getLangs(false, (xml \\ "query-continue" \ "categorymembers" \ "@cmcontinue").text) ++ (xml \\ "categorymembers" \ "cm").map(c => (c \ "@title").text)
}
}
val languages = getLangs()
Concurrent.logInfo(s"Got ${languages.size} languages..")
languages
}
def joinRosettaCodeWithLanguage(catos: Seq[(String, Int)],
langs: TreeSet[String]) =
for {
cato <- catos //Clean up the tuple pairs, eg ("Category:Erlang", 195) becomes ("Erlang", 192)
if langs.contains(cato._1)
} yield (cato._1.drop(prefix.length), cato._2 - correction max 0) // Correct count
def printScrape(languages: TreeSet[String], category: Seq[(String, Int)]) {
val join = joinRosettaCodeWithLanguage(category, languages)
val total = join.foldLeft(0)(_ + _._2)
Concurrent.logInfo("Data processed")
println(f"\nTop$maxPlaces%3d Rosetta Code Languages by Popularity as ${new java.util.Date}%tF:\n")
(join.groupBy(_._2).toSeq.sortBy(-_._1).take(maxPlaces) :+ (0, Seq(("...", 0))))
.zipWithIndex // Group the ex aequo
.foreach {
case ((score, langs), rank) =>
println(f"${rank + 1}%2d. $score%3d - ${langs.map(_._1).mkString(", ")}")
}
println(s"\nCross section yields ${join.size} languages, total of $total solutions")
println(s"Resulting average is ${total / join.size} solutions per language")
}
def printScrape(): Unit = printScrape(mineLangs, mineCatos)
} // object Acquisition
private object Concurrent extends AppCommons {
var (category: Option[Seq[(String, Int)]], language: Option[TreeSet[String]]) = (None, None)
class Worker extends Actor {
def receive = {
case 'Catalogue => sender ! Acquisition.mineCatos
case 'Language => sender ! Acquisition.mineLangs
}
}
class Listener extends Actor {
// Create and signal the worker actors
context.actorOf(Props[Worker], "worker0") ! 'Catalogue
context.actorOf(Props[Worker], "worker1") ! 'Language
def printCompleteScape() =
if (category.isDefined && language.isDefined) {
Acquisition.printScrape(language.get, category.get)
context.system.shutdown()
appEnd()
}
def receive = {
case content: TreeSet[String] =>
language = Some(content)
printCompleteScape()
case content: Seq[(String, Int)] =>
category = Some(content)
printCompleteScape()
case whatever => logInfo(whatever.toString)
} // def receive
}
} // object Concurrent
trait AppCommons {
val execStart = System.currentTimeMillis()
System.setProperty("http.agent", "*")
def logInfo(info: String) {
println(f"[Info][${System.currentTimeMillis() - execStart}%5d ms]" + info)
}
def appEnd() { logInfo("Run succesfully completed") }
}
// Main entry for sequential version (slower)
object GhettoParserSeq extends App with AppCommons {
Concurrent.logInfo("Sequential version started")
Acquisition.printScrape()
appEnd()
}
// Entry for parallel version (faster)
object GhettoParserPar extends App {
Concurrent.logInfo("Parallel version started")
ActorSystem("Main").actorOf(Props[Concurrent.Listener])
}
|
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
|
#Ceylon
|
Ceylon
|
shared void run() {
class Numeral(shared Character char, shared Integer int) {}
value tiers = [
[Numeral('I', 1), Numeral('V', 5), Numeral('X', 10)],
[Numeral('X', 10), Numeral('L', 50), Numeral('C', 100)],
[Numeral('C', 100), Numeral('D', 500), Numeral('M', 1k)]
];
String toRoman(Integer hindu, Integer tierIndex = 2) {
assert (exists tier = tiers[tierIndex]);
" Finds if it's a two character numeral like iv, ix, xl, xc, cd and cm."
function findTwoCharacterNumeral() =>
if (exists bigNum = tier.rest.find((numeral) => numeral.int - tier.first.int <= hindu < numeral.int))
then [tier.first, bigNum]
else null;
if (hindu <= 0) {
// if it's zero then we are done!
return "";
}
else if (exists [smallNum, bigNum] = findTwoCharacterNumeral()) {
value twoCharSymbol = "``smallNum.char````bigNum.char``";
value twoCharValue = bigNum.int - smallNum.int;
return "``twoCharSymbol````toRoman(hindu - twoCharValue, tierIndex)``";
}
else if (exists num = tier.reversed.find((Numeral elem) => hindu >= elem.int)) {
return "``num.char````toRoman(hindu - num.int, tierIndex)``";
}
else {
// nothing was found so move to the next smaller tier!
return toRoman(hindu, tierIndex - 1);
}
}
assert (toRoman(1) == "I");
assert (toRoman(2) == "II");
assert (toRoman(4) == "IV");
assert (toRoman(1666) == "MDCLXVI");
assert (toRoman(1990) == "MCMXC");
assert (toRoman(2008) == "MMVIII");
}
|
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.
|
#CoffeeScript
|
CoffeeScript
|
roman_to_demical = (s) ->
# s is well-formed Roman Numeral >= I
numbers =
M: 1000
D: 500
C: 100
L: 50
X: 10
V: 5
I: 1
result = 0
for c in s
num = numbers[c]
result += num
if old_num < num
# If old_num exists and is less than num, then
# we need to subtract it twice, once because we
# have already added it on the last pass, and twice
# to conform to the Roman convention that XC = 90,
# not 110.
result -= 2 * old_num
old_num = num
result
tests =
IV: 4
XLII: 42
MCMXC: 1990
MMVIII: 2008
MDCLXVI: 1666
for roman, expected of tests
dec = roman_to_demical(roman)
console.log "error" if dec != expected
console.log "#{roman} = #{dec}"
|
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
|
#Kotlin
|
Kotlin
|
// version 1.1.2
typealias DoubleToDouble = (Double) -> Double
fun f(x: Double) = x * x * x - 3.0 * x * x + 2.0 * x
fun secant(x1: Double, x2: Double, f: DoubleToDouble): Double {
val e = 1.0e-12
val limit = 50
var xa = x1
var xb = x2
var fa = f(xa)
var i = 0
while (i++ < limit) {
var fb = f(xb)
val d = (xb - xa) / (fb - fa) * fb
if (Math.abs(d) < e) break
xa = xb
fa = fb
xb -= d
}
if (i == limit) {
println("Function is not converging near (${"%7.4f".format(xa)}, ${"%7.4f".format(xb)}).")
return -99.0
}
return xb
}
fun main(args: Array<String>) {
val step = 1.0e-2
val e = 1.0e-12
var x = -1.032
var s = f(x) > 0.0
while (x < 3.0) {
val value = f(x)
if (Math.abs(value) < e) {
println("Root found at x = ${"%12.9f".format(x)}")
s = f(x + 0.0001) > 0.0
}
else if ((value > 0.0) != s) {
val xx = secant(x - step, x, ::f)
if (xx != -99.0)
println("Root found at x = ${"%12.9f".format(xx)}")
else
println("Root found near x = ${"%7.4f".format(x)}")
s = f(x + 0.0001) > 0.0
}
x += step
}
}
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link printf
procedure main()
printf("Welcome to Rock, Paper, Scissors.\n_
Rock beats scissors, Scissors beat paper, and Paper beats rock.\n\n")
historyP := ["rock","paper","scissors"] # seed player history
winP := winC := draws := 0 # totals
beats := ["rock","scissors","paper","rock"] # what beats what 1 apart
repeat {
printf("Enter your choice or rock(r), paper(p), scissors(s) or quit(q):")
turnP := case map(read()) of {
"q"|"quit": break
"r"|"rock": "rock"
"p"|"paper": "paper"
"s"|"scissors": "scissors"
default: printf(" - invalid choice.\n") & next
}
turnC := beats[(?historyP == beats[i := 2 to *beats],i-1)] # choose move
put(historyP,turnP) # record history
printf("You chose %s, computer chose %s",turnP,turnC)
(beats[p := 1 to *beats] == turnP) &
(beats[c := 1 to *beats] == turnC) & (abs(p-c) <= 1) # rank play
if p = c then
printf(" - draw (#%d)\n",draws +:= 1 )
else if p > c then
printf(" - player win(#%d)\n",winP +:= 1)
else
printf(" - computer win(#%d)\n",winC +:= 1)
}
printf("\nResults:\n %d rounds\n %d Draws\n %d Computer wins\n %d Player wins\n",
winP+winC+draws,draws,winC,winP)
end
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#J
|
J
|
rle=: ;@(<@(":@(#-.1:),{.);.1~ 1, 2 ~:/\ ])
rld=: ;@(-.@e.&'0123456789' <@({:#~1{.@,~".@}:);.2 ])
|
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.
|
#Rust
|
Rust
|
use num::Complex;
fn main() {
let n = 8;
let z = Complex::from_polar(&1.0,&(1.0*std::f64::consts::PI/n as f64));
for k in 0..=n-1 {
println!("e^{:2}πi/{} ≈ {:>14.3}",2*k,n,z.powf(2.0*k as f64));
}
}
|
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.
|
#Scala
|
Scala
|
def rootsOfUnity(n:Int)=for(k <- 0 until n) yield Complex.fromPolar(1.0, 2*math.Pi*k/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.
|
#Scheme
|
Scheme
|
(define pi (* 4 (atan 1)))
(do ((n 2 (+ n 1)))
((> n 10))
(display n)
(do ((k 0 (+ k 1)))
((>= k n))
(display " ")
(display (make-polar 1 (* 2 pi (/ k n)))))
(newline))
|
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.
|
#Run_BASIC
|
Run BASIC
|
print "FOR 1,2,3 => ";quad$(1,2,3)
print "FOR 4,5,6 => ";quad$(4,5,6)
FUNCTION quad$(a,b,c)
d = b^2-4 * a*c
x = -1*b
if d<0 then
quad$ = str$(x/(2*a));" +i";str$(sqr(abs(d))/(2*a))+" , "+str$(x/(2*a));" -i";str$(sqr(abs(d))/abs(2*a))
else
quad$ = str$(x/(2*a)+sqr(d)/(2*a))+" , "+str$(x/(2*a)-sqr(d)/(2*a))
end if
END FUNCTION
|
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.
|
#Scala
|
Scala
|
import ArithmeticComplex._
object QuadraticRoots {
def solve(a:Double, b:Double, c:Double)={
val d = b*b-4.0*a*c
val aa = a+a
if (d < 0.0) { // complex roots
val re= -b/aa;
val im = math.sqrt(-d)/aa;
(Complex(re, im), Complex(re, -im))
}
else { // real roots
val re=if (b < 0.0) (-b+math.sqrt(d))/aa else (-b -math.sqrt(d))/aa
(re, (c/(a*re)))
}
}
}
|
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
|
#FALSE
|
FALSE
|
[^$1+][$32|$$'z>'a@>|$[\%]?~[13\'m>[_]?+]?,]#%
|
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
|
#Vorpal
|
Vorpal
|
self.print_primes = method(m){
p = new()
p.fill(0, m, 1, true)
count = 0
i = 2
while(i < m){
if(p[i] == true){
p.fill(i+i, m, i, false)
count = count + 1
}
i = i + 1
}
('primes: ' + count + ' in ' + m).print()
for(i = 2, i < m, i = i + 1){
if(p[i] == true){
('' + i + ', ').put()
}
}
''.print()
}
self.print_primes(100)
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Phixmonti
|
Phixmonti
|
"mouse" "hat" "cup" "deodorant" "television"
"soap" "methamphetamine" "severed cat heads" "cup"
pstack
stklen tolist reverse
0 tolist var t
"Enter string to search: " input var s nl
true
while
head s == if
len t swap 0 put var t
endif
tail nip len
endwhile
drop
t len not if
"String not found in list" print
else
reverse
"First index for " print s print " : " print 1 get print
len 1 > if
nl "Last index for " print s print " : " print len get print
endif
endif
drop
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "gethttp.s7i";
include "scanstri.s7i";
const type: popularityHash is hash [string] integer;
const type: rankingHash is hash [integer] array string;
const func array string: getLangs (in string: buffer) is func
result
var array string: langs is 0 times "";
local
var integer: pos is 0;
begin
pos := pos(buffer, "Category:");
while pos <> 0 do
pos +:= 9;
langs &:= buffer[pos .. pred(pos(buffer, '"', pos))];
pos := pos(buffer, "Category:", pos);
end while;
end func;
const proc: main is func
local
var string: categories is "";
var popularityHash: popularity is popularityHash.value;
var rankingHash: ranking is rankingHash.value;
var array integer: numList is 0 times 0;
var string: lang is "";
var integer: pos is 0;
var string: numStri is "";
var integer: listIdx is 0;
var integer: index is 0;
var integer: place is 1;
begin
categories := getHttp("www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000");
for lang range getLangs(getHttp("rosettacode.org/mw/api.php?action=query&list=categorymembers&\
\cmtitle=Category:Programming_Languages&cmlimit=500&format=json")) do
pos := pos(categories, "title=\"Category:" & lang);
if pos <> 0 then
pos := pos(categories, "</a>", succ(pos));
if pos <> 0 then
pos := pos(categories, "(", succ(pos));
if pos <> 0 then
numStri := categories[succ(pos) len 10];
popularity @:= [lang] integer parse getDigits(numStri);
end if;
end if;
end if;
end for;
ranking := flip(popularity);
numList := sort(keys(ranking));
for listIdx range maxIdx(numList) downto minIdx(numList) do
for key index range ranking[numList[listIdx]] do
writeln(place lpad 3 <& ". " <& numList[listIdx] <& " - " <& ranking[numList[listIdx]][index]);
end for;
place +:= length(ranking[numList[listIdx]]);
end for;
end func;
|
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
|
#Clojure
|
Clojure
|
(def arabic->roman
(partial clojure.pprint/cl-format nil "~@R"))
(arabic->roman 147)
;"CXXIII"
(arabic->roman 99)
;"XCIX"
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun mapcn (chars nums string)
(loop as char across string as i = (position char chars) collect (and i (nth i nums))))
(defun parse-roman (R)
(loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R)
as (A B) on nums if A sum (if (and B (< A B)) (- A) A)))
|
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
|
#Lambdatalk
|
Lambdatalk
|
1) defining the function:
{def func {lambda {:x} {+ {* 1 :x :x :x} {* -3 :x :x} {* 2 :x}}}}
-> func
2) printing roots:
{S.map {lambda {:x}
{if {< {abs {func :x}} 0.0001}
then {br}- a root found at :x else}}
{S.serie -1 3 0.01}}
->
- a root found at 7.528699885739343e-16
- a root found at 1.0000000000000013
- a root found at 2.000000000000002
3) printing the roots of the "sin" function between -720° to +720°;
{S.map {lambda {:x}
{if {< {abs {sin {* {/ {PI} 180} :x}}} 0.01}
then {br}- a root found at :x° else}}
{S.serie -720 +720 10}}
->
- a root found at -720°
- a root found at -540°
- a root found at -360°
- a root found at -180°
- a root found at 0°
- a root found at 180°
- a root found at 360°
- a root found at 540°
- a root found at 720°
|
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.
|
#IS-BASIC
|
IS-BASIC
|
100 PROGRAM "Rock.bas"
110 RANDOMIZE
120 STRING CH$(1 TO 3)*8,K$*1
130 NUMERIC PLWINS(1 TO 3),SCORE(1 TO 3),PLSTAT(1 TO 3),CMSTAT(1 TO 3),PLCHOICE,CMCHOICE
140 CALL INIC
150 DO
160 CALL GUESS
170 PRINT :PRINT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors, ESC = quit)"
180 DO
190 LET K$=INKEY$
200 LOOP UNTIL K$>="1" AND K$<="3" OR K$=CHR$(27)
210 IF K$=CHR$(27) THEN EXIT DO
220 LET PLCHOICE=VAL(K$)
230 LET CMSTAT(CMCHOICE)=CMSTAT(CMCHOICE)+1:LET PLSTAT(PLCHOICE)=PLSTAT(PLCHOICE)+1
240 PRINT "You chose ";CH$(PLCHOICE);" and I chose ";CH$(CMCHOICE);"."
250 SET #102:INK 3
260 IF PLCHOICE=CMCHOICE THEN
270 PRINT "Tie!"
280 LET SCORE(3)=SCORE(3)+1
290 ELSE IF CMCHOICE=PLWINS(PLCHOICE) THEN
300 PRINT "You won!"
310 LET SCORE(1)=SCORE(1)+1
320 ELSE
330 PRINT "I won!"
340 LET SCORE(2)=SCORE(2)+1
350 END IF
360 SET #102:INK 1
370 LOOP
380 PRINT :PRINT "Some useless statistics:"
390 PRINT "You won";SCORE(1);"times, and I won";SCORE(2);"times;";SCORE(3);"ties."
400 PRINT :PRINT ,,CH$(1),CH$(2),CH$(3)
410 PRINT "You chose:",PLSTAT(1),PLSTAT(2),PLSTAT(3)
420 PRINT " I chose:",CMSTAT(1),CMSTAT(2),CMSTAT(3)
430 END
440 DEF INIC
450 LET CH$(1)="rock":LET CH$(2)="paper":LET CH$(3)="scissors"
460 LET PLWINS(1)=3:LET PLWINS(2)=1:LET PLWINS(3)=2
470 FOR I=1 TO 3
480 LET PLSTAT(I),CMSTAT(I),SCORE(I)=0
490 NEXT
500 TEXT 80
510 END DEF
520 DEF GUESS
530 LET CMCHOICE=INT(RND*(PLSTAT(1)+PLSTAT(2)+PLSTAT(3)+3))
540 SELECT CASE CMCHOICE
550 CASE 0 TO PLSTAT(1)
560 LET CMCHOICE=2
570 CASE PLSTAT(1)+1 TO PLSTAT(1)+PLSTAT(2)+1
580 LET CMCHOICE=3
590 CASE ELSE
600 LET CMCHOICE=1
610 END SELECT
620 END DEF
|
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.
|
#Java
|
Java
|
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "float.s7i";
include "complex.s7i";
const proc: main is func
local
var integer: n is 0;
var integer: k is 0;
begin
for n range 2 to 10 do
write(n lpad 2 <& ": ");
for k range 0 to pred(n) do
write(polar(1.0, 2.0 * PI * flt(k) / flt(n)) digits 4 lpad 15 <& " ");
end for;
writeln;
end for;
end func;
|
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.
|
#Sidef
|
Sidef
|
func roots_of_unity(n) {
n.of { |j|
exp(2i * Num.pi / n * j)
}
}
roots_of_unity(5).each { |c|
printf("%+.5f%+.5fi\n", c.reals)
}
|
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.
|
#Scheme
|
Scheme
|
(define (quadratic a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(if (and (real? delta) (> delta 0))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list
(/ (- (sqrt delta) b) 2 a)
(/ (+ (sqrt delta) b) -2 a))))))
; examples
(quadratic 1 -1 -1)
; (1.618033988749895 -0.6180339887498948)
(quadratic 1 0 -2)
; (-1.4142135623730951 1.414213562373095)
(quadratic 1 0 2)
; (0+1.4142135623730951i 0-1.4142135623730951i)
(quadratic 1+1i 2 5)
; (-1.0922677260818898-1.1884256155834088i 0.09226772608188982+2.1884256155834088i)
(quadratic 0 4 3)
; -3/4
(quadratic 0 0 1)
; fail
(quadratic 1 2 0)
; (-2 0)
(quadratic 1 2 1)
; (-1 -1)
(quadratic 1 -1e5 1)
; (99999.99999 1.0000000001000001e-05)
|
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
|
#Fantom
|
Fantom
|
class Rot13
{
static Str rot13 (Str input)
{
Str result := ""
input.each |Int c|
{
if ((c.lower >= 'a') && (c.lower <= 'm'))
result += (c+13).toChar
else if ((c.lower >= 'n') && (c.lower <= 'z'))
result += (c-13).toChar
else
result += c.toChar
}
return result
}
public static Void main (Str[] args)
{
if (args.size == 1)
{ // process each line of given file
Str filename := args[0]
File(filename.toUri).eachLine |Str line|
{
echo (rot13(line))
}
}
else
{
echo ("Test:")
Str text := "abcstuABCSTU123!+-"
echo ("Text $text becomes ${rot13(text)}")
}
}
}
|
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
|
#WebAssembly
|
WebAssembly
|
(module
(import "js" "print" (func $print (param i32)))
(memory 4096)
(func $sieve (export "sieve") (param $n i32)
(local $i i32)
(local $j i32)
(set_local $i (i32.const 0))
(block $endLoop
(loop $loop
(br_if $endLoop (i32.ge_s (get_local $i) (get_local $n)))
(i32.store8 (get_local $i) (i32.const 1))
(set_local $i (i32.add (get_local $i) (i32.const 1)))
(br $loop)))
(set_local $i (i32.const 2))
(block $endLoop
(loop $loop
(br_if $endLoop (i32.ge_s (i32.mul (get_local $i) (get_local $i))
(get_local $n)))
(if (i32.eq (i32.load8_s (get_local $i)) (i32.const 1))
(then
(set_local $j (i32.mul (get_local $i) (get_local $i)))
(block $endInnerLoop
(loop $innerLoop
(i32.store8 (get_local $j) (i32.const 0))
(set_local $j (i32.add (get_local $j) (get_local $i)))
(br_if $endInnerLoop (i32.ge_s (get_local $j) (get_local $n)))
(br $innerLoop)))))
(set_local $i (i32.add (get_local $i) (i32.const 1)))
(br $loop)))
(set_local $i (i32.const 2))
(block $endLoop
(loop $loop
(if (i32.eq (i32.load8_s (get_local $i)) (i32.const 1))
(then
(call $print (get_local $i))))
(set_local $i (i32.add (get_local $i) (i32.const 1)))
(br_if $endLoop (i32.ge_s (get_local $i) (get_local $n)))
(br $loop)))))
|
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
|
#PHP
|
PHP
|
$haystack = array("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
foreach (array("Washington","Bush") as $needle) {
$i = array_search($needle, $haystack);
if ($i === FALSE) // note: 0 is also considered false in PHP, so you need to specifically check for FALSE
echo "$needle is not in haystack\n";
else
echo "$i $needle\n";
}
|
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.
|
#Sidef
|
Sidef
|
require('MediaWiki::API')
var api = %O<MediaWiki::API>.new(
Hash(api_url => 'http://rosettacode.org/mw/api.php')
)
var languages = []
var gcmcontinue
loop {
var apih = api.api(
Hash(
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => gcmcontinue,
)
)
languages.append(apih{:query}{:pages}.values...)
gcmcontinue = apih{:continue}{:gcmcontinue}
gcmcontinue || break
}
languages.each { |lang|
lang{:title} -= /^Category:/
lang{:categoryinfo}{:size} := 0
}
var sorted_languages = languages.sort_by { |lang|
-lang{:categoryinfo}{:size}
}
sorted_languages.each_kv { |i, lang|
printf("%3d. %20s - %3d\n", i+1, lang{:title}, lang{:categoryinfo}{:size})
}
|
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
|
#CLU
|
CLU
|
roman = cluster is encode
rep = null
dmap = struct[v: int, s: string]
darr = array[dmap]
own chunks: darr := darr$
[dmap${v: 1000, s: "M"},
dmap${v: 900, s: "CM"},
dmap${v: 500, s: "D"},
dmap${v: 400, s: "CD"},
dmap${v: 100, s: "C"},
dmap${v: 90, s: "XC"},
dmap${v: 50, s: "L"},
dmap${v: 40, s: "XL"},
dmap${v: 10, s: "X"},
dmap${v: 9, s: "IX"},
dmap${v: 5, s: "V"},
dmap${v: 4, s: "IV"},
dmap${v: 1, s: "I"}]
largest_chunk = proc (i: int) returns (int, string)
for chunk: dmap in darr$elements(chunks) do
if chunk.v <= i then return (chunk.v, chunk.s) end
end
return (0, "")
end largest_chunk
encode = proc (i: int) returns (string)
result: string := ""
while i > 0 do
val: int chunk: string
val, chunk := largest_chunk(i)
result := result || chunk
i := i - val
end
return (result)
end encode
end roman
start_up = proc ()
po: stream := stream$primary_output()
tests: array[int] := array[int]$[1666, 2008, 1001, 1999, 3888, 2021]
for test: int in array[int]$elements(tests) do
stream$putl(po, int$unparse(test) || " = " || roman$encode(test))
end
end start_up
|
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.
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
include "argv.coh";
# Decode the Roman numeral in the given string.
# Returns 0 if the string does not contain a valid Roman numeral.
sub romanToDecimal(str: [uint8]): (rslt: uint16) is
# Look up a Roman digit
sub digit(char: uint8): (val: uint16) is
# Definition of Roman numerals
record RomanDigit is
char: uint8;
value: uint16;
end record;
var digits: RomanDigit[] := {
{'I',1}, {'V',5}, {'X',10}, {'L',50},
{'C',100}, {'D',500}, {'M',1000}
};
char := char & ~32; # make uppercase
# Look up given digit
var i: @indexof digits := 0;
while i < @sizeof digits loop
val := digits[i].value;
if digits[i].char == char then
return;
end if;
i := i + 1;
end loop;
val := 0;
end sub;
rslt := 0;
while [str] != 0 loop
var cur := digit([str]); # get value of current digit
if cur == 0 then rslt := 0; return; end if; # stop when invalid
str := @next str;
if digit([str]) > cur then
# a digit followed by a larger digit should be subtracted from
# the total
rslt := rslt - cur;
else
rslt := rslt + cur;
end if;
end loop;
end sub;
# Read a Roman numeral from the command line and print its output
ArgvInit();
var argmt := ArgvNext();
if argmt == (0 as [uint8]) then
# No argument
print("No argument\n");
ExitWithError();
end if;
print_i16(romanToDecimal(argmt));
print_nl();
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
' Finds and output the roots of a given function f(x),
' within a range of x values.
' [RC]Roots of an function
mainwin 80 12
xMin =-1
xMax = 3
y =f( xMin) ' Since Liberty BASIC has an 'eval(' function the fn
' and limits would be better entered via 'input'.
LastY =y
eps =1E-12 ' closeness acceptable
bigH=0.01
print
print " Checking for roots of x^3 -3 *x^2 +2 *x =0 over range -1 to +3"
print
x=xMin: dx = bigH
do
x=x+dx
y = f(x)
'print x, dx, y
if y*LastY <0 then 'there is a root, should drill deeper
if dx < eps then 'we are close enough
print " Just crossed axis, solution f( x) ="; y; " at x ="; using( "#.#####", x)
LastY = y
dx = bigH 'after closing on root, continue with big step
else
x=x-dx 'step back
dx = dx/10 'repeat with smaller step
end if
end if
loop while x<xMax
print
print " Finished checking in range specified."
end
function f( x)
f =x^3 -3 *x^2 +2 *x
end function
|
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.
|
#J
|
J
|
require'general/misc/prompt strings' NB. was 'misc strings' in older versions of J
game=:3 :0
outcomes=. rps=. 0 0 0
choice=. 1+?3
while.#response=. prompt' Choose Rock, Paper or Scissors: ' do.
playerchoice=. 1+'rps' i. tolower {.deb response
if.4 = playerchoice do.
smoutput 'Unknown response.'
smoutput 'Enter an empty line to quit'
continue.
end.
smoutput ' I choose ',choice {::;:'. Rock Paper Scissors'
smoutput (wintype=. 3 | choice-playerchoice) {:: 'Draw';'I win';'You win'
outcomes=. outcomes+0 1 2 = wintype
rps=. rps+1 2 3=playerchoice
choice=. 1+3|(?0) I.~ (}:%{:)+/\ 0, rps
end.
('Draws:','My wins:',:'Your wins: '),.":,.outcomes
)
|
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.
|
#JavaScript
|
JavaScript
|
function encode(input) {
var encoding = [];
var prev, count, i;
for (count = 1, prev = input[0], i = 1; i < input.length; i++) {
if (input[i] != prev) {
encoding.push([count, prev]);
count = 1;
prev = input[i];
}
else
count ++;
}
encoding.push([count, prev]);
return encoding;
}
|
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.
|
#Sparkling
|
Sparkling
|
function unity_roots(n) {
// nth-root(1) = cos(2 * k * pi / n) + i * sin(2 * k * pi / n)
return map(range(n), function(idx, k) {
return {
"re": cos(2 * k * M_PI / n),
"im": sin(2 * k * M_PI / n)
};
});
}
// pirnt 6th roots of unity
foreach(unity_roots(6), function(k, v) {
printf("%.3f%+.3fi\n", v.re, v.im);
});
|
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.
|
#Stata
|
Stata
|
n=7
exp(2i*pi()/n*(0::n-1))
1
+-----------------------------+
1 | 1 |
2 | .623489802 + .781831482i |
3 | -.222520934 + .974927912i |
4 | -.900968868 + .433883739i |
5 | -.900968868 - .433883739i |
6 | -.222520934 - .974927912i |
7 | .623489802 - .781831482i |
+-----------------------------+
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const type: roots is new struct
var float: x1 is 0.0;
var float: x2 is 0.0;
end struct;
const func roots: solve (in float: a, in float: b, in float: c) is func
result
var roots: solution is roots.value;
local
var float: sd is 0.0;
var float: x is 0.0;
begin
sd := sqrt(b**2 - 4.0 * a * c);
if b < 0.0 then
x := (-b + sd) / 2.0 * a;
solution.x1 := x;
solution.x2 := c / (a * x);
else
x := (-b - sd) / 2.0 * a;
solution.x1 := c / (a * x);
solution.x2 := x;
end if;
end func;
const proc: main is func
local
var roots: r is roots.value;
begin
r := solve(1.0, -10.0E5, 1.0);
writeln("X1 = " <& r.x1 digits 6 <& " X2 = " <& r.x2 digits 6);
end func;
|
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.
|
#Sidef
|
Sidef
|
var sets = [
[1, 2, 1],
[1, 2, 3],
[1, -2, 1],
[1, 0, -4],
[1, -1e6, 1],
]
func quadroots(a, b, c) {
var root = sqrt(b**2 - 4*a*c)
[(-b + root) / (2 * a),
(-b - root) / (2 * a)]
}
sets.each { |coefficients|
say ("Roots for #{coefficients}",
"=> (#{quadroots(coefficients...).join(', ')})")
}
|
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
|
#FBSL
|
FBSL
|
#APPTYPE CONSOLE
REM Create a CircularQueue object
REM CQ.Store item
REM CQ.Find items
REM CQ.Forward nItems
REM CQ.Recall
REM SO CQ init WITH "A"... "Z"
REM CQ.Find "B"
REM QC.Forward 13
REM QC.Recall
CLASS CircularQueue
items[]
head
tail
here
SUB INITIALIZE(dArray)
head = 0
tail = 0
here = 0
FOR DIM i = LBOUND(dArray) TO UBOUND(dArray)
items[tail] = dArray[i]
tail = tail + 1
NEXT
END SUB
SUB TERMINATE()
REM
END SUB
METHOD PUT(s AS STRING)
items[tail] = s
tail = tail + 1
END METHOD
METHOD Find(s AS STRING)
FOR DIM i = head TO tail - 1
IF items[i] = s THEN
here = i
RETURN TRUE
END IF
NEXT
RETURN FALSE
END METHOD
METHOD Move(n AS INTEGER)
DIM bound AS INTEGER = UBOUND(items) + 1
here = (here + n) MOD bound
END METHOD
METHOD Recall()
RETURN items[here]
END METHOD
PROPERTY Size()
RETURN COUNT(items)
END PROPERTY
END CLASS
DIM CQ AS NEW CircularQueue({"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"})
DIM c AS STRING
DIM isUppercase AS INTEGER
DIM s AS STRING = "nowhere ABJURER"
FOR DIM i = 1 TO LEN(s)
c = MID(s, i, 1)
isUppercase = lstrcmp(LCASE(c), c)
IF CQ.Find(UCASE(c)) THEN
CQ.Move(13)
PRINT IIF(isUppercase, UCASE(CQ.Recall()), LCASE(CQ.Recall())) ;
ELSE
PRINT c;
END IF
NEXT
PAUSE
|
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
|
#Xojo
|
Xojo
|
Dim limit, prime, i As Integer
Dim s As String
Dim t As Double
Dim sieve(100000000) As Boolean
REM Get the maximum number
While limit<1 Or limit > 100000000
Print("Max number? [1 to 100000000]")
s = Input
limit = CDbl(s)
Wend
REM Do the calculations
t = Microseconds
prime = 2
While prime^2 < limit
For i = prime*2 To limit Step prime
sieve(i) = True
Next
Do
prime = prime+1
Loop Until Not sieve(prime)
Wend
t = Microseconds-t
Print("Compute time = "+Str(t/1000000)+" sec")
Print("Press Enter...")
s = Input
REM Display the prime numbers
For i = 1 To limit
If Not sieve(i) Then Print(Str(i))
Next
s = Input
|
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
|
#Picat
|
Picat
|
import util.
go =>
Haystack=["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Bush", "Charlie", "Bush", "Boz", "Zag"],
println("First 'Bush'"=search_list(Haystack,"Bush")),
println("Last 'Bush'"=search_list_last(Haystack,"Bush")),
println("All 'Bush'"=search_list_all(Haystack,"Bush")),
catch(WaldoIx=search_list(Haystack,"Waldo"),E,println(E)),
println("Waldo"=WaldoIx),
nl.
% Wrapping find_first_of/2 and find_last_of/2 with exceptions
search_list(Haystack,Needle) = Ix =>
Ix = find_first_of(Haystack,Needle),
if Ix < 0 then
throw $error(search_list(Needle),not_found)
end.
search_list_last(Haystack,Needle) = Ix =>
Ix = find_last_of(Haystack,Needle),
if Ix < 0 then
throw $error(search_list_last(Needle),not_found)
end.
% Find all indices
search_list_all(Haystack,Needle) = Ixs =>
Ixs = [Ix : {W,Ix} in zip(Haystack,1..Haystack.len), W == Needle],
if Ixs == [] then
throw $error(search_list_all(Needle),not_found)
end.
|
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
|
Rosetta Code/Rank languages by popularity
|
Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,540 entries) Phix
Rank: 2 (1,531 entries) Wren
Rank: 3 (1,507 entries) Julia
Rank: 4 (1,494 entries) Go
Rank: 5 (1,488 entries) Raku
Rank: 6 (1,448 entries) Perl
Rank: 7 (1,402 entries) Nim
Rank: 8 (1,382 entries) Python
Rank: 9 (1,204 entries) C
Rank: 10 (1,152 entries) REXX
...
Notes
Each language typically demonstrates one or two methods of accessing the data:
with web scraping (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)
with the API method (examples below for Awk, Perl, Ruby, Tcl, etc).
The scraping and API solutions can be separate subsections, see the Tcl example.
Filtering wrong results is optional. You can check against Special:MostLinkedCategories (if using web scraping)
If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all 869 programming languages, updated periodically, typically weekly.
A complete ranked listing of all 813 languages (from the REXX example) is included here ──► output from the REXX program.
|
#SNOBOL4
|
SNOBOL4
|
-include "url.sno"
http.recl = "K,32767" ;* Read next 32767 characters
;* of very long lines.
rclangs = "http://rosettacode.org/mw/api.php?"
+ "format=xml&action=query&generator=categorymembers&"
+ "gcmtitle=Category:Programming%20Languages&"
+ "gcmlimit=500&prop=categoryinfo"
languagepat = arb "<page" arb 'title="Category:'
+ break('"') . lang arb 'pages="' break('"') . count
langtable = table(500, 20)
url.open(.fin, rclangs, http.recl) :s(read)
output = "Cannot open rosettacode site." :(end)
read line = line fin :f(done)
get line languagepat = :f(read)
langtable<lang> = langtable<lang> + count :(get)
done langarray = rsort(langtable,2) :s(write)
output = "No languages found." :(end)
write n = n + 1
output = lpad(n ". ", 5) lpad(langarray<n, 2>, 4)
+ " - " langarray<n,1> :s(write)
url.close(.fin)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.