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/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 ...
#Io
Io
NotFound := Exception clone List firstIndex := method(obj, indexOf(obj) ifNil(NotFound raise) ) List lastIndex := method(obj, reverseForeach(i,v, if(v == obj, return i) ) NotFound raise )   haystack := list("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo") list("Washington","...
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.Aeson import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (simpleHttp) import Data.List (sortBy, groupBy) import Data.Function (on) import Data.Map (Map, toList)   -- Record representing a single language. data Language = Language { name ...
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...
#Burlesque
Burlesque
  "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" =[{^^[~\/L[Sh}\m  
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.
#CoffeeScript
CoffeeScript
# Find the n nth-roots of 1 nth_roots_of_unity = (n) -> (complex_unit_vector(2*Math.PI*i/n) for i in [1..n])   complex_unit_vector = (rad) -> new Complex(Math.cos(rad), Math.sin(rad))   class Complex constructor: (@real, @imag) -> toString: -> round_z = (n) -> if Math.abs(n) < 0.00005 then 0 else 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.
#Common_Lisp
Common Lisp
(defun roots-of-unity (n) (loop for i below n collect (cis (* pi (/ (* 2 i) n)))))
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "os" "regexp" "strings" )   type header struct { start, end int lang string }   type data struct { count int names *[]string }   func newData(count int, name string) *data { return &data{count, &[]string{name}} }   var bma...
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...
#C.2B.2B
C++
#include <iostream> #include <utility> #include <complex>   typedef std::complex<double> complex;   std::pair<complex, complex> solve_quadratic_equation(double a, double b, double c) { b /= a; c /= a; double discriminant = b*b-4*c; if (discriminant < 0) return std::make_pair(complex(-b/2, std::sqrt(-discri...
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...
#BaCon
BaCon
INPUT "String: ", s$ PRINT "Output: ", REPLACE$(s$, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", 2)
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: ...
#J
J
NB.*rk4 a Solve function using Runge-Kutta method NB. y is: y(ta) , ta , tb , tstep NB. u is: function to solve NB. eg: fyp rk4 1 0 10 0.1 rk4=: adverb define 'Y0 a b h'=. 4{. y T=. a + i.@>:&.(%&h) b - a Y=. Yt=. Y0 for_t. }: T do. ty=. t,Yt k1=. h * u ty k2=. h * u ty + -: h,k1 k3=. h * u ty + -: h,k...
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...
#JavaScript
JavaScript
(function (strXPath) { var xr = document.evaluate( strXPath, document, null, 0, 0 ),   oNode = xr.iterateNext(), lstTasks = [];   while (oNode) { lstTasks.push(oNode.title); oNode = xr.iterateNext(); }   return [ lstTasks.length + " items found in " + document.title, ...
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). ...
#J
J
NB. character classes: 0: paren, 1: quote, 2: whitespace, 3: wordforming (default) chrMap=: '()';'"';' ',LF,TAB,CR   NB. state columns correspond to the above character classes NB. first digit chooses next state. NB. second digit is action 0: do nothing, 1: start token, 2: end token states=: 10 10#: ".;._2]0 :0 11 2...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#REXX
REXX
/*REXX program fixes (changes) depreciated HTML code tags with newer tags. */ @="<"; old.=; old.1 = @'%s>'  ; new.1 = @"lang %s>" old.2 = @'/%s>'  ; new.2 = @"/lang>" old.3 = @'code %s>'  ; new.3 = @"lang %s>" ...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Ruby
Ruby
# get all stdin in one string #text = $stdin.read # for testing, use text = DATA.read slash_lang = '/lang' langs = %w(foo bar baz) # actual list of languages declared here for lang in langs text.gsub!(Regexp.new("<(#{lang})>")) {"<lang #$1>"} text.gsub!(Regexp.new("</#{lang}>"), "<#{slash_lang}>") end text.gsub!(/<...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Vlang
Vlang
/*import math.big fn main() { //var bb, ptn, etn, dtn big.Int pt := "Rosetta Code" println("Plain text: $pt")   // a key set big enough to hold 16 bytes of plain text in // a single block (to simplify the example) and also big enough // to demonstrate efficiency of modular exponentiat...
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...
#Java
Java
import java.util.List; import java.util.Random; import java.util.stream.Stream;   import static java.util.stream.Collectors.toList;   public class Rpg {   private static final Random random = new Random();   public static int genAttribute() { return random.ints(1, 6 + 1) // Throw dices between 1 and 6 ...
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...
#Run_BASIC
Run BASIC
input "Gimme the limit:"; limit dim flags(limit) for i = 2 to limit for k = i*i to limit step i flags(k) = 1 next k if flags(i) = 0 then print i;", "; next i
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...
#Go
Go
package main   import ( "bytes" "encoding/xml" "fmt" "io" "io/ioutil" "net/http" "net/url" "strings" )   func req(u string, foundCm func(string)) string { resp, err := http.Get(u) if err != nil { fmt.Println(err) // connection or request fail return "" } 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 ...
#J
J
Haystack =: ;:'Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo' Needles =: ;:'Washington Bush'   Haystack i. Needles NB. first positions 9 4 Haystack i: Needles NB. last positions 9 7
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,...
#HicEst
HicEst
CHARACTER cats*50000, catlist*50000, sortedCat*50000, sample*100 DIMENSION RankNr(1)   READ(ClipBoard) cats catlist = ' ' pos = 1 ! find language entries like * 100 doors (2 members) nr = 0 ! after next '*' find next "name" = '100 doors' and next "(...)" = '(2 members)' : 1 EDIT(Text=cats, SetPos=pos, Righ...
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
#11l
11l
F f(x) R x^3 - 3 * x^2 + 2 * x   -V step = 0.001 -V start = -1.0 -V stop = 3.0   V sgn = f(start) > 0 V x = start   L x <= stop V value = f(x)   I value == 0 print(‘Root found at ’x) E I (value > 0) != sgn print(‘Root found near ’x)   sgn = value > 0 x += step
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...
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct stream_t stream_t, *stream; struct stream_t { /* get function is supposed to return a byte value (0-255), or -1 to signify end of input */ int (*get)(stream); /* put function does output, one byte at a time */ int (*put)(stream, int); };   /* next two struct...
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.
#Crystal
Crystal
require "complex"   def roots_of_unity(n) (0...n).map { |k| Math.exp((2 * Math::PI * k / n).i) } 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.
#D
D
import std.stdio, std.range, std.algorithm, std.complex; import std.math: PI;   auto nthRoots(in int n) pure nothrow { return n.iota.map!(k => expi(PI * 2 * (k + 1) / n)); }   void main() { foreach (immutable i; 1 .. 6) writefln("#%d: [%(%5.2f, %)]", i, i.nthRoots); }
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...
#Groovy
Groovy
import java.util.function.Predicate import java.util.regex.Matcher import java.util.regex.Pattern   class FindBareTags { private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"") private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==") priva...
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...
#Clojure
Clojure
(defn quadratic "Compute the roots of a quadratic in the form ax^2 + bx + c = 1. Returns any of nil, a float, or a vector." [a b c] (let [sq-d (Math/sqrt (- (* b b) (* 4 a c))) f #(/ (% b sq-d) (* 2 a))] (cond (neg? sq-d) nil (zero? sq-d) (f +) (pos? sq-d) [(f +) (f -)] ...
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Common_Lisp
Common Lisp
(defun quadratic (a b c) (list (/ (+ (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 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...
#BASIC
BASIC
CLS INPUT "Enter a string: ", s$ ans$ = "" FOR a = 1 TO LEN(s$) letter$ = MID$(s$, a, 1) IF letter$ >= "A" AND letter$ <= "Z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) ELSEIF letter$ >= "a" AND letter$ <= "z" THEN ...
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: ...
#Java
Java
import static java.lang.Math.*; import java.util.function.BiFunction;   public class RungeKutta {   static void runge(BiFunction<Double, Double, Double> yp_func, double[] t, double[] y, double dt) {   for (int n = 0; n < t.length - 1; n++) { double dy1 = dt * yp_func.apply(t[n], y[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...
#Julia
Julia
using HTTP, JSON   const baseuri = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:" const enduri = "&cmlimit=500&format=json" queries(x) = baseuri * HTTP.Strings.escapehtml(x) * enduri   function getimplemented(query) tasksdone = Vector{String}() request = query wh...
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...
#Lua
Lua
local requests = require('requests') local lang = arg[1]   local function merge_tables(existing, from_req) local result = existing   for _, v in ipairs(from_req) do result[v.title] = true end   return result end   local function get_task_list(category) local url = 'http://www.rosettacode.org/mw/api.php'...
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). ...
#Java
Java
package jfkbits;   import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.Iterator;   public class LispTokenizer implements Iterator<Token> { // Instance variables have default access to allow unit tests access....
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Rust
Rust
  extern crate regex;   use std::io; use std::io::prelude::*;   use regex::Regex;   const LANGUAGES: &str = "_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit \ avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp \ cpp-qt csharp c...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Scala
Scala
object FixCodeTags extends App { val rx = // See for regex explanation: https://regex101.com/r/N8X4x7/3/ // Flags ignore case, dot matching line breaks, unicode support s"(?is)<(?:(?:code\\s+)?(${langs.mkString("|")}))>(.+?|)<\\/(?:code|\\1)>".r   def langs = // Real list of langs goes here Seq("...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Wren
Wren
import "/big" for BigInt   var pt = "Rosetta Code" System.print("Plain text:  : %(pt)") var n = BigInt.new("9516311845790656153499716760847001433441357") var e = BigInt.new("65537") var d = BigInt.new("5617843187844953170308463622230283376298685") var ptn = BigInt.zero // convert plain text to a number for (b...
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...
#JavaScript
JavaScript
function roll() { const stats = { total: 0, rolls: [] } let count = 0;   for(let i=0;i<=5;i++) { let d6s = [];   for(let j=0;j<=3;j++) { d6s.push(Math.ceil(Math.random() * 6)) }   d6s.sort().splice(0, 1); rollTotal = d6s.reduce((a, b) => a+b, 0);   stats.rolls.push(roll...
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Rust
Rust
fn primes(n: usize) -> impl Iterator<Item = usize> { const START: usize = 2; if n < START { Vec::new() } else { let mut is_prime = vec![true; n + 1 - START]; let limit = (n as f64).sqrt() as usize; for i in START..limit + 1 { let mut it = is_prime[i - START..].ite...
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...
#Haskell
Haskell
import Network.Browser import Network.HTTP import Network.URI import Data.List import Data.Maybe import Text.XML.Light import Control.Arrow   justifyR w = foldl ((.return).(++).tail) (replicate w ' ') showFormatted t n = t ++ ": " ++ justifyR 4 (show n)   getRespons url = do rsp <- Network.Browser.browse $ do ...
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 ...
#Java
Java
import java.util.List; import java.util.Arrays;   List<String> haystack = Arrays.asList("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");   for (String needle : new String[]{"Washington","Bush"}) { int index = haystack.indexOf(needle); if (index < 0) System.out.println(needle + " is...
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,...
#Icon_and_Unicon
Icon and Unicon
$define RCLANGS "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo" $define RCUA "User-Agent: Unicon Rosetta 0.1" $define RCXUA "X-Unicon: http://unicon.org/"   link strings link hexcvt   procedure main() ...
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
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Roots_Of_Function is package Real_Io is new Ada.Text_Io.Float_Io(Long_Float); use Real_Io;   function F(X : Long_Float) return Long_Float is begin return (X**3 - 3.0*X*X + 2.0*X); end F;   Step  : constant Long_Float := 1.0E-6; Start : constant L...
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...
#C.23
C#
using System.Collections.Generic; using System.Linq; using static System.Console; using static System.Linq.Enumerable;   namespace RunLengthEncoding { static class Program { public static string Encode(string input) => input.Length ==0 ? "" : input.Skip(1) .Aggregate((t:input[0].ToString()...
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Delphi
Delphi
  program Roots_of_unity;   {$APPTYPE CONSOLE}   uses System.VarCmplx;   function RootOfUnity(degree: integer): Tarray<Variant>; var k: Integer; begin SetLength(result, degree); for k := 0 to degree - 1 do Result[k] := VarComplexFromPolar(1, 2 * pi * k / degree); end;   const n = 3; var num: Variant; be...
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...
#Haskell
Haskell
import System.Environment import Network.HTTP import Text.Printf import Text.Regex.TDFA import Data.List import Data.Array import qualified Data.Map as Map   {-| Takes a string and cuts out the text matched in the MatchText array. -} splitByMatches :: String -> [MatchText String] -> [String] splitByMatches str matches...
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...
#D
D
import std.math, std.traits;   CommonType!(T1, T2, T3)[] naiveQR(T1, T2, T3) (in T1 a, in T2 b, in T3 c) pure nothrow if (isFloatingPoint!T1) { alias ReturnT = typeof(typeof(return).init[0]); if (a == 0) return [ReturnT(c / b)]; // It's a linear function. immutable R...
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...
#BASIC256
BASIC256
  # rot13 Cipher v2.0 # basic256 1.1.4.0 # 2101031238   dec$ = "" TYPE$ = "cleartext " ctext$ = "" sp = 0 iOffset = 13 #offset assumed TO be 13 - uncomment LINE 11 TO change   INPUT "For decrypt enter " + "<d> " + " -- else press enter > ",dec$ # INPUT "Enter offset > ", iOffset   IF dec$ = "d" OR dec$ = ...
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: ...
#JavaScript
JavaScript
  function rk4(y, x, dx, f) { var k1 = dx * f(x, y), k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0), k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0), k4 = dx * f(x + dx, +y + k3);   return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0; }   function f(x, y) { return x * Math.sqrt(y); }   f...
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...
#Maple
Maple
#Example with the Maple Language lan := "Maple": x := URL:-Get(cat("http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_", StringTools:-SubstituteAll(lan, " ", "_")), output = content): x := StringTools:-StringSplit(x, "<h2><span class=\"mw-headline\" id=\"Not_implemented\">Not implemented</span>")[2]: x := St...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[ImportAll] ImportAll[lang_String] := Module[{data, continue, cmcontinue, extra, xml, next}, data = {}; continue = True; cmcontinue = ""; While[continue, extra = If[cmcontinue =!= "", "&cmcontinue=" <> cmcontinue, ""]; xml = Import["http://www.rosettacode.org/w/api.php?action=query&list=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). ...
#JavaScript
JavaScript
String.prototype.parseSexpr = function() { var t = this.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g) for (var o, c=0, i=t.length-1; i>=0; i--) { var n, ti = t[i].trim() if (ti == '"') return else if (ti == '(') t[i]='[', c+=1 else if (ti == ')') t[i]=']', c-=1 else if ((n=+ti) == ti) t[i]=n else t[i] = '\'' +...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Sidef
Sidef
var langs = %w(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic...
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#zkl
zkl
var BN=Import.lib("zklBigNum");   n:=BN("9516311845790656153499716760847001433441357"); e:=BN("65537"); d:=BN("5617843187844953170308463622230283376298685");   const plaintext="Rossetta Code"; pt:=BN(Data(Int,0,plaintext)); // convert string (as stream of bytes) to big int if(pt>n) throw(Exception.ValueError("Message ...
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...
#Julia
Julia
roll_skip_lowest(dice, sides) = (r = rand(collect(1:sides), dice); sum(r) - minimum(r))   function rollRPGtoon() attributes = zeros(Int, 6) attsum = 0 gte15 = 0   while attsum < 75 || gte15 < 2 for i in 1:6 attributes[i] = roll_skip_lowest(4, 6) end attsum = sum(attri...
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...
#S-BASIC
S-BASIC
  comment Find primes up to the specified limit (here 1,000) using classic Sieve of Eratosthenes end   $constant limit = 1000 $constant false = 0 $constant true = FFFFH   var i, k, count, col = integer dim integer flags(limit)   print "Finding primes from 2 to";limit   rem - initialize table for i = 1 to limit ...
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...
#Icon_and_Unicon
Icon and Unicon
$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500" $define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title=" $define RCUA "User-Agent: Unicon Rosetta 0.1" $define RCXUA "X-Unicon: http://unicon.org/" $define ...
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 ...
#JavaScript
JavaScript
var haystack = ['Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo'] var needles = ['Bush', 'Washington']   for (var i in needles) { var found = false; for (var j in haystack) { if (haystack[j] == needles[i]) { found = true; break; } } if ...
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,...
#J
J
require 'web/gethttp xml/sax/x2j regex'   x2jclass 'rcPopLang'   rx =: (<0 1) {:: (2#a:) ,~ rxmatches rxfrom ]   'Popular Languages' x2jDefn /  := langs  : langs =: 0 2 $ a: html/body/div/div/div/ul/li  := langs =: langs ,^:(a:~:{.@[)~ lang ; ' \((\d+) members?\)' rx y h...
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...
#11l
11l
V roman_values = [(‘I’, 1), (‘IV’, 4), (‘V’, 5), (‘IX’, 9), (‘X’, 10), (‘XL’, 40), (‘L’, 50), (‘XC’, 90), (‘C’, 100), (‘CD’, 400), (‘D’, 500), (‘CM’, 900), (‘M’, 1000)]   F roman_value(=roman) V total = 0 L(symbol, value) reversed(:roman_values) L roman.starts_with(symbol...
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
#ALGOL_68
ALGOL 68
MODE DBL = LONG REAL; FORMAT dbl = $g(-long real width, long real width-6, -2)$;   MODE XY = STRUCT(DBL x, y); FORMAT xy root = $f(dbl)" ("b("Exactly", "Approximately")")"$;   MODE DBLOPT = UNION(DBL, VOID); MODE XYRES = UNION(XY, VOID);   PROC find root = (PROC (DBL)DBL f, DBLOPT in x1, in x2, in x error, in y error)X...
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...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <iterator> #include <limits> #include <tuple>   namespace detail_ {   // For constexpr digit<->number conversions. constexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'};   // Helper function to encode a run-length. template <typename OutputIterator> c...
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.
#EchoLisp
EchoLisp
  (define (roots-1 n) (define theta (// (* 2 PI) n)) (for/list ((i n)) (polar 1. (* theta i))))   (roots-1 2) → (1+0i -1+0i) (roots-1 3) → (1+0i -0.4999999999999998+0.8660254037844388i -0.5000000000000004-0.8660254037844384i) (roots-1 4) → (1+0i 0+i -1+0i 0-i)  
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.
#ERRE
ERRE
  PROGRAM UNITY_ROOTS   ! ! for rosettacode.org !   BEGIN PRINT(CHR$(12);) !CLS N=5  ! this can be changed for any desired n ANGLE=0  ! start at ANGLE 0 REPEAT REAL=COS(ANGLE)  ! real axis is the x axis IF...
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...
#Icon_and_Unicon
Icon and Unicon
import Utils # To get the FindFirst class   procedure main() keys := ["{{header|","<lang>"] lang := "No language" tags := table(0) total := 0   ff := FindFirst(keys) f := reads(&input, -1)   f ? while tab(ff.locate()) do { if "{{header|" == 1(ff.getMatch(), ff.moveMatch()) then lang...
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...
#Delphi
Delphi
defmodule Quadratic do def roots(a, b, c) do IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})" d = b * b - 4 * a * c a2 = a * 2 cond do d > 0 -> sd = :math.sqrt(d) IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}" d == 0 -> IO.puts " ...
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...
#Elixir
Elixir
defmodule Quadratic do def roots(a, b, c) do IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})" d = b * b - 4 * a * c a2 = a * 2 cond do d > 0 -> sd = :math.sqrt(d) IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}" d == 0 -> IO.puts " ...
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...
#Batch_File
Batch File
  @echo off & setlocal enabledelayedexpansion   :: ROT13 obfuscator Michael Sanders - 2017 :: :: example: rot13.cmd Rire abgvpr cflpuvpf arire jva gur ybggrel?   :setup   set str=%* set buf=%str% set len=0   :getlength   if not defined buf goto :start set buf=%buf:~1% set /a len+=1 goto :getlength ...
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: ...
#jq
jq
def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   def while(cond; update): def _while: if cond then ., (update | _while) else empty end; _while;
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...
#Nim
Nim
import httpclient, strutils, xmltree, xmlparser, cgi, os     proc findrc(category: string): seq[string] =   var name = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:$#&cmlimit=500&format=xml" % encodeUrl(category) cmcontinue = "" client = newHttpClient()   whi...
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...
#Oz
Oz
declare [HTTPClient] = {Link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [XMLParser] = {Link ['x-oz://system/xml/Parser.ozf']}   fun {FindUnimplementedTasks Language} AllTasks = {FindCategory "Programming Tasks"} LangTasks = {FindCategory Language} in {ListDiff AllTasks LangTasks} end   fun {Fi...
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). ...
#Julia
Julia
  function rewritequotedparen(s) segments = split(s, "\"") for i in 1:length(segments) if i & 1 == 0 # even i ret = replace(segments[i], r"\(", s"_O_PAREN") segments[i] = replace(ret, r"\)", s"_C_PAREN") end end join(segments, "\"") end   function reconsdata(n, s...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Tcl
Tcl
set langs { ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Wren
Wren
import "./pattern" for Pattern   var source = """ Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu altera electram. Tota adhuc altera te sea, <code...
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...
#Kotlin
Kotlin
import kotlin.random.Random   fun main() { while (true) { val values = List(6) { val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4) rolls.sorted().take(3).sum() } val vsum = values.sum() val vcount = values.count { it >= 15 } if (vsum < 75 ...
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...
#SAS
SAS
proc iml; start sieve(n); a = J(n,1); a[1] = 0; do i = 1 to n; if a[i] then do; if i*i>n then return(a); a[i*(i:int(n/i))] = 0; end; end; finish;   a = loc(sieve(1000))`; create primes from a; append from a; close primes; quit;
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...
#J
J
require 'web/gethttp'   getAllTaskSolnCounts=: monad define tasks=. getCategoryMembers 'Programming_Tasks' counts=. getTaskSolnCounts &> tasks tasks;counts )   getTaskSolnCounts=: monad define makeuri=. 'http://www.rosettacode.org/w/index.php?title=' , ,&'&action=raw' wikidata=. gethttp makeuri urlencode y ...
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 ...
#jq
jq
  ["a","b","c"] | index("b") # => 1   ["a","b","c","b"] | index("b") # => 1   ["a","b","c","b"] | index("x") // error("element not found") # => jq: error: element not found   # Extra task - the last element of an array can be retrieved # using `rindex/` or by using -1 as an index into the array produced by `indices/1...
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,...
#Java
Java
import java.net.URL; import java.net.URLConnection; import java.io.*; import java.util.*;   public class GetRCLanguages { // Custom sort Comparator for sorting the language list // assumes the first character is the page count and the rest is the language name private static class LanguageComparator imp...
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...
#360_Assembly
360 Assembly
* Roman numerals Decode - 17/04/2019 ROMADEC CSECT USING ROMADEC,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST...
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
#ATS
ATS
  #include "share/atspre_staload.hats"   typedef d = double   fun findRoots ( start: d, stop: d, step: d, f: (d) -> d, nrts: int, A: d ) : void = ( // if start < stop then let val A2 = f(start) var nrts: int = nrts val () = if A2 = 0.0 then ( nrts := nrts + 1; $extfcall(void, "printf", "An exa...
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: ...
#11l
11l
V rules = [‘rock’ = ‘paper’, ‘scissors’ = ‘rock’, ‘paper’ = ‘scissors’] V previous = [‘rock’, ‘paper’, ‘scissors’]   L V human = input("\nchoose your weapon: ") V computer = rules[random:choice(previous)]   I human C (‘quit’, ‘exit’) L.break   E I human C rules previous.append(human) print...
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...
#Ceylon
Ceylon
shared void run() {   "Takes a string such as aaaabbbbbbcc and returns 4a6b2c" String compress(String string) { if (exists firstChar = string.first) { if (exists index = string.firstIndexWhere((char) => char != firstChar)) { return "``index````firstChar````compress(string[ind...
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.
#Factor
Factor
USING: math.functions prettyprint ;   1 3 roots .
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.
#Forth
Forth
: f0. ( f -- ) fdup 0e 0.001e f~ if fdrop 0e then f. ; : .roots ( n -- ) dup 1 do pi i 2* 0 d>f f* dup 0 d>f f/ ( F: radians ) fsincos cr ." real " f0. ." imag " f0. loop drop ;   3 set-precision 5 .roots
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...
#Java
Java
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Coll...
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...
#ERRE
ERRE
PROGRAM QUADRATIC   PROCEDURE SOLVE_QUADRATIC D=B*B-4*A*C IF ABS(D)<1D-6 THEN D=0 END IF CASE SGN(D) OF 0-> PRINT("the single root is ";-B/2/A) END -> 1-> F=(1+SQR(1-4*A*C/(B*B)))/2 PRINT("the real roots are ";-F*B/A;"and ";-C/B/F) END -> -1-> PRINT("the complex roo...
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...
#Factor
Factor
:: quadratic-equation ( a b c -- x1 x2 ) b sq a c * 4 * - sqrt :> sd b 0 < [ b neg sd + a 2 * / ] [ b neg sd - a 2 * / ] if :> x x c a x * / ;
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...
#BBC_BASIC
BBC BASIC
REPEAT INPUT A$ PRINT FNrot13(A$) UNTIL FALSE END   DEF FNrot13(A$) LOCAL A%,B$,C$ IF A$="" THEN ="" FOR A%=1 TO LEN A$ C$=MID$(A$,A%,1) IF C$<"A" OR (C$>"Z" AND C$<"a") OR C$>"z" THEN B$=B$+C$ ELSE IF (ASC(C$) AND &DF...
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: ...
#Julia
Julia
f(x, y) = x * sqrt(y) theoric(t) = (t ^ 2 + 4.0) ^ 2 / 16.0   rk4(f) = (t, y, δt) -> # 1st (result) lambda ((δy1) -> # 2nd lambda ((δy2) -> # 3rd lambda ((δy3) -> # 4th lambda ((δy4) -> ( δy1 + 2δy2 + 2δy3 + δy4 ) / 6 # 5th and deepest lambda: calc y_{n+1} )(...
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Kotlin
Kotlin
// version 1.1.2   typealias Y = (Double) -> Double typealias Yd = (Double, Double) -> Double   fun rungeKutta4(t0: Double, tz: Double, dt: Double, y: Y, yd: Yd) { var tn = t0 var yn = y(tn) val z = ((tz - t0) / dt).toInt() for (i in 0..z) { if (i % 10 == 0) { val exact = y(tn) ...
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...
#Perl
Perl
use LWP::UserAgent;   my $ua = LWP::UserAgent->new; $ua->agent('');   sub enc { join '', map {sprintf '%%%02x', ord} split //, shift } sub get { $ua->request( HTTP::Request->new( GET => shift))->content }   sub tasks { my($category) = shift; my $fmt = 'http://www.rosettacode.org/mw/api.php?' . 'ac...
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). ...
#Kotlin
Kotlin
// version 1.2.31   const val INDENT = 2   fun String.parseSExpr(): List<String>? { val r = Regex("""\s*("[^"]*"|\(|\)|"|[^\s()"]+)""") val t = r.findAll(this).map { it.value }.toMutableList() if (t.size == 0) return null var o = false var c = 0 for (i in t.size - 1 downTo 0) { val ti = ...
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#zkl
zkl
fcn replace(data,src,dstpat){ re,n,buf:=RegExp(src),0,Data(); while(re.search(data,True,n)){ matched:=re.matched; // L(L(12,3),"c") data[matched[0].xplode()]=re.sub(data,dstpat,buf); // "\1" --> "c" n=matched[0].sum(0); // move past change } } data:=File.stdin.read(); foreach src,dst in (T(...
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Ksh
Ksh
  #!/bin/ksh   # RPG attributes generator   # # Variables: # typeset -a attribs=( strength dexterity constitution intelligence wisdom charisma ) integer MINTOT=75 MIN15S=2   # # Functions: # # # Function _diceroll(sides, number, reportAs) - roll number of side-sided # # dice, report (s)sum or (a)array (pseudo) of r...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
valid = False; While[! valid, try = Map[Total[TakeLargest[#, 3]] &, RandomInteger[{1, 6}, {6, 4}]]; If[Total[try] > 75 && Count[try, _?(GreaterEqualThan[15])] >= 2, valid = True; ] ] {Total[try], try}
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...
#SASL
SASL
  show primes WHERE primes = sieve (2...) sieve (p : x ) = p : sieve {a <- x; a REM p > 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...
#Java
Java
  import java.util.ArrayList; import ScreenScrape;   public class CountProgramExamples { private static final String baseURL = "http://rosettacode.org/wiki/"; private static final String rootURL = "http://www.rosettacode.org/w/" + "api.php?action=query&list=categorymembers" + "&cmtitle=Category:...
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Julia
Julia
@show findfirst(["no", "?", "yes", "maybe", "yes"], "yes") @show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"]) @show findin(["no", "?", "yes", "maybe", "yes"], ["yes"]) @show find(["no", "?", "yes", "maybe", "yes"] .== "yes")
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,...
#jq
jq
#!/bin/bash   # produce lines of the form: [ "language", n ] function categories { curl -Ss 'http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000' |\ grep "/wiki/Category:" | grep member | grep -v '(.*(' |\ grep -v ' User</a>' |\ sed -e 's/.*title="Category://' -e 's/member.*//' |\ ...
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...
#11l
11l
V anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] V rnums = ‘M CM D CD C XC L XL X IX V IV I’.split(‘ ’)   F to_roman(=x) V ret = ‘’ L(a, r) zip(:anums, :rnums) (V n, x) = divmod(x, a) ret ‘’= r * n R ret   V test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
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...
#8080_Assembly
8080 Assembly
org 100h jmp test ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Takes a zero-terminated Roman numeral string in BC ;; and returns 16-bit integer in HL. ;; All registers destroyed. roman: dcx b romanfindend: inx b ; load next character ldax b inr e ana a ; are we there yet jnz romanfindend lxi h,0 ; ze...
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
#AutoHotkey
AutoHotkey
MsgBox % roots("poly", -0.99, 2, 0.1, 1.0e-5) MsgBox % roots("poly", -1, 3, 0.1, 1.0e-5)   roots(f,x1,x2,step,tol) { ; search for roots in intervals of length "step", within tolerance "tol" x := x1, y := %f%(x), s := (y>0)-(y<0) Loop % ceil((x2-x1)/step) { x += step, y := %f%(x), t := (y>0)-(y<0) If (...