task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Bracmat | Bracmat | ( ( encode
= indian roman cifr tenfoldroman letter tenfold
. !arg:#?indian
& :?roman
& whl
' ( @(!indian:#%?cifr ?indian)
& :?tenfoldroman
& whl
' ( !roman:%?letter ?roman
& !tenfoldroman
( (I.X)
... |
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... | #Ceylon | Ceylon | shared void run() {
value numerals = map {
'I' -> 1,
'V' -> 5,
'X' -> 10,
'L' -> 50,
'C' -> 100,
'D' -> 500,
'M' -> 1000
};
function toHindu(String roman) {
variable value total = 0;
for(i->c in roman.indexed) {
assert(exists currentValue = numerals[c]);
/* Look at the next letter to see... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #J | J | 1{::p. 0 2 _3 1
2 1 0 |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Java | Java | public class Roots {
public interface Function {
public double f(double x);
}
private static int sign(double x) {
return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}
public static void printRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, ox = x;
d... |
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:
... | #Fortran | Fortran |
! compilation
! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
! EXAMPLE
!
!$ ./f
!rock, paper, scissors? papier
!scoring computer choice (r) and your choice (p)
!rock, paper, scissors? sizzerz
!scoring computer choice (s) and your choice (s)
!rock, paper, scissors? quit
!scori... |
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... | #Go | Go | package main
import "fmt"
// encoding scheme:
// encode to byte array
// byte value < 26 means single character: byte value + 'A'
// byte value 26..255 means (byte value - 24) copies of next byte
func rllEncode(s string) (r []byte) {
if s == "" {
return
}
c := s[0]
if c < 'A' || c > 'Z' {
... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #R | R | for(j in 2:10) {
r <- sprintf("%d: ", j)
for(n in 1:j) {
r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", ""))
}
print(r)
} |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Racket | Racket | #lang racket
(define (roots-of-unity n)
(for/list ([k n])
(make-polar 1 (* k (/ (* 2 pi) n))))) |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Raku | Raku | constant n = 10;
for ^n -> \k {
say cis(k*τ/n);
} |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #R | R | qroots <- function(a, b, c) {
r <- sqrt(b * b - 4 * a * c + 0i)
if (abs(b - r) > abs(b + r)) {
z <- (-b + r) / (2 * a)
} else {
z <- (-b - r) / (2 * a)
}
c(z, c / (z * a))
}
qroots(1, 0, 2i)
[1] -1+1i 1-1i
qroots(1, -1e9, 1)
[1] 1e+09+0i 1e-09+0i |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Racket | Racket | #lang racket
(define (quadratic a b c)
(let* ((-b (- b))
(delta (- (expt b 2) (* 4 a c)))
(denominator (* 2 a)))
(list
(/ (+ -b (sqrt delta)) denominator)
(/ (- -b (sqrt delta)) denominator))))
;(quadratic 1 0.0000000000001 -1)
;'(0.99999999999995 -1.00000000000005)
;(quadratic 1 0.0... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #ERRE | ERRE | PROGRAM ROT13
BEGIN
INPUT("Enter a string ",TEXT$)
FOR C%=1 TO LEN(TEXT$) DO
A%=ASC(MID$(TEXT$,C%,1))
CASE A% OF
65..90->
MID$(TEXT$,C%,1)=CHR$(65+(A%-65+13) MOD 26)
END ->
97..122->
MID$(TEXT$,C%,1)=CHR$(97+(A%-97+13) MOD 26)
... |
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:
... | #Standard_ML | Standard ML | fun step y' (tn,yn) dt =
let
val dy1 = dt * y'(tn,yn)
val dy2 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy1)
val dy3 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy2)
val dy4 = dt * y'(tn + dt, yn + dy3)
in
(tn + dt, yn + (1.0 / 6.0) * (dy1 + 2.0*dy2 + 2.0*dy3 + dy4))
end
(* Sugge... |
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:
... | #Stata | Stata | function rk4(f, t0, y0, t1, n) {
h = (t1-t0)/(n-1)
a = J(n, 2, 0)
a[1, 1] = t = t0
a[1, 2] = y = y0
for (i=2; i<=n; i++) {
k1 = h*(*f)(t, y)
k2 = h*(*f)(t+0.5*h, y+0.5*k1)
k3 = h*(*f)(t+0.5*h, y+0.5*k2)
k4 = h*(*f)(t+h, y+k3)
t = t+h
y = y+(k1+2*k2+2*k3+k4)/6
a[i, 1] = t
a[i, 2] = y
}
return(a)
}... |
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... | #XPL0 | XPL0 | func Gen; \Return sum of the three largest of four random values
int I, R, Min, SI, Sum, Die(4);
[Min:= 7; Sum:= 0;
for I:= 0 to 4-1 do
[R:= Ran(6)+1; \R = 1..6
if R < Min then
[Min:= R; SI:= I];
Sum:= Sum+R;
Die(I):= R;
];
return Sum - Die(SI);
];
int Total, Count, J, Value(6);
[repea... |
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... | #Yabasic | Yabasic | sub d6()
//simulates a marked regular hexahedron coming to rest on a plane
return 1 + int(ran(6))
end sub
sub roll_stat()
//rolls four dice, returns the sum of the three highest
a = d6() : b = d6(): c = d6(): d = d6()
return a + b + c + d - min(min(a, b), min(c, d))
end sub
dim statnames$(6)
st... |
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... | #Vedit_macro_language | Vedit macro language | #10 = Get_Num("Enter number to search to: ", STATLINE)
Buf_Switch(Buf_Free) // Use edit buffer as flags array
Ins_Text("--") // 0 and 1 are not primes
Ins_Char('P', COUNT, #10-1) // init rest of the flags to "prime"
for (#1 = 2; #1*#1 < #10; #1++) {
Goto_Pos(#... |
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 ... | #PARI.2FGP | PARI/GP | find(v,n)={
my(i=setsearch(v,n));
if(i,
while(i>1, if(v[i-1]==n,i--))
,
error("Could not find")
);
i
}; |
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity | Rosetta Code/Rank languages by popularity | Rosetta Code/Rank languages by popularity
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Sort the most popular computer programming languages based in number of members in Rosetta Code categories.
Sample output on 01 juin 2022 at 14:13 +02
Rank: 1 (1,... | #Ring | Ring |
# Project: Rosetta Code/Rank languages by popularity
load "stdlib.ring"
ros= download("http://rosettacode.org/wiki/Category:Programming_Languages")
pos = 1
totalros = 0
rosname = ""
rosnameold = ""
rostitle = ""
roslist = []
for n = 1 to len(ros)
nr = searchstring(ros,'<li><a href="/wiki/',pos)
if ... |
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... | #C | C | #include <stdio.h>
int main() {
int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
// There is a bug: "XL\0" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long...
// Should be "XL" without \0 etc.
//
char roman[13][3] = {"M\0", "CM\0", "D\0", "CD\0", "C\0", "X... |
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... | #Clojure | Clojure |
;; Incorporated some improvements from the alternative implementation below
(defn ro2ar [r]
(->> (reverse (.toUpperCase r))
(map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
(partition-by identity)
(map (partial apply +))
(reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))
;; alternative
... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #JavaScript | JavaScript |
// This function notation is sorta new, but useful here
// Part of the EcmaScript 6 Draft
// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
var poly = (x => x*x*x - 3*x*x + 2*x);
function sign(x) {
return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0;
}
function printRoots(f, lowerBo... |
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:
... | #FreeBASIC | FreeBASIC | Dim Shared As Byte ganador = 1, accion = 2, perdedor = 3, wp, wc
Dim Shared As String word(10, 3)
For n As Byte = 0 To 9
Read word(n, ganador), word(n, accion), word(n, perdedor)
Next n
Sub SimonSay(n As Byte)
Print Using "\ \ \ \ "; word(n, ganador); word(n, accion); word(n, perdedor)
End Sub
... |
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... | #Groovy | Groovy | def rleEncode(text) {
def encoded = new StringBuilder()
(text =~ /(([A-Z])\2*)/).each { matcher ->
encoded.append(matcher[1].size()).append(matcher[2])
}
encoded.toString()
}
def rleDecode(text) {
def decoded = new StringBuilder()
(text =~ /([0-9]+)([A-Z])/).each { matcher ->
d... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #REXX | REXX | /*REXX program computes the K roots of unity (which usually includes complex roots).*/
numeric digits length( pi() ) - length(.) /*use number of decimal digits in pi. */
parse arg n frac . /*get optional arguments from the C.L. */
if n=='' | n=="," then n= 1 ... |
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... | #Raku | Raku | for
[1, 2, 1],
[1, 2, 3],
[1, -2, 1],
[1, 0, -4],
[1, -10**6, 1]
-> @coefficients {
printf "Roots for %d, %d, %d\t=> (%s, %s)\n",
|@coefficients, |quadroots(@coefficients);
}
sub quadroots (*[$a, $b, $c]) {
( -$b + $_ ) / (2 * $a),
( -$b - $_ ) / (2 * $a)
given
($b ** 2 - 4 * $a * $c ).Comple... |
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... | #Euphoria | Euphoria |
include std/types.e
include std/text.e
atom FALSE = 0
atom TRUE = not FALSE
function Rot13( object oStuff )
integer iOffset
integer bIsUpper
object oResult
sequence sAlphabet = "abcdefghijklmnopqrstuvwxyz"
if sequence(oStuff) then
oResult = repeat( 0, length( oStuff ) )
for i = 1 to length( oStuff ) do
... |
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:
... | #Swift | Swift | import Foundation
func rk4(dx: Double, x: Double, y: Double, f: (Double, Double) -> Double) -> Double {
let k1 = dx * f(x, y)
let k2 = dx * f(x + dx / 2, y + k1 / 2)
let k3 = dx * f(x + dx / 2, y + k2 / 2)
let k4 = dx * f(x + dx, y + k3)
return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6
}
var y = [Do... |
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:
... | #Tcl | Tcl | package require Tcl 8.5
# Hack to bring argument function into expression
proc tcl::mathfunc::dy {t y} {upvar 1 dyFn dyFn; $dyFn $t $y}
proc rk4step {dyFn y* t* dt} {
upvar 1 ${y*} y ${t*} t
set dy1 [expr {$dt * dy($t, $y)}]
set dy2 [expr {$dt * dy($t+$dt/2, $y+$dy1/2)}]
set dy3 [expr {$dt * d... |
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... | #zkl | zkl | reg attrs=List(), S,N;
do{
attrs.clear();
do(6){
abcd:=(4).pump(List,(0).random.fp(1,7)); // list of 4 [1..6] randoms
attrs.append(abcd.sum(0) - (0).min(abcd)); // sum and substract min
}
}while((S=attrs.sum(0))<75 or (N=attrs.filter('>=(15)).len())<2);
println("Random numbers: %s\nSums to %d, wi... |
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... | #Visual_Basic | Visual Basic | Sub Eratost()
Dim sieve() As Boolean
Dim n As Integer, i As Integer, j As Integer
n = InputBox("limit:", n)
ReDim sieve(n)
For i = 1 To n
sieve(i) = True
Next i
For i = 2 To n
If sieve(i) Then
For j = i * 2 To n Step i
sieve(j) = False
... |
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 ... | #Pascal | Pascal | use List::Util qw(first);
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
foreach my $needle (qw(Washington Bush)) {
my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
... |
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,... | #Ruby | Ruby | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
# API has trouble with long titles= values.
# To prevent skipping languages, use short slices of 20 titles.
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" =>... |
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... | #C.23 | C# | using System;
class Program
{
static uint[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static string[] rum = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
static string ToRoman(uint number)
{
string value = "";
for (int i = 0; i < nums... |
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... | #CLU | CLU | roman = cluster is decode
rep = null
digit_value = proc (c: char) returns (int) signals (invalid)
if c < 'a' then c := char$i2c(char$c2i(c) + 32) end
if c = 'm' then return(1000)
elseif c = 'd' then return(500)
elseif c = 'c' then return(100)
elseif c = 'l' then re... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #jq | jq | def sign:
if . < 0 then -1 elif . > 0 then 1 else 0 end;
def printRoots(f; lowerBound; upperBound; step):
lowerBound as $x
| ($x|f) as $y
| ($y|sign) as $s
| reduce range($x; upperBound+step; step) as $x
# state: [ox, oy, os, roots]
( [$x, $y, $s, [] ];
.[0] as $ox | .[1] as $oy | .[2] as $os
| ... |
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:
... | #GlovePIE | GlovePIE | if var.end=0 then
var.end=0
var.computerchoice=random(3) // 1 is rock, 2 is paper, and 3 is scissors.
debug="Press the R key for rock, the P key for paper, or the S key for scissors:"
endif
if pressed(Key.R)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="You chose rock, which the computer a... |
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:
... | #Go | Go | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p,... |
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... | #Haskell | Haskell | import Data.List (group)
-- Datatypes
type Encoded = [(Int, Char)] -- An encoded String with form [(times, char), ...]
type Decoded = String
-- Takes a decoded string and returns an encoded list of tuples
rlencode :: Decoded -> Encoded
rlencode = fmap ((,) <$> length <*> head) . group
-- Takes an encoded list o... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Ring | Ring |
decimals(4)
for n = 2 to 5
see string(n) + " : "
for root = 0 to n-1
real = cos(2*3.14 * root / n)
imag = sin(2*3.14 * root / n)
see "" + real + " " + imag + "i"
if root != n-1 see ", " ok
next
see nl
next
|
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #RLaB | RLaB | // specify polynomial
>> n = 10;
>> a = zeros(1,n+1); a[1] = 1; a[n+1] = -1;
>> polyroots(a)
radius roots success
>> polyroots(a).roots
-0.309016994 + 0.951056516i
-0.809016994 + 0.587785252i
-1 + 5.95570041e-23i
-0.809016994 - 0.587785252i
-0.309016994 - 0.951056516i
... |
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... | #REXX | REXX | /*REXX program finds the roots (which may be complex) of a quadratic function. */
parse arg a b c . /*obtain the specified arguments: A B C*/
call quad a,b,c /*solve quadratic function via the sub.*/
r1= r1/1; r2= r2/1; a= a/1; b= b/1; c= c/1... |
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... | #F.23 | F# | let rot13 (s : string) =
let rot c =
match c with
| c when c > 64 && c < 91 -> ((c - 65 + 13) % 26) + 65
| c when c > 96 && c < 123 -> ((c - 97 + 13) % 26) + 97
| _ -> c
s |> Array.of_seq
|> Array.map(int >> rot >> char)
|> (fun seq -> new string(seq)) |
http://rosettacode.org/wiki/Runge-Kutta_method | Runge-Kutta method | Given the example Differential equation:
y
′
(
t
)
=
t
×
y
(
t
)
{\displaystyle y'(t)=t\times {\sqrt {y(t)}}}
With initial condition:
t
0
=
0
{\displaystyle t_{0}=0}
and
y
0
=
y
(
t
0
)
=
y
(
0
)
=
1
{\displaystyle y_{0}=y(t_{0})=y(0)=1}
This equation has an exact solution:
... | #Wren | Wren | import "/fmt" for Fmt
var rungeKutta4 = Fn.new { |t0, tz, dt, y, yd|
var tn = t0
var yn = y.call(tn)
var z = ((tz - t0)/dt).truncate
for (i in 0..z) {
if (i % 10 == 0) {
var exact = y.call(tn)
var error = yn - exact
Fmt.print("$4.1f $10f $10f $9f", tn, yn... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Dim n As Integer, k As Integer, limit As Integer
Console.WriteLine("Enter number to search to: ")
limit = Console.ReadLine
Dim flags(limit) As Integer
For n = 2 To Math.Sqrt(limit)
If flags(n) = 0 Then
For k = n * n To limit Step n
flags(k) = 1
Next k
End If
Next n
' Display the pr... |
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 ... | #Perl | Perl | use List::Util qw(first);
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
foreach my $needle (qw(Washington Bush)) {
my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
... |
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,... | #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:" ' make memory DB
#mem execute("CREATE TABLE stats(lang,cnt)")
a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages")
aa$ = httpGet$("http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000")
i = instr(a$,"/wiki/Category:")
while i > 0 and lang$ <>... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <string>
std::string to_roman(int value)
{
struct romandata_t { int value; char const* numeral; };
static romandata_t const romandata[] =
{ 1000, "M",
900, "CM",
500, "D",
400, "CD",
100, "C",
90, "XC",
50, "L",
40, "XL",... |
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... | #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. UNROMAN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 filler.
03 i pic 9(02) comp.
03 j pic 9(02) comp.
03 k pic 9(02) comp.
03 l pic 9(02) comp.
01 inp-rom... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Julia | Julia | using Roots
println(find_zero(x -> x^3 - 3x^2 + 2x, (-100, 100))) |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Haskell | Haskell | import System.Random (randomRIO)
data Choice
= Rock
| Paper
| Scissors
deriving (Show, Eq)
beats :: Choice -> Choice -> Bool
beats Paper Rock = True
beats Scissors Paper = True
beats Rock Scissors = True
beats _ _ = False
genrps :: (Int, Int, Int) -> IO Choice
genrps (r, p, s) = rps <$> rand
where
r... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
write(" s=",image(s))
write("s1=",image(s1 := rle_encode(s)))
write("s2=",image(s2 := rle_decode(s1)))
if s ~== s2 then write("Encode/Decode problem.")
else write("Encode/Decode worked.... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Ruby | Ruby | def roots_of_unity(n)
(0...n).map {|k| Complex.polar(1, 2 * Math::PI * k / n)}
end
p roots_of_unity(3) |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Run_BASIC | Run BASIC | PI = 3.1415926535
FOR n = 2 TO 5
PRINT n;":" ;
FOR root = 0 TO n-1
real = COS(2*PI * root / n)
imag = SIN(2*PI * root / n)
PRINT using("-##.#####",real);using("-##.#####",imag);"i";
IF root <> n-1 then PRINT "," ;
NEXT
PRINT
NEXT
|
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Ring | Ring |
x1 = 0
x2 = 0
quadratic(3, 4, 4/3.0) # [-2/3]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(3, 2, -1) # [1/3, -1]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(-2, 7, 15) # [-3/2, 5]
see "x1 = " + x1 + " x2 = " + x2 + nl
quadratic(1, -2, 1) # [1]
see "x1 = " + x1 + " x2 = " + x2 + nl
func quadrat... |
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... | #Ruby | Ruby | require 'cmath'
def quadratic(a, b, c)
sqrt_discriminant = CMath.sqrt(b**2 - 4*a*c)
[(-b + sqrt_discriminant) / (2.0*a), (-b - sqrt_discriminant) / (2.0*a)]
end
p quadratic(3, 4, 4/3.0) # [-2/3]
p quadratic(3, 2, -1) # [1/3, -1]
p quadratic(3, 2, 1) # [(-1/3 + sqrt(2/9)i), (-1/3 - sqrt(2/9)i)]
p quadr... |
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... | #Factor | Factor | #! /usr/bin/env factor
USING: kernel io ascii math combinators sequences ;
IN: rot13
: rot-base ( ch ch -- ch ) [ - 13 + 26 mod ] keep + ;
: rot13-ch ( ch -- ch )
{
{ [ dup letter? ] [ CHAR: a rot-base ] }
{ [ dup LETTER? ] [ CHAR: A rot-base ] }
[ ]
}
cond ;
: rot13 ( str --... |
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:
... | #zkl | zkl | fcn yp(t,y) { t * y.sqrt() }
fcn exact(t){ u:=0.25*t*t + 1.0; u*u }
fcn rk4_step([(y,t)],h){
k1:=h * yp(t,y);
k2:=h * yp(t + 0.5*h, y + 0.5*k1);
k3:=h * yp(t + 0.5*h, y + 0.5*k2);
k4:=h * yp(t + h, y + k3);
T(y + (k1+k4)/6.0 + (k2+k3)/3.0, t + h);
}
fcn loop(h,n,[(y,t)]){
if(n % 10 == 1)
pri... |
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... | #Vlang | Vlang | fn main() {
limit := 201 // means sieve numbers < 201
// sieve
mut c := []bool{len: limit} // c for composite. false means prime candidate
c[1] = true // 1 not considered prime
mut p := 2
for {
// first allowed optimization: outer loop only goes to sqrt(limit)
p2... |
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 ... | #Phix | Phix | constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"}
integer r = find("Zag",s) ?r -- 2 (first)
r = find("Zag",s,r+1) ?r -- 10 (next)
r = find("Zag",s,r+1) ?r -- 0 (no more)
r = rfind("Zag",s) ?r -- 10 (last)
r = find("Zo... |
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,... | #Scala | Scala | import akka.actor.{Actor, ActorSystem, Props}
import scala.collection.immutable.TreeSet
import scala.xml.XML
// Reports a list with all languages recorded in the Wiki
private object Acquisition {
val (endPoint, prefix) = ("http://rosettacode.org/mw/api.php", "Category:")
val (maxPlaces, correction) = (50, 2)
... |
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... | #Ceylon | Ceylon | shared void run() {
class Numeral(shared Character char, shared Integer int) {}
value tiers = [
[Numeral('I', 1), Numeral('V', 5), Numeral('X', 10)],
[Numeral('X', 10), Numeral('L', 50), Numeral('C', 100)],
[Numeral('C', 100), Numeral('D', 500), Numeral('M', 1k)]
];
String toRoman(Integer hindu, I... |
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... | #CoffeeScript | CoffeeScript | roman_to_demical = (s) ->
# s is well-formed Roman Numeral >= I
numbers =
M: 1000
D: 500
C: 100
L: 50
X: 10
V: 5
I: 1
result = 0
for c in s
num = numbers[c]
result += num
if old_num < num
# If old_num exists and is less than num, then
# we need to s... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Kotlin | Kotlin | // version 1.1.2
typealias DoubleToDouble = (Double) -> Double
fun f(x: Double) = x * x * x - 3.0 * x * x + 2.0 * x
fun secant(x1: Double, x2: Double, f: DoubleToDouble): Double {
val e = 1.0e-12
val limit = 50
var xa = x1
var xb = x2
var fa = f(xa)
var i = 0
while (i++ < limit) {
... |
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:
... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
printf("Welcome to Rock, Paper, Scissors.\n_
Rock beats scissors, Scissors beat paper, and Paper beats rock.\n\n")
historyP := ["rock","paper","scissors"] # seed player history
winP := winC := draws := 0 # totals
beats := ["rock","scissors","paper","... |
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... | #J | J | rle=: ;@(<@(":@(#-.1:),{.);.1~ 1, 2 ~:/\ ])
rld=: ;@(-.@e.&'0123456789' <@({:#~1{.@,~".@}:);.2 ]) |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Rust | Rust | use num::Complex;
fn main() {
let n = 8;
let z = Complex::from_polar(&1.0,&(1.0*std::f64::consts::PI/n as f64));
for k in 0..=n-1 {
println!("e^{:2}πi/{} ≈ {:>14.3}",2*k,n,z.powf(2.0*k as f64));
}
} |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Scala | Scala | def rootsOfUnity(n:Int)=for(k <- 0 until n) yield Complex.fromPolar(1.0, 2*math.Pi*k/n) |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Scheme | Scheme | (define pi (* 4 (atan 1)))
(do ((n 2 (+ n 1)))
((> n 10))
(display n)
(do ((k 0 (+ k 1)))
((>= k n))
(display " ")
(display (make-polar 1 (* 2 pi (/ k n)))))
(newline)) |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Run_BASIC | Run BASIC | print "FOR 1,2,3 => ";quad$(1,2,3)
print "FOR 4,5,6 => ";quad$(4,5,6)
FUNCTION quad$(a,b,c)
d = b^2-4 * a*c
x = -1*b
if d<0 then
quad$ = str$(x/(2*a));" +i";str$(sqr(abs(d))/(2*a))+" , "+str$(x/(2*a));" -i";str$(sqr(abs(d))/abs(2*a))
else
quad$ = str$(x/(2*a)+sqr(d)/(2*a))+" , "+str$... |
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... | #Scala | Scala | import ArithmeticComplex._
object QuadraticRoots {
def solve(a:Double, b:Double, c:Double)={
val d = b*b-4.0*a*c
val aa = a+a
if (d < 0.0) { // complex roots
val re= -b/aa;
val im = math.sqrt(-d)/aa;
(Complex(re, im), Complex(re, -im))
}
else { // real roots
val re=if (b... |
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... | #FALSE | FALSE | [^$1+][$32|$$'z>'a@>|$[\%]?~[13\'m>[_]?+]?,]#% |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Vorpal | Vorpal | self.print_primes = method(m){
p = new()
p.fill(0, m, 1, true)
count = 0
i = 2
while(i < m){
if(p[i] == true){
p.fill(i+i, m, i, false)
count = count + 1
}
i = i + 1
}
('primes: ' + count + ' in ' + m).print()
for(i = 2, i < m, i = i + 1){
if(p[i] == t... |
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 ... | #Phixmonti | Phixmonti | "mouse" "hat" "cup" "deodorant" "television"
"soap" "methamphetamine" "severed cat heads" "cup"
pstack
stklen tolist reverse
0 tolist var t
"Enter string to search: " input var s nl
true
while
head s == if
len t swap 0 put var t
endif
tail nip len
endwhile
drop
t len not if
"String not found... |
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,... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "gethttp.s7i";
include "scanstri.s7i";
const type: popularityHash is hash [string] integer;
const type: rankingHash is hash [integer] array string;
const func array string: getLangs (in string: buffer) is func
result
var array string: langs is 0 times "";
local
var ... |
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... | #Clojure | Clojure | (def arabic->roman
(partial clojure.pprint/cl-format nil "~@R"))
(arabic->roman 147)
;"CXXIII"
(arabic->roman 99)
;"XCIX" |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Common_Lisp | Common Lisp |
(defun mapcn (chars nums string)
(loop as char across string as i = (position char chars) collect (and i (nth i nums))))
(defun parse-roman (R)
(loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R)
as (A B) on nums if A sum (if (and B (< A B)) (- A) A)))
|
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Lambdatalk | Lambdatalk |
1) defining the function:
{def func {lambda {:x} {+ {* 1 :x :x :x} {* -3 :x :x} {* 2 :x}}}}
-> func
2) printing roots:
{S.map {lambda {:x}
{if {< {abs {func :x}} 0.0001}
then {br}- a root found at :x else}}
{S.serie -1 3 0.01}}
->
- a root found at 7.528699885739343e-16 ... |
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:
... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Rock.bas"
110 RANDOMIZE
120 STRING CH$(1 TO 3)*8,K$*1
130 NUMERIC PLWINS(1 TO 3),SCORE(1 TO 3),PLSTAT(1 TO 3),CMSTAT(1 TO 3),PLCHOICE,CMCHOICE
140 CALL INIC
150 DO
160 CALL GUESS
170 PRINT :PRINT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors, ESC = quit)"
180 DO
190 LET K$=INKEY$
2... |
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... | #Java | Java | import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() ... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "complex.s7i";
const proc: main is func
local
var integer: n is 0;
var integer: k is 0;
begin
for n range 2 to 10 do
write(n lpad 2 <& ": ");
for k range 0 to pred(n) do
write(polar(1.0, 2.0 * PI * flt(k) / flt(n)) digits 4... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Sidef | Sidef | func roots_of_unity(n) {
n.of { |j|
exp(2i * Num.pi / n * j)
}
}
roots_of_unity(5).each { |c|
printf("%+.5f%+.5fi\n", c.reals)
} |
http://rosettacode.org/wiki/Roots_of_a_quadratic_function | Roots of a quadratic function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Write a program to find the roots of a quadratic equation, i.e., solve the equation
a
x
2
+
b
x
+
c
=
0
{\displaystyle ax^{2}+bx+c=0}
.
Your program must correctly handle n... | #Scheme | Scheme | (define (quadratic a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(if (and (real? delta) (> delta 0))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list
(/ (- (sqrt delta) b) 2 a)
(/ (+ (sqrt delta) b) -2 a))))))
; ex... |
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... | #Fantom | Fantom |
class Rot13
{
static Str rot13 (Str input)
{
Str result := ""
input.each |Int c|
{
if ((c.lower >= 'a') && (c.lower <= 'm'))
result += (c+13).toChar
else if ((c.lower >= 'n') && (c.lower <= 'z'))
result += (c-13).toChar
else
result += c.toChar
}
return... |
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... | #WebAssembly | WebAssembly | (module
(import "js" "print" (func $print (param i32)))
(memory 4096)
(func $sieve (export "sieve") (param $n i32)
(local $i i32)
(local $j i32)
(set_local $i (i32.const 0))
(block $endLoop
(loop $loop
(br_if $endLoop (i32.ge_s (get_local $i) (get_local $n)))
(i32.store8 (get_local... |
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 ... | #PHP | PHP | $haystack = array("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
foreach (array("Washington","Bush") as $needle) {
$i = array_search($needle, $haystack);
if ($i === FALSE) // note: 0 is also considered false in PHP, so you need to specifically check for FALSE
echo "$needle is not in ha... |
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,... | #Sidef | Sidef | require('MediaWiki::API')
var api = %O<MediaWiki::API>.new(
Hash(api_url => 'http://rosettacode.org/mw/api.php')
)
var languages = []
var gcmcontinue
loop {
var apih = api.api(
Hash(
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Categor... |
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... | #CLU | CLU | roman = cluster is encode
rep = null
dmap = struct[v: int, s: string]
darr = array[dmap]
own chunks: darr := darr$
[dmap${v: 1000, s: "M"},
dmap${v: 900, s: "CM"},
dmap${v: 500, s: "D"},
dmap${v: 400, s: "CD"},
dmap${v: 100, s: "C"},
dmap${v: 90, s:... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
# Decode the Roman numeral in the given string.
# Returns 0 if the string does not contain a valid Roman numeral.
sub romanToDecimal(str: [uint8]): (rslt: uint16) is
# Look up a Roman digit
sub digit(char: uint8): (val: uint16) is
# Definition of Roman numeral... |
http://rosettacode.org/wiki/Roots_of_a_function | Roots of a function | Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
| #Liberty_BASIC | Liberty BASIC | ' Finds and output the roots of a given function f(x),
' within a range of x values.
' [RC]Roots of an function
mainwin 80 12
xMin =-1
xMax = 3
y =f( xMin) ' Since Liberty BASIC has an 'eval(' function the fn
' and limits would be better entered via 'inp... |
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:
... | #J | J | require'general/misc/prompt strings' NB. was 'misc strings' in older versions of J
game=:3 :0
outcomes=. rps=. 0 0 0
choice=. 1+?3
while.#response=. prompt' Choose Rock, Paper or Scissors: ' do.
playerchoice=. 1+'rps' i. tolower {.deb response
if.4 = playerchoice do.
smoutput 'Unknown response.'
... |
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... | #JavaScript | JavaScript | function encode(input) {
var encoding = [];
var prev, count, i;
for (count = 1, prev = input[0], i = 1; i < input.length; i++) {
if (input[i] != prev) {
encoding.push([count, prev]);
count = 1;
prev = input[i];
}
else
count ++;
}
... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Sparkling | Sparkling | function unity_roots(n) {
// nth-root(1) = cos(2 * k * pi / n) + i * sin(2 * k * pi / n)
return map(range(n), function(idx, k) {
return {
"re": cos(2 * k * M_PI / n),
"im": sin(2 * k * M_PI / n)
};
});
}
// pirnt 6th roots of unity
foreach(unity_roots(6), function(k, v) {
printf("%.3f%+.3fi\n", v.re, v.... |
http://rosettacode.org/wiki/Roots_of_unity | Roots of unity | The purpose of this task is to explore working with complex numbers.
Task
Given n, find the nth roots of unity.
| #Stata | Stata | n=7
exp(2i*pi()/n*(0::n-1))
1
+-----------------------------+
1 | 1 |
2 | .623489802 + .781831482i |
3 | -.222520934 + .974927912i |
4 | -.900968868 + .433883739i |
5 | -.900968868 - .433883739i |
6 | -.222520934 - .974927912i |
7 | ... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const type: roots is new struct
var float: x1 is 0.0;
var float: x2 is 0.0;
end struct;
const func roots: solve (in float: a, in float: b, in float: c) is func
result
var roots: solution is roots.value;
local
var float: sd ... |
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... | #Sidef | Sidef | var sets = [
[1, 2, 1],
[1, 2, 3],
[1, -2, 1],
[1, 0, -4],
[1, -1e6, 1],
]
func quadroots(a, b, c) {
var root = sqrt(b**2 - 4*a*c)
[(-b + root) / (2 * a),
(-b - root) / (2 * a)]
}
sets.each { |coefficients|
say ... |
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... | #FBSL | FBSL | #APPTYPE CONSOLE
REM Create a CircularQueue object
REM CQ.Store item
REM CQ.Find items
REM CQ.Forward nItems
REM CQ.Recall
REM SO CQ init WITH "A"... "Z"
REM CQ.Find "B"
REM QC.Forward 13
REM QC.Recall
CLASS CircularQueue
items[]
head
tail
here
SUB INITIALIZE(dArray)
head = 0
tail = 0
here = 0
FOR ... |
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... | #Xojo | Xojo | Dim limit, prime, i As Integer
Dim s As String
Dim t As Double
Dim sieve(100000000) As Boolean
REM Get the maximum number
While limit<1 Or limit > 100000000
Print("Max number? [1 to 100000000]")
s = Input
limit = CDbl(s)
Wend
REM Do the calculations
t = Microseconds
prime = 2
While prime^2 < limit
For i = 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 ... | #Picat | Picat | import util.
go =>
Haystack=["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Bush", "Charlie", "Bush", "Boz", "Zag"],
println("First 'Bush'"=search_list(Haystack,"Bush")),
println("Last 'Bush'"=search_list_last(Haystack,"Bush")),
println("All 'Bush'"=search_list_all(Haystack,"Bush")),
catch(WaldoI... |
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,... | #SNOBOL4 | SNOBOL4 | -include "url.sno"
http.recl = "K,32767" ;* Read next 32767 characters
;* of very long lines.
rclangs = "http://rosettacode.org/mw/api.php?"
+ "format=xml&action=query&generator=categorymembers&"
+ "gcmtitle=Category:Programming%20Languages&"
+ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.