task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Ada | Ada | with Ada.Text_IO; with Ada.Numerics.Float_Random;
procedure Rock_Paper_Scissors is
package Rand renames Ada.Numerics.Float_Random;
Gen: Rand.Generator;
type Choice is (Rock, Paper, Scissors);
Cnt: array (Choice) of Natural := (1, 1, 1);
-- for the initialization: pretend that each of Rock, Pape... |
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... | #Clojure | Clojure | (defn compress [s]
(->> (partition-by identity s) (mapcat (juxt count first)) (apply str)))
(defn extract [s]
(->> (re-seq #"(\d+)([A-Z])" s)
(mapcat (fn [[_ n ch]] (repeat (Integer/parseInt n) ch)))
(apply str))) |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Fortran | Fortran | PROGRAM Roots
COMPLEX :: root
INTEGER :: i, n
REAL :: angle, pi
pi = 4.0 * ATAN(1.0)
DO n = 2, 7
angle = 0.0
WRITE(*,"(I1,A)", ADVANCE="NO") n,": "
DO i = 1, n
root = CMPLX(COS(angle), SIN(angle))
WRITE(*,"(SP,2F7.4,A)", ADVANCE="NO") root, "j "
angle = angle + (2.0*pi / RE... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #FreeBASIC | FreeBASIC | #define twopi 6.2831853071795864769252867665590057684
dim as uinteger m, n
dim as double real, imag, theta
input "n? ", n
for m = 0 to n-1
theta = m*twopi/n
real = cos(theta)
imag = sin(theta)
if imag >= 0 then
print using "#.##### + #.##### i"; real; imag
else
print using "#.###... |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Julia | Julia | using Gumbo, AbstractTrees, HTTP, JSON, Dates
rosorg = "http://rosettacode.org"
qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json"
sqU... |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Kotlin | Kotlin | import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.regex.Pattern
import java.util.stream.Collectors
const val BASE = "http://rosettacode.org"
fun main() {
val client = HttpClient.newBuilder().build()
val titleUri = URI.cr... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Forth | Forth | : quadratic ( fa fb fc -- r1 r2 )
frot frot
( c a b )
fover 3 fpick f* -4e f* fover fdup f* f+
( c a b det )
fdup f0< if abort" imaginary roots" then
fsqrt
fover f0< if fnegate then
f+ fnegate
( c a b-det )
2e f/ fover f/
( c a r1 )
frot frot f/ fover f/ ; |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Fortran | Fortran | PROGRAM QUADRATIC
IMPLICIT NONE
INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15)
REAL(dp) :: a, b, c, e, discriminant, rroot1, rroot2
COMPLEX(dp) :: croot1, croot2
WRITE(*,*) "Enter the coefficients of the equation ax^2 + bx + c"
WRITE(*, "(A)", ADVANCE="NO") "a = "
READ *, a
WRITE(*,"(A)", ADVANCE="NO") "... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #BCPL | BCPL | get "libhdr"
let rot13(x) =
'A' <= x <= 'Z' -> (x - 'A' + 13) rem 26 + 'A',
'a' <= x <= 'z' -> (x - 'a' + 13) rem 26 + 'a',
x
let start() be
$( let ch = rdch()
if ch = endstreamch then break
wrch(rot13(ch))
$) repeat |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Liberty_BASIC | Liberty BASIC |
'[RC] Runge-Kutta method
'initial conditions
x0 = 0
y0 = 1
'step
h = 0.1
'number of points
N=101
y=y0
FOR i = 0 TO N-1
x = x0+ i*h
IF x = INT(x) THEN
actual = exactY(x)
PRINT "y("; x ;") = "; y; TAB(20); "Error = "; actual - y
END IF
k1 = h*dydx(x,y)
k2 = h*dydx(x+h/2,y+k1/2)
... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #Phix | Phix | -- demo\rosetta\Find_unimplemented_tasks.exw
without js -- (libcurl, file i/o, peek, progress..)
constant language = "Phix",
-- language = "Go",
-- language = "Julia",
-- language = "Python",
-- language = "Wren",
base_query = "http://rosettacode.org/mw/api.php?action=query"&
... |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #Lua | Lua | lpeg = require 'lpeg' -- see http://www.inf.puc-rio.br/~roberto/lpeg/
imports = 'P R S C V match'
for w in imports:gmatch('%a+') do _G[w] = lpeg[w] end -- make e.g. 'lpeg.P' function available as 'P'
function tosymbol(s) return s end
function tolist(x, ...) return {...} end -- ignore the first capture, the whole s... |
http://rosettacode.org/wiki/RPG_attributes_generator | RPG attributes generator | RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three... | #min | min | randomize ; Seed the rng with current timestamp.
; Implement some general operators we'll need that aren't in the library.
(() 0 shorten) :new
((new (over -> swons)) dip times nip) :replicate
(('' '' '') => spread if) :if?
((1 0 if?) concat map sum) :count
(5 random succ) :d6 ; Ro... |
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... | #MiniScript | MiniScript | roll = function()
results = []
for i in range(0,3)
results.push ceil(rnd * 6)
end for
results.sort
results.remove 0
return results.sum
end function
while true
attributes = []
gt15 = 0 // (how many attributes > 15)
for i in range(0,5)
attributes.push roll
... |
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... | #Scala | Scala | import scala.annotation.tailrec
import scala.collection.parallel.mutable
import scala.compat.Platform
object GenuineEratosthenesSieve extends App {
def sieveOfEratosthenes(limit: Int) = {
val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt)
@tailrec
... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #jq | jq | #!/bin/bash
# Produce lines of the form: URI TITLE
function titles {
local uri="http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers"
uri+="&cmtitle=Category:Programming_Tasks&cmlimit=5000&format=json"
curl -Ss "$uri" |
jq -r '.query.categorymembers[] | .title | "\(@uri) \(.)"'
}
... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #Julia | Julia | using HTTP, JSON, Dates
rosorg = "http://rosettacode.org"
qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json"
sqURI = rosorg * "/wiki/"... |
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 ... | #K | K | Haystack:("Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo")
Needles:("Washington";"Bush")
{:[y _in x;(y;x _bin y);(y;"Not Found")]}[Haystack]'Needles |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity | Rosetta Code/Rank languages by popularity | Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,... | #Julia | Julia | using HTTP
try
response = HTTP.request("GET", "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000")
langcount = Dict{String, Int}()
for mat in eachmatch(r"<li><a href[^\>]+>([^\<]+)</a>[^1-9]+(\d+)[^\w]+member.?.?</li>", String(response.body))
if match(r"^Programming", mat.cap... |
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 numeral... | #8080_Assembly | 8080 Assembly | org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Takes a 16-bit integer in HL, and stores it
;; as a 0-terminated string starting at BC.
;; On exit, all registers destroyed; BC pointing at
;; end of string.
mkroman: push h ; put input on stack
lxi h,mkromantab
mkromandgt: mov a,m ; scan ahead ... |
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 decima... | #Action.21 | Action! | CARD FUNC DecodeRomanDigit(CHAR c)
IF c='I THEN RETURN (1)
ELSEIF c='V THEN RETURN (5)
ELSEIF c='X THEN RETURN (10)
ELSEIF c='L THEN RETURN (50)
ELSEIF c='C THEN RETURN (100)
ELSEIF c='D THEN RETURN (500)
ELSEIF c='M THEN RETURN (1000)
FI
RETURN (0)
CARD FUNC DecodeRomanNumber(CHAR ARRAY s)
CARD res... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Axiom | Axiom | expr := x^3-3*x^2+2*x
solve(expr,x) |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #BBC_BASIC | BBC BASIC | function$ = "x^3-3*x^2+2*x"
rangemin = -1
rangemax = 3
stepsize = 0.001
accuracy = 1E-8
PROCroots(function$, rangemin, rangemax, stepsize, accuracy)
END
DEF PROCroots(func$, min, max, inc, eps)
LOCAL x, sign%, oldsign%
oldsign% = 0
FOR x = min TO max S... |
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:
... | #Aime | Aime | text
computer_play(record plays, record beats)
{
integer a, c, total;
text s;
total = plays["rock"] + plays["paper"] + plays["scissors"];
a = drand(total - 1);
for (s, c in plays) {
if (a < c) {
break;
}
a -= c;
}
beats[s];
}
integer
main(void)
{
... |
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... | #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. run-length-encoding.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION encode
FUNCTION decode
.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 input-str PIC A(100).
01 encoded PIC ... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Frink | Frink |
roots[n] :=
{
a = makeArray[[n], 0]
alpha = 360/n degrees
theta = 0 degrees
for k = 0 to length[a] - 1
{
a@k = cos[theta] + i sin[theta]
theta = theta + alpha
}
a
}
|
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #FunL | FunL | import math.{exp, Pi}
def rootsOfUnity( n ) = {exp( 2Pi i k/n ) | k <- 0:n}
println( rootsOfUnity(3) ) |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Maple | Maple | #Did not count the tasks where languages tasks are properly closed
add_lan := proc(language, n, existence, languages, pos)
if (assigned(existence[language])) then
existence[language] += n:
return pos;
else
existence[language] := n:
languages(pos) := language:
return pos+1;
end if;
end proc:
count_tags := ... |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | tasks[page_: ""] :=
Module[{res =
Import["http://rosettacode.org/mw/api.php?format=xml&action=\
query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=\
500" <> page, "XML"]},
If[MemberQ[res[[2, 3]], XMLElement["query-continue", __]],
Join[res[[2, 3, 1, 3, 1, 3, All, 2, 3, 2]],
ta... |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Nim | Nim | import algorithm, htmlparser, httpclient, json
import sequtils, strformat, strscans, tables, times, xmltree
import strutils except escape
const
Rosorg = "http://rosettacode.org"
QUri = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json"
QdUri = "/mw/api.p... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #FreeBASIC | FreeBASIC | ' version 20-12-2020
' compile with: fbc -s console
#Include Once "gmp.bi"
Sub solvequadratic_n(a As Double ,b As Double, c As Double)
Dim As Double f, d = b ^ 2 - 4 * a * c
Select Case Sgn(d)
Case 0
Print "1: the single root is "; -b / 2 / a
Case 1
Print "1: the ... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Befunge | Befunge | ~:"z"`#v_:"m"`#v_:"`"` |>
:"Z"`#v_:"M"`#v_:"@"`|>
: 0 `#v_@v-6-7< >
, < <+6+7 <<v |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (* Symbolic solution *)
DSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, t]
Table[{t, 1/16 (4 + t^2)^2}, {t, 0, 10}]
(* Numerical solution I (not RK4) *)
Table[{t, y[t], Abs[y[t] - 1/16*(4 + t^2)^2]}, {t, 0, 10}] /.
First@NDSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, {t, 0, 10}]
(* Numerical solution II (RK4) *)
f... |
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:
... | #MATLAB | MATLAB | function testRK4Programs
figure
hold on
t = 0:0.1:10;
y = 0.0625.*(t.^2+4).^2;
plot(t, y, '-k')
[tode4, yode4] = testODE4(t);
plot(tode4, yode4, '--b')
[trk4, yrk4] = testRK4(t);
plot(trk4, yrk4, ':r')
legend('Exact', 'ODE4', 'RK4')
hold off
fprintf('Time\tExactVal\tODE4V... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #PicoLisp | PicoLisp | (load "@lib/http.l" "@lib/xm.l")
(de rosettaCategory (Cat)
(let (Cont NIL Xml)
(make
(loop
(client "rosettacode.org" 80
(pack
"mw/api.php?action=query&list=categorymembers&cmtitle=Category:"
Cat
"&cmlimit=200&format=xm... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #PowerShell | PowerShell |
function Find-UnimplementedTask
{
[CmdletBinding()]
[OutputType([string[]])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[string]
$Language
)
$url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_$Language"
$web = Invoke-WebR... |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #Nim | Nim | import strutils
const Input = """
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
"""
type
TokenKind = enum
tokInt, tokFloat, tokString, tokIdent
tokLPar, tokRPar
tokEnd
Token = object
case kind: TokenKind
of tokString: stringVal: string
of tokInt: intVal: int
of t... |
http://rosettacode.org/wiki/RPG_attributes_generator | RPG attributes generator | RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three... | #Nim | Nim |
# Import "random" to get random numbers and "algorithm" to get sorting functions for arrays.
import random, algorithm
randomize()
proc diceFourRolls(): array[4, int] =
## Generates 4 random values between 1 and 6.
for i in 0 .. 3:
result[i] = rand(1..6)
proc sumRolls(rolls: array[4, int]): int =
## Sa... |
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... | #Scheme | Scheme | ; Tail-recursive solution :
(define (sieve n)
(define (aux u v)
(let ((p (car v)))
(if (> (* p p) n)
(let rev-append ((u u) (v v))
(if (null? u) v (rev-append (cdr u) (cons (car u) v))))
(aux (cons p u)
(let wheel ((u '()) (v (cdr v)) (a (* p p)))
(cond ((null... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #Lasso | Lasso | local(root = json_deserialize(curl('http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=json')->result))
local(tasks = array, title = string, urltitle = string, thiscount = 0, totalex = 0)
with i in #root->find('query')->find('categorymembers') do => ... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #LiveCode | LiveCode | on mouseUp
put empty into fld "taskurls"
put URL "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=10&format=xml" into apixml
put revXMLCreateTree(apixml,true,true,false) into pDocID
put "/api/query/categorymembers/cm" into pXPathExpression
... |
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 ... | #Kotlin | Kotlin | // version 1.0.6 (search_list.kt)
fun main(args: Array<String>) {
val haystack = listOf("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag")
println(haystack)
var needle = "Zag"
var index = haystack.indexOf(needle)
val index2 = haystack.lastIndexOf(needle)
print... |
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,... | #Kotlin | Kotlin | import java.net.URL
import java.io.*
object Popularity {
/** Gets language data. */
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=... |
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 numeral... | #8086_Assembly | 8086 Assembly | mov ax,0070h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,1776h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,2021h
call EncodeRoman
mov si,offset StringRam
call PrintString
call NewLine
mov ax,3999h
call EncodeRoman
mov si,offset... |
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 decima... | #Ada | Ada | Pragma Ada_2012;
Pragma Assertion_Policy( Check );
With
Unchecked_Conversion,
Ada.Text_IO;
Procedure Test_Roman_Numerals is
-- We create an enumeration of valid characters, note that they are
-- character-literals, this is so that we can use literal-strings,
-- and that their size is that of Integer.
... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #C | C | #include <math.h>
#include <stdio.h>
double f(double x)
{
return x*x*x-3.0*x*x +2.0*x;
}
double secant( double xA, double xB, double(*f)(double) )
{
double e = 1.0e-12;
double fA, fB;
double d;
int i;
int limit = 50;
fA=(*f)(xA);
for (i=0; i<limit; i++) {
fB=(*f)(xB);
... |
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:
... | #ALGOL_68 | ALGOL 68 | BEGIN
# rock/paper/scissors game #
# counts of the number of times the player has chosen each move #
# we initialise each to 1 so that the total isn't zero when we are #
# choosing the computer's first move (as in the Ada version) #
IN... |
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... | #CoffeeScript | CoffeeScript | encode = (str) ->
str.replace /(.)\1*/g, (w) ->
w[0] + w.length
decode = (str) ->
str.replace /(.)(\d+)/g, (m,w,n) ->
new Array(+n+1).join(w)
console.log s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
console.log encode s
console.log decode encode s |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #FutureBasic | FutureBasic | window 1, @"Roots of Unity", (0,0,1050,200)
long n, root
double real, imag
for n = 2 to 7
print n;":" ;
for root = 0 to n-1
real = cos( 2 * pi * root / n)
imag = sin( 2 * pi * root / n)
print using "-##.#####"; real;using "-##.#####"; imag; "i";
if root != n-1 then print ",";
next
print
next... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #GAP | GAP | roots := n -> List([0 .. n-1], k -> E(n)^k);
r:=roots(7);
# [ 1, E(7), E(7)^2, E(7)^3, E(7)^4, E(7)^5, E(7)^6 ]
List(r, x -> x^7);
# [ 1, 1, 1, 1, 1, 1, 1 ] |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Objeck | Objeck | use Web.HTTP;
use Query.RegEx;
use Collection.Generic;
class Program {
function : Main(args : String[]) ~ Nil {
master_tasks := ProcessTasks(["100_doors", "99_bottles_of_beer", "Filter", "Array_length", "Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"]);
"---"->PrintLine... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #GAP | GAP | QuadraticRoots := function(a, b, c)
local d;
d := Sqrt(b*b - 4*a*c);
return [ (-b+d)/(2*a), (-b-d)/(2*a) ];
end;
# Hint : E(12) is a 12th primitive root of 1
QuadraticRoots(2, 2, -1);
# [ 1/2*E(12)^4-1/2*E(12)^7+1/2*E(12)^8+1/2*E(12)^11,
# 1/2*E(12)^4+1/2*E(12)^7+1/2*E(12)^8-1/2*E(12)^11 ]
# This works also... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Go | Go | package main
import (
"fmt"
"math"
)
func qr(a, b, c float64) ([]float64, []complex128) {
d := b*b-4*a*c
switch {
case d == 0:
// single root
return []float64{-b/(2*a)}, nil
case d > 0:
// two real roots
if b < 0 {
d = math.Sqrt(d)-b
} else... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Burlesque | Burlesque |
blsq ) "HELLO WORLD"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww
"URYYB JBEYQ"
blsq ) "URYYB JBEYQ"{{'A'Zr\\/Fi}m[13?+26.%'A'Zr\\/si}ww
"HELLO WORLD"
|
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Maxima | Maxima | /* Here is how to solve a differential equation */
'diff(y, x) = x * sqrt(y);
ode2(%, y, x);
ic1(%, x = 0, y = 1);
factor(solve(%, y)); /* [y = (x^2 + 4)^2 / 16] */
/* The Runge-Kutta solver is builtin */
load(dynamics)$
sol: rk(t * sqrt(y), y, 1, [t, 0, 10, 1.0])$
plot2d([discrete, sol])$
/* An implementation of... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #Python | Python | """
Given the name of a language on Rosetta Code,
finds all tasks which are not implemented in that language.
"""
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
... |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #OCaml | OCaml | (** This module is a very simple parsing library for S-expressions. *)
(* Copyright (C) 2009 Florent Monnier, released under MIT license. *)
type sexpr = Atom of string | Expr of sexpr list
(** the type of S-expressions *)
val parse_string : string -> sexpr list
(** parse from a string *)
val parse_ic : in_chann... |
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... | #OCaml | OCaml |
(* Task : RPG_attributes_generator *)
(*
A programmatic solution to generating character attributes for an RPG
*)
(* Generates random whole values between 1 and 6. *)
let rand_die () : int = Random.int 6
(* Generates 4 random values and saves the sum of the 3 largest *)
let rand_attr () : int =
let four_ro... |
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... | #Scilab | Scilab | function a = sieve(n)
a = ~zeros(n, 1)
a(1) = %f
for i = 1:n
if a(i)
j = i*i
if j > n
return
end
a(j:i:n) = %f
end
end
endfunction
find(sieve(100))
// [2 3 5 ... 97]
sum(sieve(1000))
// 168, the number of primes below 10... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #Maple | Maple | ConvertUTF8 := proc( str )
local i, tempstring, uniindex;
try
tempstring := str;
uniindex := [StringTools:-SearchAll("\u",str)];
if uniindex <> [] then
for i in uniindex do
tempstring := StringTools:-Substitute(tempstring, str[i..i+5], U... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | TaskList = Flatten[
Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]];
Print["Task \"", StringReplace[#, "_" -> " "], "\" has ",
Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]],
StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]& ... |
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 ... | #Lang5 | Lang5 | : haystack(*) ['rosetta 'code 'search 'a 'list 'lang5 'code] find-index ;
: find-index
2dup eq length iota swap select swap drop
length if swap drop
else drop " is not in haystack" 2 compress "" join
then ;
: ==>search apply ;
['hello 'code] 'haystack ==>search . |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity | Rosetta Code/Rank languages by popularity | Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,... | #Lasso | Lasso | <pre><code>[
sys_listtraits !>> 'xml_tree_trait' ? include('xml_tree.lasso')
local(lang = array)
local(f = curl('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000')->result->asString)
local(ff) = xml_tree(#f)
local(lis = #ff->body->div(3)->div(3)->div(3)->div->ul->getnodes)
with li in #lis do =>... |
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 numeral... | #Action.21 | Action! | DEFINE PTR="CARD"
CARD ARRAY arabic=[1000 900 500 400 100 90 50 40 10 9 5 4 1]
PTR ARRAY roman(13)
PROC InitRoman()
roman(0)="M" roman(1)="CM" roman(2)="D" roman(3)="CD"
roman(4)="C" roman(5)="XC" roman(6)="L" roman(7)="XL"
roman(8)="X" roman(9)="IX" roman(10)="V" roman(11)="IV" roman(12)="I"
RETURN
PROC Enco... |
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 decima... | #ALGOL_68 | ALGOL 68 | PROC roman to int = (STRING roman) INT:
BEGIN
PROC roman digit value = (CHAR roman digit) INT:
(roman digit = "M" | 1000 |:
roman digit = "D" | 500 |:
roman digit = "C" | 100 |:
roman digit = "L" | 50 |:
roman digit = "X" | 10 |:
... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #C.23 | C# | using System;
class Program
{
public static void Main(string[] args)
{
Func<double, double> f = x => { return x * x * x - 3 * x * x + 2 * x; };
double step = 0.001; // Smaller step values produce more accurate and precise results
double start = -1;
double stop = 3;
do... |
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:
... | #AutoHotkey | AutoHotkey | DllCall("AllocConsole")
Write("Welcome to Rock-Paper-Scissors`nMake a choice: ")
cR := cP := cS := 0 ; user choice count
userChoice := Read()
Write("My choice: " . cpuChoice := MakeChoice(1, 1, 1))
Loop
{
Write(DecideWinner(userChoice, cpuChoice) . "`nMake A Choice: ")
cR += SubStr(userChoice, 1, 1) = "r", cP += ... |
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... | #Common_Lisp | Common Lisp | (defun group-similar (sequence &key (test 'eql))
(loop for x in (rest sequence)
with temp = (subseq sequence 0 1)
if (funcall test (first temp) x)
do (push x temp)
else
collect temp
and do (setf temp (list x))))
(defun run-length-encode (sequence)
(mapcar (lam... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Go | Go | package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
fo... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Groovy | Groovy | /** The following closure creates a list of n evenly-spaced points around the unit circle,
* useful in FFT calculations, among other things */
def rootsOfUnity = { n ->
(0..<n).collect {
Complex.fromPolar(1, 2 * Math.PI * it / n)
}
} |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Perl | Perl | my $lang = 'no language';
my $total = 0;
my %blanks = ();
while (<>) {
if (m/<lang>/) {
if (exists $blanks{lc $lang}) {
$blanks{lc $lang}++
} else {
$blanks{lc $lang} = 1
}
$total++
} elsif (m/==\s*\{\{\s*header\s*\|\s*([^\s\}]+)\s*\}\}\s*==/) {
$lang = lc $1
}
}
if ($total) {
p... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Haskell | Haskell | import Data.Complex (Complex, realPart)
type CD = Complex Double
quadraticRoots :: (CD, CD, CD) -> (CD, CD)
quadraticRoots (a, b, c)
| 0 < realPart b =
( (2 * c) / (- b - d),
(- b - d) / (2 * a)
)
| otherwise =
( (- b + d) / (2 * a),
(2 * c) / (- b + d)
)
where
d = sqrt $ b ^ 2... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #C | C | #include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static char rot13_table[UCHAR_MAX + 1];
static void init_rot13_table(void) {
static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz";
for (int ch = '\0'; ch... |
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:
... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ПП 38 П1 ПП 30 П2 ПП 35 П3 2
* ПП 30 ИП2 ИП3 + 2 * + ИП1
+ 3 / ИП7 + П7 П8 С/П БП 00
ИП6 ИП5 + П6 <-> ИП7 + П8
ИП8 КвКор ИП6 *
ИП5 * В/О |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Nim | Nim | import math
proc fn(t, y: float): float =
result = t * math.sqrt(y)
proc solution(t: float): float =
result = (t^2 + 4)^2 / 16
proc rk(start, stop, step: float) =
let nsteps = int(round((stop - start) / step)) + 1
let delta = (stop - start) / float(nsteps - 1)
var cur_y = 1.0
for i in 0..(... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #R | R | library(XML)
find.unimplemented.tasks <- function(lang="R"){
PT <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml",sep="") )
PT.nodes <- getNodeSet(PT,"//cm")
PT.titles = as.character( sapply(PT.nodes, xmlG... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #Racket | Racket |
#lang racket
(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref]))
(define (RC-get verb params)
((compose1 get-pure-port string->url format)
"http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params)))
(define (get-category catname)
(let loop ([c #f])
(define t
... |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #Perl | Perl | #!/usr/bin/perl -w
use strict;
use warnings;
sub sexpr
{
my @stack = ([]);
local $_ = $_[0];
while (m{
\G # start match right at the end of the previous one
\s*+ # skip whitespaces
# now try to match any of possible tokens in THIS order:
(?<lparen>\() |
(?<rparen>\)) |
(?<FLOAT>[0-9]*+\.[0-9]*+) ... |
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... | #Pascal | Pascal |
program attributes;
var
total, roll,score, count: integer;
atribs : array [1..6] of integer;
begin
randomize; {Initalise the random number genertor}
repeat
count:=0;
total:=0;
for score :=1 to 6 do begin
{roll:=random(18)+1; produce a number up to 18, pretty muc... |
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... | #Scratch | Scratch |
when clicked
broadcast: fill list with zero (0) and wait
broadcast: put one (1) in list of multiples and wait
broadcast: fill primes where zero (0 in list
when I receive: fill list with zero (0)
delete all of primes
delete all of list
set i to 0
set maximum to 25
repeat maximum
... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #MATLAB_.2F_Octave | MATLAB / Octave | function c = count_examples(url)
c = 0;
[s, success] = urlread (url);
if ~success, return; end;
c = length(strfind(s,'<h2><span class='));
end;
% script
s = urlread ('http://rosettacode.org/wiki/Category:Programming_Tasks');
pat = '<li><a href="/wiki/';
ix = strfind(s,pat)+length(pat)... |
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 ... | #Lasso | Lasso | local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')
#haystack->findindex('Bush')->first // 5
#haystack->findindex('Bush')->last // 8
protect => {^
handle_error => {^ error_msg ^}
fail_if(not #haystack->findindex('Washington')->first,'Washington is not in... |
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,... | #M2000_Interpreter | M2000 Interpreter |
Module RankLanguages {
Const Part1$="<a href="+""""+ "/wiki/Category", Part2$="member"
Const langHttp$="http://rosettacode.org/wiki/Category:Programming_Languages"
Const categoriesHttp$="http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
Def long m, i,j, tasks, counte... |
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 numeral... | #ActionScript | ActionScript | function arabic2roman(num:Number):String {
var lookup:Object = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
var roman:String = "", i:String;
for (i in lookup) {
while (num >= lookup[i]) {
roman += i;
num -= lookup[i];
}
}
return roman;
}
trace("1990 in roman is ... |
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 decima... | #ALGOL_W | ALGOL W | begin
% decodes a roman numeral into an integer %
% there must be at least one blank after the numeral %
% This takes a lenient view on roman numbers so e.g. IIXX is 18 - see %
% the Discussion ... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #C.2B.2B | C++ | #include <iostream>
double f(double x)
{
return (x*x*x - 3*x*x + 2*x);
}
int main()
{
double step = 0.001; // Smaller step values produce more accurate and precise results
double start = -1;
double stop = 3;
double value = f(start);
double sign = (value > 0);
// Check for root at start
if ( 0 == value )
... |
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:
... | #AutoIt | AutoIt |
RPS()
Func RPS()
Local $ai_Played_games[4]
$ai_Played_games[0] = 3
For $I = 1 To 3
$ai_Played_games[$I] = 1
Next
$RPS = GUICreate("Rock Paper Scissors", 338, 108, 292, 248)
$Rock = GUICtrlCreateButton("Rock", 8, 8, 113, 25, 131072)
$Paper = GUICtrlCreateButton("Paper", 8, 40, 113, 25, 131072)
$Scissors = ... |
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... | #D | D | import std.algorithm, std.array;
alias encode = group;
auto decode(Group!("a == b", string) enc) {
return enc.map!(t => [t[0]].replicate(t[1])).join;
}
void main() {
immutable s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW" ~
"WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
assert(s.encode.decode.equal... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Haskell | Haskell | import Data.Complex (Complex, cis)
rootsOfUnity :: (Enum a, Floating a) => a -> [Complex a]
rootsOfUnity n =
[ cis (2 * pi * k / n)
| k <- [0 .. n - 1] ]
main :: IO ()
main = mapM_ print $ rootsOfUnity 3 |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
roots(10)
end
procedure roots(n)
every n := 2 to 10 do
every writes(n | (str_rep((0 to (n-1)) * 2 * &pi / n)) | "\n")
end
procedure str_rep(k)
return " " || cos(k) || "+" || sin(k) || "i"
end |
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags | Rosetta Code/Find bare lang tags | Task
Find all <lang> tags without a language specified in the text of a page.
Display counts by language section:
Description
<lang>Pseudocode</lang>
=={{header|C}}==
<lang C>printf("Hello world!\n");</lang>
=={{header|Perl}}==
<lang>print "Hello world!\n"</lang>
should display something like
2 bare langu... | #Phix | Phix | --
-- demo\rosetta\Find_bare_lang_tags.exw
-- ====================================
--
-- (Uses '&' instead of/as well as 'a', for everyone's sanity..)
-- Finds/counts no of "<l&ng>" as opposed to eg "<l&ng Phix>" tags.
-- Since downloading all the pages can be very slow, this uses a cache.
--
without js -- (fairly o... |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Icon_and_Unicon | Icon and Unicon | procedure main()
solve(1.0, -10.0e5, 1.0)
end
procedure solve(a,b,c)
d := sqrt(b*b - 4.0*a*c)
roots := if b < 0 then [r1 := (-b+d)/(2.0*a), c/(a*r1)]
else [r1 := (-b-d)/(2.0*a), c/(a*r1)]
write(a,"*x^2 + ",b,"*x + ",c," has roots ",roots[1]," and ",roots[2])
end |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #C.23 | C# | using System;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static char Rot13(char c)
{
if ('a' <= c && c <= 'm' || 'A' <= c && c <= 'M')
{
return (char)(c + 13);
}
if ('n' <= c && c <= 'z' || 'N' <= c && c <= 'Z')
{
retu... |
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:
... | #Objeck | Objeck | class RungeKuttaMethod {
function : Main(args : String[]) ~ Nil {
x0 := 0.0; x1 := 10.0; dx := .1;
n := 1 + (x1 - x0)/dx;
y := Float->New[n->As(Int)];
y[0] := 1;
for(i := 1; i < n; i++;) {
y[i] := Rk4(Rate(Float, Float) ~ Float, dx, x0 + dx * (i - 1), y[i-1]);
};
for(i := 0; ... |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #Raku | Raku | use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Sort::Naturally;
unit sub MAIN( Str :$lang = 'Raku' );
my $client = HTTP::UserAgent.new;
my $url = 'http://rosettacode.org/mw';
my @total;
my @impl;
@total.append: .&get-cat for 'Programming_Tasks', 'Draft_Programming_Tasks';
@impl = get-cat $lang;
say... |
http://rosettacode.org/wiki/S-expressions | S-expressions | S-Expressions are one convenient way to parse and store data.
Task
Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.
The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).
... | #Phix | Phix | with javascript_semantics
constant s_expr_str = """
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))"""
function skip_spaces(string s, integer sidx)
while sidx<=length(s) and find(s[sidx],{' ','\t','\r','\n'}) do sidx += 1 end while
return sidx
end function
function get_term(string s, inte... |
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... | #Perl | Perl | use strict;
use List::Util 'sum';
my ($min_sum, $hero_attr_min, $hero_count_min) = <75 15 3>;
my @attr_names = <Str Int Wis Dex Con Cha>;
sub heroic { scalar grep { $_ >= $hero_attr_min } @_ }
sub roll_skip_lowest {
my($dice, $sides) = @_;
sum( (sort map { 1 + int rand($sides) } 1..$dice)[1..$dice-1] );
}... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func set of integer: eratosthenes (in integer: n) is func
result
var set of integer: sieve is EMPTY_SET;
local
var integer: i is 0;
var integer: j is 0;
begin
sieve := {2 .. n};
for i range 2 to sqrt(n) do
if i in sieve then
for j range i ** 2 to... |
http://rosettacode.org/wiki/Rosetta_Code/Count_examples | Rosetta Code/Count examples | task
Essentially, count the number of occurrences of =={{header| on each task page.
Output:
100 doors: 20 examples.
99 Bottles of Beer: 29 examples.
Abstract type: 10 examples.
Total: X examples.
For a full output, updated periodically, see Rosetta Code/Count examples/Full list.
You'll need to use the Media Wiki AP... | #Nim | Nim | import httpclient, strutils, xmltree, xmlparser, cgi
proc count(s, sub: string): int =
var i = 0
while true:
i = s.find(sub, i)
if i < 0: break
inc i
inc result
const
mainSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=... |
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 ... | #Liberty_BASIC | Liberty BASIC | haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
needle$="needle"
'index of first occurrence
for i = 1 to t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.