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/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,...
#Maple
Maple
count_sizes := proc(arr_name,arr_pop,i,lst) local index := i; local language; for language in lst do language := language[1]: arr_name(index) := txt["query"]["pages"][language]["title"][10..]: if(assigned(txt["query"]["pages"][language]["categoryinfo"]["size"])) then arr_pop(index) := txt["query"]["pages"]...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Roman_Numeral_Test is function To_Roman (Number : Positive) return String is subtype Digit is Integer range 0..9; function Roman (Figure : Digit; I, V, X : Character) return String is begin case Figure is when 0 => return ""; ...
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...
#ANTLR
ANTLR
/* Parse Roman Numerals   Nigel Galloway March 16th., 2012 */ grammar ParseRN ;   options { language = Java; } @members { int rnValue; int ONE; }   parseRN: ({rnValue = 0;} rn NEWLINE {System.out.println($rn.text + " = " + rnValue);})* ;   rn : (Thousand {rnValue += 1000;})* hundreds? tens? units?;   hundreds: {ON...
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
#Clojure
Clojure
    (defn findRoots [f start stop step eps] (filter #(-> (f %) Math/abs (< eps)) (range start stop step)))  
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Bash
Bash
#!/bin/bash echo "What will you choose? [rock/paper/scissors]" read response aiThought=$(echo $[ 1 + $[ RANDOM % 3 ]]) case $aiThought in 1) aiResponse="rock" ;; 2) aiResponse="paper" ;; 3) aiResponse="scissors" ;; esac echo "AI - $aiResponse" responses="$response$aiResponse" case $responses in rockrock)...
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
rle: if not dup: drop return []   swap ]   local :source chars pop-from source 1 for c in source: if = c over: ++ else: 1 c & & return [   rld: ) for pair in swap: repeat &< pair: &> pair concat(     rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" !. dup !. rld
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.
#IDL
IDL
n = 5 print, exp( dcomplex( 0, 2*!dpi/n) ) ^ ( 1 + indgen(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.
#J
J
rou=: [: ^ 0j2p1 * i. % ]   rou 4 1 0j1 _1 0j_1   rou 5 1 0.309017j0.951057 _0.809017j0.587785 _0.809017j_0.587785 0.309017j_0.951057
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Python
Python
  """Count bare `lang` tags in wiki markup. Requires Python >=3.6.   Uses the Python standard library `urllib` to make MediaWiki API requests. """   from __future__ import annotations   import functools import gzip import json import logging import platform import re   from collections import Counter from collections i...
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...
#IDL
IDL
compile_OPT IDL2   print, "input a, press enter, input b, press enter, input c, press enter" read,a,b,c Promt='Enter values of a,b,c and hit enter'   a0=0.0 b0=0.0 c0=0.0 ;make them floating point variables   x=-b+sqrt((b^2)-4*a*c) y=-b-sqrt((b^2)-4*a*c) z=2*a d= x/z e= y/z   print, d,e
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...
#IS-BASIC
IS-BASIC
  100 PROGRAM "Quadratic.bas" 110 PRINT "Enter coefficients a, b and c:":INPUT PROMPT "a= ,b= ,c= ":A,B,C 120 IF A=0 THEN 130 PRINT "The coefficient of x^2 can not be 0." 140 ELSE 150 LET D=B^2-4*A*C 160 SELECT CASE SGN(D) 170 CASE 0 180 PRINT "The single root is ";-B/2/A 190 CASE 1 200 PRINT "The re...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#C.2B.2B
C++
#include <iostream> #include <istream> #include <ostream> #include <fstream> #include <cstdlib> #include <string>   // the rot13 function std::string rot13(std::string s) { static std::string const lcalph = "abcdefghijklmnopqrstuvwxyz", ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   std::string result; std::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: ...
#OCaml
OCaml
let y' t y = t *. sqrt y let exact t = let u = 0.25*.t*.t +. 1.0 in u*.u   let rk4_step (y,t) h = let k1 = h *. y' t y in let k2 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k1) in let k3 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k2) in let k4 = h *. y' (t +. h) (y +. k3) in (y +. (k1+.k4)/.6.0 +. (k2+.k3)/.3.0, t +. h)   let...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Ring
Ring
  # Project: Rosetta Code/Find unimplemented tasks   load "stdlib.ring" ros= download("http://rosettacode.org/wiki/Category:Programming_Tasks") lang = "Ring" pos = 1 num = 0 totalros = 0 rosname = "" rostitle = "" see "Tasks not implemented in " + lang + " language:" + nl for n = 1 to len(ros) nr = searchstrin...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Ruby
Ruby
require 'rosettacode' require 'time'   module RosettaCode def self.get_unimplemented(lang) programming_tasks = [] category_members("Programming_Tasks") {|task| programming_tasks << task}   lang_tasks = [] category_members(lang) {|task| lang_tasks << task}   lang_tasks_omit = [] category_member...
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). ...
#PicoLisp
PicoLisp
: (any "((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))") -> ((data "quoted data" 123 5) (data (!@# (5) "(more" "data)")))   : (view @) +---+-- data | | | +-- "quoted data" | | | +-- 123 | | | +-- 5 | +---+-- data | +---+-- !@# | +---+-- 5 | +-...
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...
#Phix
Phix
with javascript_semantics sequence numbers = repeat(0,6) integer t,n while true do for i=1 to length(numbers) do sequence ni = sq_rand(repeat(6,4)) numbers[i] = sum(ni)-min(ni) end for t = sum(numbers) n = sum(sq_ge(numbers,15)) if t>=75 and n>=2 then exit end if ?"re-rolling..."...
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...
#Sidef
Sidef
func sieve(limit) { var sieve_arr = [false, false, (limit-1).of(true)...] gather { sieve_arr.each_kv { |number, is_prime| if (is_prime) { take(number) for i in (number**2 .. limit `by` number) { sieve_arr[i] = false } ...
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...
#Objeck
Objeck
use HTTP; use XML;   class RosettaCount { function : Main(args : String[]) ~ Nil { taks_xml := HttpGet("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"); parser := XmlParser->New(taks_xml); if(parser->Parse()) { task_...
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 ...
#Lingo
Lingo
haystack = ["apples", "oranges", "bananas", "oranges"] needle = "oranges"   pos = haystack.getPos(needle) if pos then put "needle found at index "&pos else put "needle not found in haystack" end if   -- "needle found at index 2"
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,...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]]; Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}]; b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"], "category, out of " ~~ x:Num...
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...
#ALGOL_68
ALGOL 68
[]CHAR roman = "MDCLXVmdclxvi"; # UPPERCASE for thousands # []CHAR adjust roman = "CCXXmmccxxii"; []INT arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1); []INT adjust arabic = (100000, 100000, 10000, 10000, 1000, 1000, 100, 100, 10, 10, 1, 1, 0);   PROC arabic to ro...
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...
#APL
APL
fromRoman←{ rmn←(⎕A,⎕A,'*')[(⎕A,⎕UCS 96+⍳26)⍳⍵] ⍝ make input uppercase dgt←↑'IVXLCDM' (1 5 10 50 100 500 1000) ⍝ values of roman digits ~rmn∧.∊⊂dgt[1;]:⎕SIGNAL 11 ⍝ domain error if non-roman input map←dgt[2;dgt[1;]⍳rmn] ⍝ map digits to values +/map×1-2×(2</map),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
#CoffeeScript
CoffeeScript
  print_roots = (f, begin, end, step) -> # Print approximate roots of f between x=begin and x=end, # using sign changes as an indicator that a root has been # encountered. x = begin y = f(x) last_y = y   cross_x_axis = -> (last_y < 0 and y > 0) or (last_y > 0 and y < 0)   console.log '-----' wh...
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: ...
#BASIC
BASIC
DIM pPLchoice(1 TO 3) AS INTEGER, pCMchoice(1 TO 3) AS INTEGER DIM choices(1 TO 3) AS STRING DIM playerwins(1 TO 3) AS INTEGER DIM playerchoice AS INTEGER, compchoice AS INTEGER DIM playerwon AS INTEGER, compwon AS INTEGER, tie AS INTEGER DIM tmp AS INTEGER   ' Do it this way for QBasic; FreeBASIC supports direct array...
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...
#Delphi
Delphi
  program RunLengthTest;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TRLEPair = record count: Integer; letter: Char; end;   TRLEncoded = TArray<TRLEPair>;   TRLEncodedHelper = record helper for TRLEncoded public procedure Clear; function Add(c: Char): Integer; procedure Encode(Da...
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.
#Java
Java
import java.util.Locale;   public class Test {   public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); }   public static void unity(int n) { System.out.printf("%n%d: ", n);   //all the way around the circle at even intervals for (double angle...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Racket
Racket
  #lang racket   (require net/url net/uri-codec json)   (define (get-text page) (define ((get k) x) (dict-ref x k)) ((compose1 (get '*) car (get 'revisions) cdar hash->list (get 'pages) (get 'query) read-json get-pure-port string->url format) "http://rosettacode.org/mw/api.php?~a" (alist->form-ur...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Raku
Raku
my $lang = '(no language)'; my $total = 0; my %blanks;   for lines() { when / '<lang>' / { %blanks{$lang}++; $total++; } when ms/ '==' '{{' 'header' '|' ( <-[}]>+? ) '}}' '==' / { $lang = $0.lc; } }   say "$total bare language tag{ 's' if $total != 1 }\n"; say .value, ' in ', .key for %blanks.sort;
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...
#J
J
p.
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Java
Java
public class QuadraticRoots { private static class Complex { double re, im;   public Complex(double re, double im) { this.re = re; this.im = im; }   @Override public boolean equals(Object obj) { if (obj == this) {return true;} 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...
#Clojure
Clojure
(ns rosettacode.rot-13)   (let [a (int \a) m (int \m) A (int \A) M (int \M) n (int \n) z (int \z) N (int \N) Z (int \Z)] (defn rot-13 [^Character c] (char (let [i (int c)] (cond-> i (or (<= a i m) (<= A i M)) (+ 13) (or (<= n i z) (<= N i Z)) (- 13))))))   (apply str (map rot-13 "The Q...
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: ...
#Octave
Octave
  #Applying the Runge-Kutta method (This code must be implement on a different file than the main one).   function temp = rk4(func,x,pvi,h) K1 = h*func(x,pvi); K2 = h*func(x+0.5*h,pvi+0.5*K1); K3 = h*func(x+0.5*h,pvi+0.5*K2); K4 = h*func(x+h,pvi+K3); temp = pvi + (K1 + 2*K2 + 2*K3 + K4)/6; endfuncti...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Run_BASIC
Run BASIC
WordWrap$ = "style='white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word'" a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages") a$ = word$(a$,2,"mw-subcategories") a$ = word$(a$,1,"</table>") i = instr(a$,"/wiki/Category:") html "<...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Rust
Rust
  use std::collections::{BTreeMap, HashSet};   use reqwest::Url; use serde::Deserialize; use serde_json::Value;   /// A Rosetta Code task. #[derive(Clone, PartialEq, Eq, Hash, Debug, Deserialize)] pub struct Task { /// The ID of the page containing the task in the MediaWiki API. #[serde(rename = "pageid")] ...
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). ...
#Pike
Pike
class Symbol(string name) { string _sprintf(int type) { switch(type) { case 's': return name; case 'O': return sprintf("(Symbol: %s)", name||""); case 'q': return name; case 't': return "Symbol"; default: return sprintf("%"+int2ch...
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...
#PHP
PHP
<?php   $attributesTotal = 0; $count = 0;   while($attributesTotal < 75 || $count < 2) { $attributes = [];   foreach(range(0, 5) as $attribute) { $rolls = [];   foreach(range(0, 3) as $roll) { $rolls[] = rand(1, 6); }   sort($rolls); array_shift($rolls);   ...
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...
#Simula
Simula
BEGIN INTEGER ARRAY t(0:1000); INTEGER i,j,k; FOR i:=0 STEP 1 UNTIL 1000 DO t(i):=1; t(0):=0; t(1):=0; i:=0; FOR i:=i WHILE i<1000 DO BEGIN FOR i:=i WHILE i<1000 AND t(i)=0 DO i:=i+1; IF i<1000 THEN BEGIN j:=2; k:=j*i; FOR k:=k WHIL...
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...
#OCaml
OCaml
ocaml str.cma unix.cma -I +pcre pcre.cma -I +netsys netsys.cma -I +equeue equeue.cma \ -I +netstring netstring.cma -I +netclient netclient.cma -I +xml-light xml-light.cma countex.ml
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...
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} [StringX] = {Module.link ['x-oz://system/String.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   AllTasksUrl = "http://rosettacode.org/mw/api.php?action=query&lis...
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 ...
#Lisaac
Lisaac
+ haystack : ARRAY[STRING]; haystack := "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo".split; "Washington Bush".split.foreach { needle : STRING; haystack.has(needle).if { haystack.first_index_of(needle).print; ' '.print; needle.print; '\n'.print; } else { needle.print; " is not in hays...
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,...
#Nim
Nim
import httpclient, json, re, strformat, strutils, algorithm   const LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json" CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" let regex = ...
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...
#ALGOL_W
ALGOL W
BEGIN   PROCEDURE ROMAN (INTEGER VALUE NUMBER; STRING(15) RESULT CHARACTERS; INTEGER RESULT LENGTH); COMMENT Returns the Roman number of an integer between 1 and 3999. "MMMDCCCLXXXVIII" (15 characters long) is the longest Roman number under 4000; BEGIN INTEGER PLACE, POWER;   P...
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...
#AppleScript
AppleScript
  ------------- INTEGER VALUE OF A ROMAN STRING ------------   -- romanValue :: String -> Int on romanValue(s) script roman property mapping : [["M", 1000], ["CM", 900], ["D", 500], ["CD", 400], ¬ ["C", 100], ["XC", 90], ["L", 50], ["XL", 40], ["X", 10], ["IX", 9], ¬ ["V", 5], ["IV",...
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
#Common_Lisp
Common Lisp
(defun find-roots (function start end &optional (step 0.0001)) (let* ((roots '()) (value (funcall function start)) (plusp (plusp value))) (when (zerop value) (format t "~&Root found at ~W." start)) (do ((x (+ start step) (+ x step))) ((> x end) (nreverse roots)) (setf val...
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: ...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   set choice1=rock set choice2=paper set choice3=scissors set freq1=0 set freq2=0 set freq3=0 set games=0 set won=0 set lost=0 set tie=0   :start cls echo Games - %games% : Won - %won% : Lost - %lost% : Ties - %tie% choice /c RPS /n /m "[R]ock, [P]aper or [S]cissors? "   set ch...
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...
#E
E
def rle(string) { var seen := null var count := 0 var result := [] def put() { if (seen != null) { result with= [count, seen] } } for ch in string { if (ch != seen) { put() seen := ch count := 0 } count += 1 } put() return result }   def unrle(coded) { var...
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.
#JavaScript
JavaScript
function Root(angle) { with (Math) { this.r = cos(angle); this.i = sin(angle) } }   Root.prototype.toFixed = function(p) { return this.r.toFixed(p) + (this.i >= 0 ? '+' : '') + this.i.toFixed(p) + 'i' }   function roots(n) { var rs = [], teta = 2*Math.PI/n for (var angle=0, i=0; i<n; angle+=teta, i+=1) rs.push( new...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#REXX
REXX
/*REXX pgm finds and displays bare language (<lang>) tags without a language specified. */ parse arg iFID . /*obtain optional argument from the CL.*/ if iFID=='' | iFID="," then iFID= 'BARELANG.HTM' /*Not specified? Then assume default*/ call lineout iFID ...
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...
#jq
jq
# If there are infinitely many solutions, emit true; # if none, emit empty; # otherwise always emit two. # For numerical accuracy, Middlebrook's approach is adopted: def quadratic_roots(a; b; c): if a == 0 and b == 0 then if c == 0 then true # infinitely many else empty # none end elif 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...
#CLU
CLU
rot13 = proc (c: char) returns (char) base: int letter: bool := false if c>='A' & c<='Z' then base := char$c2i('A') letter := true elseif c>='a' & c<='z' then base := char$c2i('a') letter := true end if ~letter then return(c) end return(char$i2c((char$c2i(c)-b...
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#PARI.2FGP
PARI/GP
rk4(f,dx,x,y)={ my(k1=dx*f(x,y), k2=dx*f(x+dx/2,y+k1/2), k3=dx*f(x+dx/2,y+k2/2), k4=dx*f(x+dx,y+k3)); y + (k1 + 2*k2 + 2*k3 + k4) / 6 }; rate(x,y)=x*sqrt(y); go()={ my(x0=0,x1=10,dx=.1,n=1+(x1-x0)\dx,y=vector(n)); y[1]=1; for(i=2,n,y[i]=rk4(rate, dx, x0 + dx * (i - 1), y[i-1])); print("x\ty\trel. err.\n----...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Scala
Scala
libraryDependencies ++= Seq( "org.json4s"%%"json4s-native"%"3.6.0", "com.softwaremill.sttp"%%"core"%"1.5.11", "com.softwaremill.sttp"%%"json4s"%"1.5.11")
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Tcl
Tcl
package require Tcl 8.5 package require http package require json package require struct::set   fconfigure stdout -buffering none   # Initialize a cache of lookups array set cache {} proc log msg { #puts -nonewline $msg }   proc get_tasks {category} { global cache if {[info exists cache($category)]} { retu...
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). ...
#Potion
Potion
isdigit = (c): 47 < c ord and c ord < 58. iswhitespace = (c): c ord == 10 or c ord == 13 or c == " ".   # str: a string of the form "...<nondigit>[{<symb>}]..." # i: index to start at (must be the index of <nondigit>) # => returns (<the symbol as a string>, <index after the last char>) parsesymbol = (str, i) : datum...
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...
#Plain_English
Plain English
To add an attribute to some stats: Allocate memory for an entry. Put the attribute into the entry's attribute. Append the entry to the stats.   An attribute is a number.   An entry is a thing with an attribute.   To find a count of attributes greater than fourteen in some stats: Put 0 into the count. Get an entry from ...
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...
#Smalltalk
Smalltalk
| potentialPrimes limit | limit := 100. potentialPrimes := Array new: limit. potentialPrimes atAllPut: true. 2 to: limit sqrt do: [:testNumber | (potentialPrimes at: testNumber) ifTrue: [ (testNumber * 2) to: limit by: testNumber do: [:nonPrime | potentialPrimes at: nonPrime put: false ]...
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...
#Perl
Perl
use HTTP::Tiny;   my $site = "http://rosettacode.org"; my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";   my $response = HTTP::Tiny->new->get("$site$list_url"); for ($response->{content} =~ /cm.*?title="(.*?)"/g) { (my $slug = $_) =~ tr/ /_/; ...
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 ...
#Logo
Logo
to indexof :item :list if empty? :list [(throw "NOTFOUND 0)] if equal? :item first :list [output 1] output 1 + indexof :item butfirst :list end   to showindex :item :list make "i catch "NOTFOUND [indexof :item :list] ifelse :i = 0 [(print :item [ not found in ] :list)] [(print :item [ found at position ] :i [...
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 ...
#Lua
Lua
list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} --contents of my desk   item = io.read()   for i,v in ipairs(list) if v == item then print(i) end end
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Objeck
Objeck
use HTTP; use RegEx; use XML; use Collection;   class RosettaRank { function : Main(args : String[]) ~ Nil { langs_xml := ""; client := HttpClient->New(); in := client->Get("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=5000&format=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...
#APL
APL
toRoman←{ ⍝ Digits and corresponding values ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I' vs←1000, ,100 10 1∘.×9 5 4 1 ⍝ Input ≤ 0 is invalid ⍵≤0:⎕SIGNAL 11 { 0=d←⊃⍸vs≤⍵:⍬ ⍝ Find highest digit in number (d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number }⍵ }
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Applesoft_BASIC
Applesoft BASIC
10 LET R$ = "MCMXCIX" 20 GOSUB 100 PRINT "ROMAN NUMERALS DECODED" 30 LET R$ = "MMXII" 40 GOSUB 100 50 LET R$ = "MDCLXVI" 60 GOSUB 100 70 LET R$ = "MMMDCCCLXXXVIII" 80 GOSUB 100 90 END 100 PRINT M$R$, 110 LET M$ = CHR$ (13) 120 GOSUB 150"ROMAN NUMERALS DECODE given R$" 130 PRINT N; 140 RETU...
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
#D
D
import std.stdio, std.math, std.algorithm;   bool nearZero(T)(in T a, in T b = T.epsilon * 4) pure nothrow { return abs(a) <= b; }   T[] findRoot(T)(immutable T function(in T) pure nothrow fi, in T start, in T end, in T step=T(0.001L), T tolerance = T(1e-4L)) { if (step.nearZero)...
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: ...
#BBC_BASIC
BBC BASIC
PRINT"Welcome to the game of rock-paper-scissors" PRINT "Each player guesses one of these three, and reveals it at the same time." PRINT "Rock blunts scissors, which cut paper, which wraps stone." PRINT "If both players choose the same, it is a draw!" PRINT "When you've had enough, choose Q." DIM rps%(2),g$(3) g$()="ro...
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...
#Elena
Elena
import system'text; import system'routines; import extensions; import extensions'text;   singleton compressor { string compress(string s) { auto tb := new TextBuilder(); int count := 0; char current := s[0]; s.forEach:(ch) { if (ch == current) { ...
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.
#jq
jq
def nthroots(n): (8 * (1|atan)) as $twopi | range(0;n) | (($twopi * .) / n) as $angle | [ ($angle | cos), ($angle | sin) ];   nthroots(10)
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.
#Julia
Julia
nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ]
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Ruby
Ruby
require "open-uri" require "cgi"   tasks = ["Greatest_common_divisor", "Greatest_element_of_a_list", "Greatest_subsequential_sum"] part_uri = "http://rosettacode.org/wiki?action=raw&title=" Report = Struct.new(:count, :tasks) result = Hash.new{|h,k| h[k] = Report.new(0, [])}   tasks.each do |task| puts "processing...
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...
#Julia
Julia
using Printf   function quadroots(x::Real, y::Real, z::Real) a, b, c = promote(float(x), y, z) if a ≈ 0.0 return [-c / b] end Δ = b ^ 2 - 4a * c if Δ ≈ 0.0 return [-sqrt(c / a)] end if Δ < 0.0 Δ = complex(Δ) end d = sqrt(Δ) if b < 0.0 d -= b return [d / 2a, 2c / d] else ...
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...
#Kotlin
Kotlin
import java.lang.Math.*   data class Equation(val a: Double, val b: Double, val c: Double) { data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> "${i}i" else -> "$r + ${i}i" } }   data cl...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. rot-13.   DATA DIVISION. LOCAL-STORAGE SECTION. 78 STR-LENGTH VALUE 100.   78 normal-lower VALUE "abcdefghijklmnopqrstuvwxyz". 78 rot13-lower VALUE "nopqrstuvwxyzabcdefghijklm".   78 normal-upper VALUE "ABCDEFGHIJKLMNOPQ...
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: ...
#Pascal
Pascal
program RungeKuttaExample;   uses sysutils;   type TDerivative = function (t, y : Real) : Real;   procedure RungeKutta(yDer : TDerivative; var t, y : array of Real; dt : Real); var dy1, dy2, dy3, dy4 : Real; idx : Cardinal;   begin for idx := Lo...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Wren
Wren
/* rc_find_unimplemented_tasks.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 // ret...
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). ...
#Python
Python
import re   dbg = False   term_regex = r'''(?mx) \s*(?: (?P<brackl>\()| (?P<brackr>\))| (?P<num>\-?\d+\.\d+|\-?\d+)| (?P<sq>"[^"]*")| (?P<s>[^(^)\s]+) )'''   def parse_sexp(sexp): stack = [] out = [] if dbg: print("%-6s %-14s %-44s %-s" % tuple("term value ...
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...
#PureBasic
PureBasic
#heroicAttributeMinimum = 15 #heroicAttributeCountMinimum = 2 #attributeSumMinimum = 75 #attributeCount = 6   Procedure roll_attribute() Protected i, sum Dim rolls(3)   For i = 0 To 3 rolls(i) = Random(6, 1) Next i   ;sum the highest three rolls SortArray(rolls(), #PB_Sort_Descending) For i = 0 To 2 ...
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...
#SNOBOL4
SNOBOL4
define('sieve(n)i,j,k,p,str,res') :(sieve_end) sieve i = lt(i,n - 1) i + 1 :f(sv1) str = str (i + 1) ' ' :(sieve) sv1 str break(' ') . j span(' ') = :f(return) sieve = sieve j ' ' sieve = gt(j ^ 2,n) sieve str :s(return) ;* Opt1 res = '' str (arb ' ') @p ((j ^ 2) ' ...
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...
#Phix
Phix
-- -- demo\rosetta\rosettacode_cache.e -- ================================ -- -- Common routines for handling rc_cache etc. -- without js -- (libcurl, file i/o, peek, progress..) include builtins\timedate.e constant day = timedelta(days:=1) integer refresh_cache = 21*day -- 0 for always [NB refresh_cache += timedelta(d...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Flush ' empty stack Inventory Queue Haystack= "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt" Append Haystack, "foo", "bar", "bletch", "foo", "bar", "fum", "fred", "jim", "sheila", "barney", "flarp", "zxc" Append Haystack, ...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * Create a list of Rosetta Code languages showing the number of tasks * This program's logic is basically that of the REXX program * rearranged to my taste and utilizing the array class of ooRexx * which offers a neat way of sorting as desired, see...
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...
#AppleScript
AppleScript
------------------ ROMAN INTEGER STRINGS -----------------   -- roman :: Int -> String on roman(n) set kvs to {["M", 1000], ["CM", 900], ["D", 500], ¬ ["CD", 400], ["C", 100], ["XC", 90], ["L", 50], ¬ ["XL", 40], ["X", 10], ["IX", 9], ["V", 5], ¬ ["IV", 4], ["I", 1]}   script stringAdded...
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...
#Arturo
Arturo
syms: #[ M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 ]   fromRoman: function [roman][ ret: 0 loop 0..(size roman)-2 'ch [ fst: roman\[ch] snd: roman\[ch+1] valueA: syms\[fst] valueB: syms\[snd]   if? valueA < valueB -> ret: ret - valueA else -> ret: ret + valueA ] return ret + syms\[last roman...
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
#Dart
Dart
double fn(double x) => x * x * x - 3 * x * x + 2 * x;   findRoots(Function(double) f, double start, double stop, double step, double epsilon) sync* { for (double x = start; x < stop; x = x + step) { if (fn(x).abs() < epsilon) yield x; } }   main() { // Vector(-9.381755897326649E-14, 0.9999999999998124, 1.9999...
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: ...
#C
C
  #include <stdio.h> #include <stdlib.h> #define LEN 3   /* pick a random index from 0 to n-1, according to probablities listed in p[] which is assumed to have a sum of 1. The values in the probablity list matters up to the point where the sum goes over 1 */ int rand_idx(double *p, int n) { double s = rand() / ...
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...
#Elixir
Elixir
defmodule Run_length do def encode(str) when is_bitstring(str) do to_char_list(str) |> encode |> to_string end def encode(list) when is_list(list) do Enum.chunk_by(list, &(&1)) |> Enum.flat_map(fn chars -> to_char_list(length(chars)) ++ [hd(chars)] end) end   def decode(str) when is_bitstring(str)...
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Kotlin
Kotlin
import java.lang.Math.*   data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> i.toString() + 'i' else -> "$r + ${i}i" } }   fun unity_roots(n: Number) = (1..n.toInt() - 1).map { val a = it * 2 * PI / n.toDouble() ...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Rust
Rust
  extern crate regex;   use std::io; use std::io::prelude::*;   use regex::Regex;   fn find_bare_lang_tags(input: &str) -> Vec<(Option<String>, i32)> { let mut language_pairs = vec![]; let mut language = None; let mut counter = 0_i32;   let header_re = Regex::new(r"==\{\{header\|(?P<lang>[[:alpha:]]+)\}...
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Scala
Scala
// Map lines to a list of Option(heading -> task) for each bare lang tag found. val headerFormat = "==[{]+header[|]([^}]*)[}]+==".r val langFormat = "<lang([^>]*)>".r def mapped(lines: Seq[String], taskName: String = "") = { var heading = "" for (line <- lines; head = headerFormat.findFirstMatchIn(line).map(_ ...
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...
#lambdatalk
lambdatalk
  1) using lambdas:   {def equation {lambda {:a :b :c} {b equation :a*x{sup 2}+:b*x+:c=0} {{lambda {:a' :b' :d} {if {> :d 0} then {{lambda {:b' :d'} {equation.disp {+ :b' :d'} {- :b' :d'} 2 real roots} } :b' {/ {sqrt :d} :a'}} else {if {< :d 0} then {{lambda {:b' :d'} ...
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...
#Commodore_BASIC
Commodore BASIC
1 rem rot-13 cipher 2 rem rosetta code 10 print chr$(147);chr$(14); 25 gosub 1000 30 print chr$(147);"Enter a message to translate." 35 print:print "Press CTRL-Z when finished.":print 40 mg$="":gosub 2000 45 print chr$(147);"Processing...":gosub 3000 50 print chr$(147);"The translated message is:" 55 print:print cm$ 10...
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: ...
#Perl
Perl
sub runge_kutta { my ($yp, $dt) = @_; sub { my ($t, $y) = @_; my @dy = $dt * $yp->( $t , $y ); push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[0]/2 ); push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[1]/2 ); push @dy, $dt * $yp->( $t + $dt , $y + $dy[2] ); return $t + $dt, $y + ($dy[0] + 2*$dy[1] + 2*$dy[...
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#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/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). ...
#Racket
Racket
  #lang racket (define input #<<--- ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) --- )   (read (open-input-string input))  
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...
#Python
Python
import random random.seed() attributes_total = 0 count = 0   while attributes_total < 75 or count < 2: attributes = []   for attribute in range(0, 6): rolls = []   for roll in range(0, 4): result = random.randint(1, 6) rolls.append(result)   sorted_rolls = sorted(...
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...
#Standard_ML
Standard ML
  val segmentedSieve = fn N => (* output : list of {segment=bit segment, start=number at startposition segment} *)   let   val NSegmt= 120000000; (* segment size *)     val inf2i = IntInf.toInt ; val i2inf = IntInf.fromInt ; val isInt = f...
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...
#PicoLisp
PicoLisp
(load "@lib/http.l")   (client "rosettacode.org" 80 "mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" (while (from " title=\"") (let Task (till "\"") (client "rosettacode.org" 80 (pack "wiki/" (replace Task " " "_")) (let Cnt 0 ...
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#PureBasic
PureBasic
Procedure handleError(value, msg.s) If value = 0 MessageRequester("Error", msg) End EndIf EndProcedure   handleError(InitNetwork(), "Unable to initialize network functions.") If OpenConsole() Define url$, x1$, y1$, title$, unescapedTitle$, encodedURL$ Define x2, i, j, totalExamples, totalTasks url$ = ...
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 ...
#Maple
Maple
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]: occurences := ListTools:-SearchAll(needle,haystack): try #first occurence printf("The first occurence is at index %d\n", occurences[1]); #last occurence, note that StringTools:-SearchAll()retuns a list of all occurences positions pr...
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,...
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   fun {GetPage RawUrl} Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} Url = {VirtualString.toString RawUrl} OutParams HttpResponseParams i...
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...
#Arturo
Arturo
nums: [[1000 "M"] [900 "CM"] [500 "D"] [400 "CD"] [100 "C"] [90 "XC"] [50 "L"] [40 "XL"] [10 "X"] [9 "IX"] [5 "V"] [4 "IV"] [1 "I"])   toRoman: function [x][ ret: "" idx: 0 initial: x loop nums 'num [ d: num\0 l: num\1   i: 0 while [i<initial/d] [ ret: ret ++ l ...