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/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.
| #Nim | Nim | import complex, math, sequtils, strformat, strutils
proc roots(n: Positive): seq[Complex64] =
for k in 0..<n:
result.add rect(1.0, 2 * k.float * Pi / n.float)
proc toString(z: Complex64): string =
&"{z.re:.3f} + {z.im:.3f}i"
for nr in 2..10:
let result = roots(nr).map(toString).join(", ")
echo &"{nr: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.
| #OCaml | OCaml | open Complex
let pi = 4. *. atan 1.
let () =
for n = 1 to 10 do
Printf.printf "%2d " n;
for k = 1 to n do
let ret = polar 1. (2. *. pi *. float_of_int k /. float_of_int n) in
Printf.printf "(%f + %f i)" ret.re ret.im
done;
print_newline ()
done |
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... | #Nim | Nim | import math, complex, strformat
const Epsilon = 1e-15
type
SolKind = enum solDouble, solFloat, solComplex
Roots = object
case kind: SolKind
of solDouble:
fvalue: float
of solFloat:
fvalues: (float, float)
of solComplex:
cvalues: (Complex64, Complex64)
func quadRoots(a, ... |
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... | #OCaml | OCaml | type quadroots =
| RealRoots of float * float
| ComplexRoots of Complex.t * Complex.t ;;
let quadsolve a b c =
let d = (b *. b) -. (4.0 *. a *. c) in
if d < 0.0
then
let r = -. b /. (2.0 *. a)
and i = sqrt(-. d) /. (2.0 *. a) in
ComplexRoots ({ Complex.re = r; Complex.im = i },
... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | rot-13:
)
for ch in chars swap:
ord ch
if <= 65 dup:
if >= 90 dup:
+ 13 - swap 65
+ 65 % swap 26
if <= 97 dup:
if >= 122 dup:
+ 13 - swap 97
+ 97 % swap 26
chr
concat(
!print rot-13 "Snape kills Frodo with Rosebud." |
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:
... | #Raku | Raku | sub runge-kutta(&yp) {
return -> \t, \y, \δt {
my $a = δt * yp( t, y );
my $b = δt * yp( t + δt/2, y + $a/2 );
my $c = δt * yp( t + δt/2, y + $b/2 );
my $d = δt * yp( t + δt, y + $c );
($a + 2*($b + $c) + $d) / 6;
}
}
constant δt = .1;
my &δy = runge-kutta { $^t * sqrt(... |
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).
... | #Sidef | Sidef | func sexpr(txt) {
txt.trim!
if (txt.match(/^\((.*)\)$/s)) {|m|
txt = m[0]
}
else {
die "Invalid: <<#{txt}>>"
}
var w
var ret = []
while (!txt.is_empty) {
given (txt.first) {
when('(') {
(w, txt) = txt.extract_bracketed('()');
... |
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... | #Ring | Ring |
# Project : RPG Attributes Generator
load "stdlib.ring"
attributestotal = 0
count = 0
while attributestotal < 75 or count < 2
attributes = []
for attribute = 0 to 6
rolls = []
largest3 = []
for roll = 0 to 4
result = random(5)+1
... |
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... | #Ruby | Ruby | res = []
until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do
res = Array.new(6) do
a = Array.new(4){rand(1..6)}
a.sum - a.min
end
end
p res
puts "sum: #{res.sum}"
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #UNIX_Shell | UNIX Shell | function primes {
typeset -a a
typeset i j
a[1]=""
for (( i = 2; i <= $1; i++ )); do
a[$i]=$i
done
for (( i = 2; i * i <= $1; i++ )); do
if [[ ! -z ${a[$i]} ]]; then
for (( j = i * i; j <= $1; j += i )); do
a[$j]=""
done
fi
done
printf '%s' "${a[2]}"
printf ' %s' ${a[*]... |
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... | #Sidef | Sidef | var lwp = require('LWP::UserAgent').new(agent => 'Mozilla/5.0');
var site = 'http://rosettacode.org';
var list_url = '/mw/api.php?action=query&list=categorymembers&'+
'cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml';
var content = lwp.get(site + list_url).decoded_content;
while (var m = ... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require http
package require json
fconfigure stdout -buffering none
proc get_tasks {category} {
set start [clock milliseconds]
puts -nonewline "getting $category members..."
set base_url http://www.rosettacode.org/w/api.php
set query {action query list categorymembers... |
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 ... | #Objeck | Objeck | use Collection;
class Test {
function : Main(args : String[]) ~ Nil {
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
values := CompareVector->New();
each(i : haystack) {
values->AddBack(haystack[i]->As(Compare));
};
needles := ["Washington", "Bush"];
... |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity | Rosetta Code/Rank languages by popularity | Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,... | #Python | Python | import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3] # strip last 3
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.su... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
set cnt=0&for %%A in (1000,900,500,400,100,90,50,40,10,9,5,4,1) do (set arab!cnt!=%%A&set /a cnt+=1)
set cnt=0&for %%R in (M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I) do (set rom!cnt!=%%R&set /a cnt+=1)
::Testing
call :toRoman 2009
echo 2009 = !result!
call :toRoman 1666
echo 1666 = !r... |
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... | #BQN | BQN | ⟨ToArabic⇐A⟩ ← {
c ← "IVXLCDM" # Characters
v ← ⥊ (10⋆↕4) ×⌜ 1‿5 # Their values
A ⇐ +´∘(⊢ׯ1⋆<⟜«) v ⊏˜ c ⊐ ⊢
} |
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
| #FreeBASIC | FreeBASIC | #Include "crt.bi"
const iterations=20000000
sub bisect( f1 as function(as double) as double,min as double,max as double,byref O as double,a() as double)
dim as double last,st=(max-min)/iterations,v
for n as double=min to max step st
v=f1(n)
if sgn(v)<>sgn(last) then
redim preserve ... |
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:
... | #Erlang | Erlang |
-module(rps).
-compile(export_all).
play() ->
loop([1,1,1]).
loop([R,P,S]=Odds) ->
case io:fread("What is your move? (R,P,S,Q) ","~c") of
{ok,["Q"]} -> io:fwrite("Good bye!~n");
{ok,[[Human]]} when Human == $R; Human == $P; Human == $S ->
io:fwrite("Your move is ~s.~n",
... |
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... | #Fan | Fan | **
** Generates a run-length encoding for a string
**
class RLE
{
Run[] encode(Str s)
{
runs := Run[,]
s.size.times |i|
{
ch := s[i]
if (runs.size==0 || runs.last.char != ch)
runs.add(Run(ch))
runs.last.inc
}
return runs
}
Str decode(Run[] runs)
{
buf := 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.
| #Octave | Octave | for j = 2 : 10
printf("*** %d\n", j);
for n = 1 : j
disp(exp(2i*pi*n/j));
endfor
disp("");
endfor |
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.
| #OoRexx | OoRexx | /*REXX program computes the K roots of unity (which include complex roots).*/
parse Version v
Say v
parse arg n frac . /*get optional arguments from the C.L. */
if n=='' then n=1 /*Not specified? Then use the default.*/
if frac='' then frac=5 /* " " ... |
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... | #Octave | Octave | roots(a,b,c)=polrootsreal(Pol([a,b,c])) |
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... | #PARI.2FGP | PARI/GP | roots(a,b,c)=polrootsreal(Pol([a,b,c])) |
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... | #E | E | pragma.enable("accumulator")
var rot13Map := [].asMap()
for a in ['a', 'A'] {
for i in 0..!26 {
rot13Map with= (a + i, E.toString(a + (i + 13) % 26))
}
}
def rot13(s :String) {
return accum "" for c in s { _ + rot13Map.fetch(c, fn{ c }) }
} |
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:
... | #REXX | REXX | The Runge─Kutta method is used to solve the following differential equation:
y'(t) = t2 √ y(t)
The exact solution: y(t) = (t2+4)2 ÷ 16
|
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:
... | #Ring | Ring |
decimals(8)
y = 1.0
for i = 0 to 100
t = i / 10
if t = floor(t)
actual = (pow((pow(t,2) + 4),2)) / 16
see "y(" + t + ") = " + y + " error = " + (actual - y) + nl ok
k1 = t * sqrt(y)
k2 = (t + 0.05) * sqrt(y + 0.05 * k1)
k3 = (t + 0.05) * sqrt(y + 0.05 * k2)
k4 = (t + 0.10) * ... |
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).
... | #Tcl | Tcl | package require Tcl 8.5
proc fromSexp {str} {
set tokenizer {[()]|"(?:[^\\""]|\\.)*"|(?:[^()""\s\\]|\\.)+|[""]}
set stack {}
set accum {}
foreach token [regexp -inline -all $tokenizer $str] {
if {$token eq "("} {
lappend stack $accum
set accum {}
} elseif {$token eq ")"} {
if {![lleng... |
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... | #Run_BASIC | Run BASIC | dim statnames$(6)
data "STR", "CON", "DEX", "INT", "WIS", "CHA"
for i = 1 to 6
read statnames$(i)
next i
dim stat(6)
acceptable = false
while 1
sum = 0 : n15 = 0
for i = 1 to 6
stat(i) = rollstat()
sum = sum + stat(i)
if stat(i) >= 15 then n15 = n15 + 1
next i
if sum >= 75 and n15... |
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... | #Rust | Rust |
use rand::distributions::Uniform;
use rand::prelude::{thread_rng, ThreadRng};
use rand::Rng;
fn main() {
for _ in 0..=10 {
attributes_engine();
}
}
#[derive(Copy, Clone, Debug)]
pub struct Dice {
amount: i32,
range: Uniform<i32>,
rng: ThreadRng,
}
impl Dice {
// Modeled after d2... |
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... | #Ursala | Ursala | #import nat
sieve = ~<{0,1}&& iota; @NttPX ~&r->lx ^/~&rhPlC remainder@rlX~|@r |
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... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"
data=REQUEST (url)
BUILD S_TABLE beg=*
DATA :title=":
BUILD S_TABLE end=*
DATA :":
titles=EXTRACT (data,beg|,end,1,0,"~~")
titles=SPLIT (titles,":~~:")
sz_titles=SI... |
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... | #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
SITE=https://www.rosettacode.org
API=$SITE/mw/api.php
PAGES=$SITE/mw/index.php
query="$API?action=query"
query+=$(printf '&%s' \
list=categorymembers \
cmtitle=Category:Programming_Tasks \
cmlimit=500)
total=0
while read title; do
t=${title// /_}
tasks=$(curl -s "$P... |
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 ... | #Objective-C | Objective-C | NSArray *haystack = @[@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo"];
for (id needle in @[@"Washington",@"Bush"]) {
int index = [haystack indexOfObject:needle];
if (index == NSNotFound)
NSLog(@"%@ is not in haystack", needle);
else
NSLog(@"%i %@", index, needl... |
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,... | #R | R |
library(rvest)
library(plyr)
library(dplyr)
options(stringsAsFactors=FALSE)
langUrl <- "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&prop=categoryinfo&gcmlimit=5000"
langs <- html(langUrl) %>%
html_nodes('page')
ff <- function(xml_... |
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... | #BBC_BASIC | BBC BASIC | PRINT ;1999, FNroman(1999)
PRINT ;2012, FNroman(2012)
PRINT ;1666, FNroman(1666)
PRINT ;3888, FNroman(3888)
END
DEF FNroman(n%)
LOCAL i%, r$, arabic%(), roman$()
DIM arabic%(12), roman$(12)
arabic%() = 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,1000
... |
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... | #Bracmat | Bracmat | ( unroman
= nbr,lastVal,val
. 0:?nbr:?lastVal
& @( low$!arg
: ?
%@?L
( ?
& (m.1000)
(d.500)
(c.100)
(l.50)
(x.10)
(v.5)
... |
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
| #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
example := func(x float64) float64 { return x*x*x - 3*x*x + 2*x }
findroots(example, -.5, 2.6, 1)
}
func findroots(f func(float64) float64, lower, upper, step float64) {
for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step {
x1 = math.Min(x1, ... |
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:
... | #Euphoria | Euphoria | function weighted_rand(sequence table)
integer sum,r
sum = 0
for i = 1 to length(table) do
sum += table[i]
end for
r = rand(sum)
for i = 1 to length(table)-1 do
r -= table[i]
if r <= 0 then
return i
end if
end for
return length(table)
end fun... |
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... | #Forth | Forth | variable a
: n>a (.) tuck a @ swap move a +! ;
: >a a @ c! 1 a +! ;
: encode ( c-addr +n a -- a n' )
dup a ! -rot over c@ 1 2swap 1 /string bounds ?do
over i c@ = if 1+
else n>a >a i c@ 1 then
loop n>a >a a @ over - ;
: digit? [char] 0 [ char 9 1+ literal ] within ;
: decode ( c-addr +n a -- a 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.
| #PARI.2FGP | PARI/GP | vector(n,k,exp(2*Pi*I*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.
| #Pascal | Pascal | Program Roots;
var
root: record // poor man's complex type.
r: real;
i: real;
end;
i, n: integer;
angle: real;
begin
for n := 2 to 7 do
begin
angle := 0.0;
write(n, ': ');
for i := 1 to n do
begin
root.r := cos(angle);
root.i := sin(angle);
write(root.r:8:5, r... |
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... | #Pascal | Pascal | Program QuadraticRoots;
var
a, b, c, q, f: double;
begin
a := 1;
b := -10e9;
c := 1;
q := sqrt(a * c) / b;
f := (1 + sqrt(1 - 4 * q * q)) / 2;
writeln ('Version 1:');
writeln ('x1: ', (-b * f / a):16, ', x2: ', (-c / (b * f)):16);
writeln ('Version 2:');
q := sqrt(b * b - 4 * a * c);
if b ... |
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... | #Elena | Elena | import system'routines;
import extensions;
import extensions'text;
singleton rotConvertor
{
char convert(char ch)
{
if (($97 <= ch && ch <= $109) || ($65 <= ch && ch <= $77))
{
^ (ch.toInt() + 13).toChar()
};
if (($110 <= ch && ch <= $122) || ($78 <= ch && ch <= $90... |
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:
... | #Ruby | Ruby | def calc_rk4(f)
return ->(t,y,dt){
->(dy1 ){
->(dy2 ){
->(dy3 ){
->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call(
dt * f.call( t + dt , y + dy3 ))}.call(
dt * f.call( t + dt/2, y + dy2/2 ))}.call(
dt * f.call( t + dt/2, y + dy1/2 ))}.c... |
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).
... | #TXR | TXR | $ txr -p '(read)'
((data "quoted data" 123 4.5)
(data (!@# (4.5) "(more" "data)")))
[Ctrl-D][Enter]
((data "quoted data" 123 4.5) (data (! (sys:var #(4.5)) "(more" "data)"))) |
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... | #Scala | Scala |
import scala.util.Random
Random.setSeed(1)
def rollDice():Int = {
val v4 = Stream.continually(Random.nextInt(6)+1).take(4)
v4.sum - v4.min
}
def getAttributes():Seq[Int] = Stream.continually(rollDice()).take(6)
def getCharacter():Seq[Int] = {
val attrs = getAttributes()
println("generated => " + attrs.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... | #Vala | Vala | using Gee;
ArrayList<int> primes(int limit){
var sieve = new ArrayList<bool>();
var prime_list = new ArrayList<int>();
for(int i = 0; i <= limit; i++){
sieve.add(true);
}
sieve[0] = false;
sieve[1] = false;
for (int i = 2; i <= limit/2; i++){
if (sieve[i] != false){
for (int j = 2; i*j <= limit; j... |
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... | #Wren | Wren | /* rc_count_examples.wren */
import "./pattern" for Pattern
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
foreign class Buffer {
construct new() {} // C will allocate buffer of a suitable size
foreign value // returns buffe... |
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 ... | #OCaml | OCaml | # let find_index pred lst =
let rec loop n = function
[] -> raise Not_found
| x::xs -> if pred x then n
else loop (n+1) xs
in
loop 0 lst;;
val find_index : ('a -> bool) -> 'a list -> int = <fun>
# let haystack =
["Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Ch... |
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,... | #Racket | Racket | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (mak... |
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... | #BCPL | BCPL | get "libhdr"
let toroman(n, v) = valof
$( let extract(n, val, rmn, v) = valof
$( while n >= val
$( n := n - val;
for i=1 to rmn%0 do v%(v%0+i) := rmn%i
v%0 := v%0 + rmn%0
$)
resultis n
$)
v%0 := 0
n := extract(n, 1000, "M", v)
n := extract(n, ... |
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... | #C | C | #include <stdio.h>
int digits[26] = { 0, 0, 100, 500, 0, 0, 0, 0, 1, 1, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 10, 0, 0 };
/* assuming ASCII, do upper case and get index in alphabet. could also be
inline int VALUE(char x) { return digits [ (~0x20 & x) - 'A' ]; }
if you think macros are evil */
#defin... |
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
| #Haskell | Haskell | f x = x^3-3*x^2+2*x
findRoots start stop step eps =
[x | x <- [start, start+step .. stop], abs (f x) < eps] |
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:
... | #F.23 | F# | open System
let random = Random ()
let rand = random.NextDouble () //Gets a random number in the range (0.0, 1.0)
/// Union of possible choices for a round of rock-paper-scissors
type Choice =
| Rock
| Paper
| Scissors
/// Gets the string representation of a Choice
let getString = function
| Rock -> "Rock"
... |
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... | #Fortran | Fortran | program RLE
implicit none
integer, parameter :: bufsize = 100 ! Sets maximum size of coded and decoded strings, adjust as necessary
character(bufsize) :: teststr = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
character(bufsize) :: codedstr = "", decodedstr = ""
call Encode(tests... |
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.
| #Perl | Perl | use Math::Complex;
foreach my $n (2 .. 10) {
printf "%2d", $n;
my @roots = root(1,$n);
foreach my $root (@roots) {
$root->display_format(style => 'cartesian', format => '%.3f');
print " $root";
}
print "\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.
| #Phix | Phix | with javascript_semantics
for n=2 to 10 do
printf(1,"%2d:",n)
for root=0 to n-1 do
atom real = cos(2*PI*root/n)
atom imag = sin(2*PI*root/n)
printf(1,"%s %6.3f %6.3fi",{iff(root?",":""),real,imag})
end for
printf(1,"\n")
end for
|
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... | #Perl | Perl | use Math::Complex;
($x1,$x2) = solveQuad(1,2,3);
print "x1 = $x1, x2 = $x2\n";
sub solveQuad
{
my ($a,$b,$c) = @_;
my $root = sqrt($b**2 - 4*$a*$c);
return ( -$b + $root )/(2*$a), ( -$b - $root )/(2*$a);
} |
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... | #Phix | Phix | procedure solve_quadratic(sequence t3)
atom {a,b,c} = t3,
d = b*b-4*a*c, f
string s = sprintf("for a=%g,b=%g,c=%g",t3), t
sequence u
if abs(d)<1e-6 then d=0 end if
switch sign(d) do
case 0: t = "single root is %g"
u = {-b/2/a}
case 1: t = "real roots are %g a... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Elixir | Elixir | defmodule RC do
def rot13(clist) do
f = fn(c) when (?A <= c and c <= ?M) or (?a <= c and c <= ?m) -> c + 13
(c) when (?N <= c and c <= ?Z) or (?n <= c and c <= ?z) -> c - 13
(c) -> c
end
Enum.map(clist, f)
end
end
IO.inspect encode = RC.rot13('Rosetta Code')
IO.inspect RC.rot13... |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Run_BASIC | Run BASIC | y = 1
while t <= 10
k1 = t * sqr(y)
k2 = (t + .05) * sqr(y + .05 * k1)
k3 = (t + .05) * sqr(y + .05 * k2)
k4 = (t + .1) * sqr(y + .1 * k3)
if right$(using("##.#",t),1) = "0" then print "y(";using("##",t);") ="; using("####.#######", y);chr$(9);"Error ="; (((t^2 + 4)^2) /16) -y
y = y + .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:
... | #Rust | Rust | fn runge_kutta4(fx: &dyn Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 {
let k1 = dx * fx(x, y);
let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0);
let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0);
let k4 = dx * fx(x + dx, y + k3);
y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
}
fn f(x: f64, y: f64) -... |
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).
... | #Wren | Wren | import "/pattern" for Pattern
import "/fmt" for Fmt
var INDENT = 2
var parseSExpr = Fn.new { |str|
var ipat = " \t\n\f\v\r()\""
var p = Pattern.new("""+0/s["+0^""|(|)|"|+1/I]""", Pattern.within, ipat)
var t = p.findAll(str).map { |m| m.text }.toList
if (t.count == 0) return null
var o = false
... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: count is 0;
var integer: total is 0;
var integer: attribIdx is 0;
var integer: diceroll is 0;
var integer: sumOfRolls is 0;
var array integer: attribute is 6 times 0;
var array integer: dice is 4 times 0;
begin
... |
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... | #True_BASIC | True BASIC | FUNCTION min(a, b)
IF a < b THEN LET min = a ELSE LET min = b
END FUNCTION
FUNCTION d6
LET d6 = 1 + INT(RND * 6)
END FUNCTION
FUNCTION rollstat
LET a = d6
LET b = d6
LET c = d6
LET d = d6
LET rollstat = a + b + c + d - min(min(a, b), min(c, d))
END FUNCTION
DIM statnames$(6)
DATA "STR"... |
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... | #VAX_Assembly | VAX Assembly | 000F4240 0000 1 n=1000*1000
0000 0000 2 .entry main,0
7E 7CFD 0002 3 clro -(sp) ;result buffer
5E DD 0005 4 pushl sp ;pointer to buffer
10 DD 0007 ... |
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... | #zkl | zkl | var [const] YAJL=Import("zklYAJL")[0], CURL=Import("zklCurl");
fcn getTasks(language){
continueValue,tasks:="",Data(0,String); // "nm\0nm\0...."
do{
page:=CURL().get(("http://rosettacode.org/mw/api.php?"
"action=query&cmlimit=500"
"&format=json"
"&list=categorymembers"
"&cmtitle=Category:%... |
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 ... | #Oforth | Oforth | : needleIndex(needle, haystack)
haystack indexOf(needle) dup ifNull: [ drop ExRuntime throw("Not found", needle) ] ;
[ "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz" ] const: Haystack
needleIndex("Bush", Haystack) println
Haystack lastIndexOf("Bush") println
needleIndex("Washington",... |
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,... | #Raku | Raku | use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Sort::Naturally;
my $client = HTTP::UserAgent.new;
my $url = 'http://rosettacode.org/mw';
my $tablefile = './RC_Popularity.txt';
my %cat = (
'Programming_Tasks' => 'Task',
'Draft_Programming_Tasks' => 'Draft'
);
my %tasks;
for %cat.keys.sort ->... |
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... | #Befunge | Befunge | &>0\0>00p:#v_$ >:#,_ $ @
4-v >5+#:/#<\55+%:5/\5%:
vv_$9+00g+5g\00g8+>5g\00
g>\20p>:10p00g \#v _20gv
> 2+ v^-1g01\g5+8<^ +9 _
IVXLCDM |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace Roman
{
internal class Program
{
private static void Main(string[] args)
{
// Decode and print the numerals.
Console.WriteLine("{0}: {1}", "MCMXC", Decode("MCMXC"));
Console.WriteLine("{0}: {1}", "MMV... |
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
| #HicEst | HicEst | OPEN(FIle='test.txt')
1 DLG(NameEdit=x0, DNum=3)
x = x0
chi2 = SOLVE(NUL=x^3 - 3*x^2 + 2*x, Unknown=x, I=iterations, NumDiff=1E-15)
EDIT(Text='approximate exact ', Word=(chi2 == 0), Parse=solution)
WRITE(FIle='test.txt', LENgth=6, Name) x0, x, solution, chi2, iterations
GOTO 1 |
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:
... | #Factor | Factor | USING: combinators formatting io kernel math math.ranges qw
random sequences ;
IN: rosetta-code.rock-paper-scissors
CONSTANT: thing qw{ rock paper scissors }
CONSTANT: msg { "I win." "Tie!" "You win." }
: ai-choice ( r p s -- n )
3dup + + nip [1,b] random {
{ [ 3dup nip >= ] [ 3drop 1 ] }
{ [ 3d... |
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... | #FreeBASIC | FreeBASIC |
Dim As String initial, encoded, decoded
Function RLDecode(i As String) As String
Dim As Long Loop0
dim as string rCount, outP, m
For Loop0 = 1 To Len(i)
m = Mid(i, Loop0, 1)
Select Case m
Case "0" To "9"
rCount += m
Case Else
If Len(rCount) Then
... |
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.
| #PicoLisp | PicoLisp | (load "@lib/math.l")
(for N (range 2 10)
(let Angle 0.0
(prin N ": ")
(for I N
(let Ipart (sin Angle)
(prin
(round (cos Angle) 4)
(if (lt0 Ipart) "-" "+")
"j"
(round (abs Ipart) 4)
" " ) )
(inc 'An... |
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.
| #PL.2FI | PL/I | complex_roots:
procedure (N);
declare N fixed binary nonassignable;
declare x float, c fixed decimal (10,8) complex;
declare twopi float initial ((4*asin(1.0)));
do x = 0 to twopi by twopi/N;
c = complex(cos(x), sin(x));
put skip list (c);
end;
end complex_roots;
1.00000000+0.000000... |
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.
| #Prolog | Prolog |
roots(N, Rs) :-
succ(Pn, N), numlist(0, Pn, Ks),
maplist(root(N), Ks, Rs).
root(N, M, R2) :-
R0 is (2*M) rdiv N, % multiple of PI
(R0 > 1 -> R1 is R0 - 2; R1 = R0), % adjust for principal values
cis(R1, R2).
cis(0, 1) :- !.
cis(1, -1) :- !.
cis(1 rdiv 2, i) :- !.
cis(-1 rdiv 2, -i) :- !.
cis... |
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... | #PicoLisp | PicoLisp | (scl 40)
(de solveQuad (A B C)
(let SD (sqrt (- (* B B) (* 4 A C)))
(if (lt0 B)
(list
(*/ (- SD B) A 2.0)
(*/ C 2.0 (*/ A A (- SD B) `(* 1.0 1.0))) )
(list
(*/ C 2.0 (*/ A A (- 0 B SD) `(* 1.0 1.0)))
(*/ (- 0 B SD) A 2.0) ) ) ) )
(mapcar rou... |
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... | #PL.2FI | PL/I |
declare (c1, c2) float complex,
(a, b, c, x1, x2) float;
get list (a, b, c);
if b**2 < 4*a*c then
do;
c1 = (-b + sqrt(b**2 - 4+0i*a*c)) / (2*a);
c2 = (-b - sqrt(b**2 - 4+0i*a*c)) / (2*a);
put data (c1, c2);
end;
else
do;
x1 = (-b + sqrt(b*... |
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... | #Emacs_Lisp | Emacs Lisp | (rot13-string "abc") ;=> "nop"
(with-temp-buffer
(insert "abc")
(rot13-region (point-min) (point-max))
(buffer-string)) ;=> "nop" |
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:
... | #Scala | Scala | object Main extends App {
val f = (t: Double, y: Double) => t * Math.sqrt(y) // Runge-Kutta solution
val g = (t: Double) => Math.pow(t * t + 4, 2) / 16 // Exact solution
new Calculator(f, Some(g)).compute(100, 0, .1, 1)
}
class Calculator(f: (Double, Double) => Double, g: Option[Double => Double] = None) {
... |
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... | #UNIX_Shell | UNIX Shell | function main {
typeset attrs=(str dex con int wis cha)
typeset -A values
typeset attr
typeset -i value total fifteens
while true; do
fifteens=0
total=0
for attr in "${attrs[@]}"; do
# "random" values repeat in zsh if run in a subshell
r4d6drop >/tmp/$$
read value </tmp/$$
... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Dim r As New Random
Function getThree(n As Integer) As List(Of Integer)
getThree = New List(Of Integer)
For i As Integer = 1 To 4 : getThree.Add(r.Next(n) + 1) : Next
getThree.Sort() : getThree.RemoveAt(0)
End Function
Function getSix() As List(Of Integer)
... |
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... | #VBA | VBA | Sub primes()
'BRRJPA
'Prime calculation for VBA_Excel
'p is the superior limit of the range calculation
'This example calculates from 2 to 100000 and print it
'at the collum A
p = 100000
Dim nprimes(1 To 100000) As Integer
b = Sqr(p)
For n = 2 To b
For k = n * n To p Step n
nprimes(k) = 1
Ne... |
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 ... | #ooRexx | ooRexx | -- ordered collections always return the first hit
a = .array~of(1,2,3,4,4,5)
say a~index(4)
a2 = .array~new(5,5) -- multidimensional
a2[3,3] = 4
-- the returned index is an array of values
say a2~index(4)~makestring('line', ',')
-- Note, list indexes are assigned when an item is added and
-- are not tied to relative ... |
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,... | #Red | Red | Red []
data: read http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
lb: make block! 500
;;data: read %data.html ;; for testing save html and use flat file
arr: split data newline
k: "Category:"
;; exclude list:
exrule: [thru ["programming"
| "users"
| "Im... |
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... | #BQN | BQN | ⟨ToRoman⇐R⟩ ← {
ds ← 1↓¨(¯1+`⊏⊸=)⊸⊔" I IV V IX X XL L XC C CD D CM M"
vs ← 1e3∾˜ ⥊1‿4‿5‿9×⌜˜10⋆↕3
R ⇐ {
𝕨𝕊0: "";
(⊑⟜ds∾·𝕊𝕩-⊑⟜vs) 1-˜⊑vs⍋𝕩
}
} |
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... | #C.2B.2B | C++ |
#include <exception>
#include <string>
#include <iostream>
using namespace std;
namespace Roman
{
int ToInt(char c)
{
switch (c)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
... |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
showRoots(f, -1.0, 4, 0.002)
end
procedure f(x)
return x^3 - 3*x^2 + 2*x
end
procedure showRoots(f, lb, ub, step)
ox := x := lb
oy := f(x)
os := sign(oy)
while x <= ub do {
if (s := sign(y := f(x))) = 0 then write(x)
else if s ~= os then {
dx := x... |
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:
... | #Forth | Forth |
include random.fs
0 value aiwins
0 value plwins
10 constant inlim
0 constant rock
1 constant paper
2 constant scissors
create rpshistory 0 , 0 , 0 ,
create inversemove 1 , 2 , 0 ,
3 constant historylen
: @a ( n array -- )
swap cells + @ ;
: sum-history ( -- n )
0 historylen 0 ?do
i rpshistory @a... |
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... | #Gambas | Gambas | Public Sub Main()
Dim sString As String = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
Dim siCount As Short = 1
Dim siStart As Short = 1
Dim sHold As New String[]
Dim sTemp As String
sString &= " "
Repeat
sTemp = Mid(sString, siCount, 1)
Do
Inc siCount
If Mid(sString, siCount, ... |
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.
| #PureBasic | PureBasic | OpenConsole()
For n = 2 To 10
angle = 0
PrintN(Str(n))
For i = 1 To n
x.f = Cos(Radian(angle))
y.f = Sin(Radian(angle))
PrintN( Str(i) + ": " + StrF(x, 6) + " / " + StrF(y, 6))
angle = angle + (360 / n)
Next
Next
Input() |
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.
| #Python | Python | import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.... |
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... | #Python | Python | #!/usr/bin/env python3
import math
import cmath
import numpy
def quad_discriminating_roots(a,b,c, entier = 1e-5):
"""For reference, the naive algorithm which shows complete loss of
precision on the quadratic in question. (This function also returns a
characterization of the roots.)"""
discriminant ... |
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... | #Erlang | Erlang | rot13(Str) ->
F = fun(C) when (C >= $A andalso C =< $M); (C >= $a andalso C =< $m) -> C + 13;
(C) when (C >= $N andalso C =< $Z); (C >= $n andalso C =< $z) -> C - 13;
(C) -> C
end,
lists:map(F, Str). |
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:
... | #Sidef | Sidef | func runge_kutta(yp) {
func (t, y, δt) {
var a = (δt * yp(t, y));
var b = (δt * yp(t + δt/2, y + a/2));
var c = (δt * yp(t + δt/2, y + b/2));
var d = (δt * yp(t + δt, y + c));
(a + 2*(b + c) + d) / 6;
}
}
define δt = 0.1;
var δy = runge_kutta(func(t, y) { t * y.sqrt });... |
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... | #Wren | Wren | import "random" for Random
import "/sort" for Sort
var rand = Random.new()
var vals = List.filled(6, 0)
while (true) {
for (i in 0..5) {
var rns = List.filled(4, 0)
for (j in 0..3) rns[j] = rand.int(1, 7)
var sum = rns.reduce { |acc, n| acc + n }
Sort.insertion(rns)
vals[i]... |
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... | #VBScript | VBScript |
Dim sieve()
If WScript.Arguments.Count>=1 Then
n = WScript.Arguments(0)
Else
n = 99
End If
ReDim sieve(n)
For i = 1 To n
sieve(i) = True
Next
For i = 2 To n
If sieve(i) Then
For j = i * 2 To n Step i
sieve(j) = False
Next
... |
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 ... | #Oz | Oz | declare
%% Lazy list of indices of Y in Xs.
fun {Indices Y Xs}
for
X in Xs
I in 1;I+1
yield:Yield
do
if Y == X then {Yield I} end
end
end
fun {Index Y Xs}
case {Indices Y Xs} of X|_ then X
else raise index(elementNotFound Y) end
end
end
Hayst... |
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,... | #REXX | REXX | /*REXX program reads two files and displays a ranked list of Rosetta Code languages.*/
parse arg catFID lanFID outFID . /*obtain optional arguments from the CL*/
call init /*initialize some REXX variables. */
call get ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.