task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#FreeBASIC_2
FreeBASIC
' FB 1.05.0 Win64   Function romanEncode(n As Integer) As String If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999 Dim roman1(0 To 2) As String = {"MMM", "MM", "M"} Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"} Dim roman3(0 To 8) As S...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#J
J
rom2d=: [: (+/ .* _1^ 0,~ 2</\ ]) 1 5 10 50 100 500 1000 {~ 'IVXLCDM'&i.
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
#Tcl
Tcl
proc froots {lambda {start -3} {end 3} {step 0.0001}} { set res {} set lastsign [sgn [apply $lambda $start]] for {set x $start} {$x <= $end} {set x [expr {$x + $step}]} { set sign [sgn [apply $lambda $x]] if {$sign != $lastsign} { lappend res [format ~%.11f $x] } ...
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Racket
Racket
  #lang racket (require math)   (define history (make-hash '((paper . 1) (scissors . 1) (rock . 1)))) (define total 3)   (define (update-history! human-choice) (set! total (+ total 1)) (hash-update! history human-choice add1 0))   (define (pick-one) (sample (discrete-dist '(paper scissors rock) ...
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#PHP
PHP
<?php function encode($str) { return preg_replace_callback('/(.)\1*/', function ($match) { return strlen($match[0]) . $match[1]; }, $str); }   function decode($str) { return preg_replace_callback('/(\d+)(\D)/', function($match) { return str_repeat($match[2], $match[1]); }, $str); }   ech...
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...
#LabVIEW
LabVIEW
  abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.  
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 ...
#Tcl
Tcl
set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo} foreach needle {Bush Washington} { if {[set idx [lsearch -exact $haystack $needle]] == -1} { error "$needle does not appear in the haystack" } else { puts "$needle appears at index $idx in the haystack" } }
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...
#FutureBasic
FutureBasic
window 1   local fn DecimaltoRoman( decimal as short ) as Str15 short arabic(12) Str15 roman(12) long i Str15 result : result = ""   arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400 arabic(4) = 100  : arabic(5) = 90  : arabic(6) = 50  : arabic(7) = 40 arabic(8) = 10  : arabic(9) =...
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...
#Java_2
Java
public class Roman { private static int decodeSingle(char letter) { switch(letter) { case 'M': return 1000; case 'D': return 500; case 'C': return 100; case 'L': return 50; case 'X': return 10; case 'V': return 5; case 'I': return 1; default: return 0; } } public static int decode(String ...
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
#TI-89_BASIC
TI-89 BASIC
import "/fmt" for Fmt   var secant = Fn.new { |f, x0, x1| var f0 = 0 var f1 = f.call(x0) for (i in 0...100) { f0 = f1 f1 = f.call(x1) if (f1 == 0) return [x1, "exact"] if ((x1-x0).abs < 1e-6) return [x1, "approximate"] var t = x0 x0 = x1 x1 = x1-f1*(x1...
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Raku
Raku
my %vs = ( options => [<Rock Paper Scissors>], ro => { ro => [ 2, '' ], pa => [ 1, 'Paper covers Rock: ' ], sc => [ 0, 'Rock smashes Scissors: ' ] }, pa => { ro => [ 0, 'Paper covers Rock: ' ], pa => [ 2, '' ], ...
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Picat
Picat
rle(S) = RLE => RLE = "", Char = S[1], I = 2, Count = 1, while (I <= S.len) if Char == S[I] then Count := Count + 1 else RLE := RLE ++ Count.to_string() ++ Char.to_string(), Count := 1, Char := S[I] end, I := I + 1 end, RLE := RLE ++ Count.to_string() ++ Char.to_s...
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...
#Lambdatalk
Lambdatalk
  abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.  
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 ...
#TorqueScript
TorqueScript
function findIn(%haystack,%needles) { %hc = getWordCount(%haystack); %nc = getWordCount(%needles);   for(%i=0;%i<%nc;%i++) { %nword = getWord(%needles,%i); %index[%nword] = -1; }   for(%i=0;%i<%hc;%i++) { %hword = getWord(%haystack,%i);   for(%j=0;%j<%nc;%j++) { %nword = getWord(%needles,%j);   ...
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...
#Go
Go
package main   import "fmt"   var ( m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"} m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"} m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"} m3 = []string{"", "M", "MM", "MMM", "I̅V̅", ...
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...
#JavaScript
JavaScript
var Roman = { Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4], ['IX', 9], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['M', 1000], ['I', 1], ['D', 500]], UnmappedStr : 'Q', parse: function(str) { var result = 0 for (var i=0; i<Roman.Values.leng...
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
#Wren
Wren
import "/fmt" for Fmt   var secant = Fn.new { |f, x0, x1| var f0 = 0 var f1 = f.call(x0) for (i in 0...100) { f0 = f1 f1 = f.call(x1) if (f1 == 0) return [x1, "exact"] if ((x1-x0).abs < 1e-6) return [x1, "approximate"] var t = x0 x0 = x1 x1 = x1-f1*(x1...
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Rascal
Rascal
import Prelude;   rel[str, str] whatbeats = {<"Rock", "Scissors">, <"Scissors", "Paper">, <"Paper", "Rock">};   list[str] ComputerChoices = ["Rock", "Paper", "Scissors"];   str CheckWinner(a, b){ if(b == getOneFrom(whatbeats[a])) return a; elseif(a == getOneFrom(whatbeats[b])) return b; else return "Nobody"; } ...
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...
#PicoLisp
PicoLisp
(de encode (Str) (pack (make (for (Lst (chop Str) Lst) (let (N 1 C) (while (= (setq C (pop 'Lst)) (car Lst)) (inc 'N) ) (link N C) ) ) ) ) )   (de decode (Str) (pack (make (let N 0 (for C (chop Str) ...
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...
#Lasso
Lasso
// Extend the string type   define string->rot13 => { local( rot13 = bytes, i, a, b )   with char in .eachCharacter let int = #char->integer do { // We only modify these ranges, set range if we should modify #int >= 65 and #int < 91  ? local(a=65,b=91) | #int...
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 ...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT SET haystack="Zig'Zag'Wally'Ronald'Bush'Krusty'Charlie'Bush'Bozo" PRINT "haystack=",haystack LOOP needle="Washington'Bush'Wally" SET table =QUOTES (needle) BUILD S_TABLE needle = table IF (haystack.ct.needle) THEN BUILD R_TABLE needle = table SET position=FILTER_INDEX(haystack,needle,-) RELEASE...
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 ...
#UNIX_Shell
UNIX Shell
if [ $1 ];then haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo"   index=$(echo $haystack|tr " " "\n"|grep -in "^$1$") if [ $? = 0 ];then quantity_of_hits=$(echo $index|tr " " "\n"|wc -l|tr -d " ") first_index=$(echo $index|cut -f 1 -d ":") if [ $quantity_of_hits = 1 ];then echo The sole index for $1 is: $f...
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...
#Golo
Golo
#!/usr/bin/env golosh ---- This module takes a decimal integer and converts it to a Roman numeral. ---- module Romannumeralsencode   augment java.lang.Integer {   function digits = |this| {   var remaining = this let digits = vector[] while remaining > 0 { digits: prepend(remaining % 10) remai...
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...
#jq
jq
def fromRoman: def addRoman(n): if length == 0 then n elif startswith("M") then .[1:] | addRoman(1000 + n) elif startswith("CM") then .[2:] | addRoman(900 + n) elif startswith("D") then .[1:] | addRoman(500 + n) elif startswith("CD") then .[2:] | addRoman(400 + n) elif startswith("C") then ...
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
#zkl
zkl
fcn findRoots(f,start,stop,step,eps){ [start..stop,step].filter('wrap(x){ f(x).closeTo(0.0,eps) }) }
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Red
Red
  Red [Purpose: "Implement a rock-paper-scissors game with weighted probability"]   prior: rejoin choices: ["r" "p" "s"]   while [ find choices pchoice: ask "choose rock: r, paper: p, or scissors: s^/" ] [ print ["AI Draws:" cchoice: random/only prior] cwin: select "rpsr" pchoice close: select "rspr" pchoice   pr...
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...
#PL.2FI
PL/I
declare (c1, c2) character (1); declare run_length fixed binary; declare input file;   open file (input) title ('/RLE.DAT,type(text),recsize(20000)'); on endfile (input) go to epilog;   get file (input) edit (c1) (a(1)); run_length = 1; do forever; get file (input) edit (c2) (a(1)); if c1 = c2 then run_leng...
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...
#Liberty_BASIC
Liberty BASIC
input "Type some text to be encoded, then ENTER. ";tx$   tex$ = Rot13$(tx$) print tex$ 'check print Rot13$(tex$)   wait   Function Rot13$(t$) if t$="" then Rot13$="" exit function end if for i = 1 to len(t$) c$=mid$(t$,i,1) ch$=c$ if (asc(c$)>=asc("A")) and (asc(c$)<=...
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 ...
#Ursala
Ursala
#import std   indices = ||<'missing'>!% ~&nSihzXB+ ~&lrmPE~|^|/~& num
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 ...
#VBA
VBA
Function IsInArray(stringToBeFound As Variant, arr As Variant, _ Optional start As Integer = 1, Optional reverse As Boolean = False) As Long 'Adapted from https://stackoverflow.com/questions/12414168/use-of-custom-data-types-in-vba Dim i As Long, lo As Long, hi As Long, stp As Long ' default return value if...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Groovy
Groovy
symbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ]   def roman(arabic) { def result = "" symbols.keySet().sort().reverse().each { while (arabic >= it) { arabic-=it result+=symbols[it] } } r...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Jsish
Jsish
prompt$ jsish -e 'require("Roman"); puts(Roman.fromRoman("MDCLXVI"));' 1666
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: ...
#REXX
REXX
/*REXX program plays rock─paper─scissors with a human; tracks what human tends to use. */ != '────────'; err=! "***error***"; @.=0 /*some constants for this program. */ prompt= ! 'Please enter one of: Rock Paper Scissors (or Quit)' $.p= 'paper' ; $.s= "scissors"; $.r= 'rock' /*list of the...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#C.2B.2B
C++
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream>   int digit_product(int base, int n) { int product = 1; for (; n != 0; n /= base) product *= n % base; return product; }   int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2;...
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#PowerBASIC
PowerBASIC
FUNCTION RLDecode (i AS STRING) AS STRING DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING   FOR Loop0 = 1 TO LEN(i) m = MID$(i, Loop0, 1) SELECT CASE m CASE "0" TO "9" rCount = rCount & m CASE ELSE IF LEN(rCount) THEN ...
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...
#Limbo
Limbo
implement Rot13;   include "sys.m"; sys: Sys; include "draw.m";   Rot13: module { init: fn(ctxt: ref Draw->Context, argv: list of string); };   stdout: ref Sys->FD; tab: array of int;   init(nil: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; stdout = sys->fildes(1); inittab(); args = tl args...
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 ...
#VBScript
VBScript
  data = "foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt," &_ "foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc," &_ "spqr,wombat,shme,foo,bar,baz,bongo,spam,eggs,snork,foo,bar," &_ "zot,blarg,wibble,toto,titi,tata,tutu,pippo,pluto,paperino,aap," &_ "noot,mies,oogle,foogle,boogle,zork...
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...
#Haskell
Haskell
digit :: Char -> Char -> Char -> Integer -> String digit x y z k = [[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !! (fromInteger k - 1)   toRoman :: Integer -> String toRoman 0 = "" toRoman x | x < 0 = error "Negative roman numeral" toRoman x | x >= 1000 = 'M' : toRoman (x - 100...
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...
#Julia
Julia
function parseroman(rnum::AbstractString) romandigits = Dict('I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000) mval = accm = 0 for d in reverse(uppercase(rnum)) val = try romandigits[d] catch throw(DomainError()) ...
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: ...
#Ring
Ring
  # Project : Rock-paper-scissors   load "stdlib.ring" load "guilib.ring"   width = 200 height = 200   myChose = 1 compChose = 1 nextPlayer = 1 myScore = 0 compScore = 0 C_FONTSIZE = 15   C_ROCK = "images/rock.jpg" C_PAPER = "images/paper.jpg" C_SCISSORS = "images/scissors.jpg"   ChoseList = [C_ROCK,C_PA...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Factor
Factor
USING: formatting grouping io kernel lists lists.lazy math math.parser math.primes math.primes.factors prettyprint ranges sequences sequences.extras ;   : rhonda? ( n base -- ? ) [ [ >base 1 group ] keep '[ _ base> ] map-product ] [ swap factors sum * ] 2bi = ;   : rhonda ( base -- list ) 1 lfrom swap '[ _ rhon...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Go
Go
package main   import ( "fmt" "rcu" "strconv" )   func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false }   func main() { for b := 2; b <= 36; b++ { if rcu.IsPrime(b) { continue } co...
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...
#PowerShell
PowerShell
function Compress-RLE ($s) { $re = [regex] '(.)\1*' $ret = "" foreach ($m in $re.Matches($s)) { $ret += $m.Length $ret += $m.Value[0] } return $ret }   function Expand-RLE ($s) { $re = [regex] '(\d+)(.)' $ret = "" foreach ($m in $re.Matches($s)) { $ret += [string]...
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...
#LiveCode
LiveCode
function rot13 S repeat with i = 1 to length(S) get chartonum(char i of S) if it < 65 or it > 122 or (it > 90 and it < 97) then next repeat put char it - 64 of "NOPQRSTUVWXYZABCDEFGHIJKLM nopqrstuvwxyzabcdefghijklm" into char i of S end repeat return S end rot13
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 ...
#Wart
Wart
def (pos x (seq | (head ... tail)) n) default n :to 0 if seq if (head = x) n (pos x tail n+1)
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...
#HicEst
HicEst
CHARACTER Roman*20   CALL RomanNumeral(1990, Roman) ! MCMXC CALL RomanNumeral(2008, Roman) ! MMVIII CALL RomanNumeral(1666, Roman) ! MDCLXVI   END   SUBROUTINE RomanNumeral( arabic, roman) CHARACTER roman DIMENSION ddec(13) DATA ddec/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1/   roman = ' ' tod...
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...
#K
K
romd: {v:1 5 10 50 100 500 1000@"IVXLCDM"?/:x; +/v*_-1^(>':v),0}
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: ...
#Ruby
Ruby
class RockPaperScissorsGame CHOICES = %w[rock paper scissors quit] BEATS = { 'rock' => 'paper', 'paper' => 'scissors', 'scissors' => 'rock', }   def initialize() @plays = { 'rock' => 1, 'paper' => 1, 'scissors' => 1, } @score = [0, 0, 0] # [0]:Hum...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#C
C
  #include<curl/curl.h> #include<string.h> #include<stdio.h>   #define MAX_LEN 1000   void searchChatLogs(char* searchString){ char* baseURL = "http://tclers.tk/conferences/tcl/"; time_t t; struct tm* currentDate; char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100]; int i,flag; FILE *fp;   CU...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#J
J
tobase=: (a.{~;48 97(+ i.)each 10 26) {~ #.inv isrhonda=: (*/@:(#.inv) = (* +/@q:))"0   task=: {{ for_base.(#~ 0=1&p:) }.1+i.36 do. k=.i.0 block=. 1+i.1e4 while. 15>#k do. k=. k, block#~ base isrhonda block block=. block+1e4 end. echo '' echo 'First 15 Rhondas in',b=.' base ',':',~...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Java
Java
public class RhondaNumbers { public static void main(String[] args) { final int limit = 15; for (int base = 2; base <= 36; ++base) { if (isPrime(base)) continue; System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base); int numbers[]...
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...
#Prolog
Prolog
% the test run_length :- L = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", writef('encode %s\n', [L]), encode(L, R), writeln(R), nl, writef('decode %w\n', [R]), decode(R, L1), writeln(L1).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % encode % % trans...
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...
#Locomotive_Basic
Locomotive Basic
10 INPUT "Enter a string: ",a$ 20 GOSUB 50 30 PRINT b$ 40 END 50 FOR i=1 TO LEN(a$) 60 n=ASC(MID$(a$,i,1)) 70 e=255 80 IF n>64 AND n<91 THEN e=90 ' uppercase 90 IF n>96 AND n<123 THEN e=122 ' lowercase 100 IF e<255 THEN n=n+13 110 IF n>e THEN n=n-26 120 b$=b$+CHR$(n) 130 NEXT 140 RETURN
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 ...
#Wren
Wren
import "/seq" for Lst   var find = Fn.new { |haystack, needle| var res = Lst.indicesOf(haystack, needle) if (!res[0]) Fiber.abort("Needle not found in haystack.") System.print("The needle occurs %(res[1]) time(s) in the haystack.") if (res[1] == 1) { System.print("It occurs at index %(res[2][0])...
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...
#Icon_and_Unicon
Icon and Unicon
link numbers # commas, roman   procedure main(arglist) every x := !arglist do write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***") end
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...
#Kotlin
Kotlin
// version 1.0.6   fun romanDecode(roman: String): Int { if (roman.isEmpty()) return 0 var n = 0 var last = 'O' for (c in roman) { when (c) { 'I' -> n += 1 'V' -> if (last == 'I') n += 3 else n += 5 'X' -> if (last == 'I') n += 8 else n += 10 ...
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: ...
#Run_BASIC
Run BASIC
pri$ = "RSPR" rps$ = "Rock,Paper,Sissors" [loop] button #r, "Rock", [r] button #p, "Paper", [p] button #s, "Scissors",[s] button #q, "Quit", [q] wait [r] y = 1 :goto [me] [p] y = 2 :goto [me] [s] y = 3 [me] cls y$ = word$(rps$,y,",") m = int((rnd(0) * 2) + 1) m$ = word$(rps$,m,",") print chr$(10);"You Chose:"...
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: ...
#Rust
Rust
extern crate rand; #[macro_use] extern crate rand_derive;   use std::io; use rand::Rng; use Choice::*;   #[derive(PartialEq, Clone, Copy, Rand, Debug)] enum Choice { Rock, Paper, Scissors, }   fn beats(c1: Choice, c2: Choice) -> bool { (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) ||...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Elixir
Elixir
#! /usr/bin/env elixir defmodule Mentions do def get(url) do {:ok, {{_, 200, _}, _, body}} = url |> String.to_charlist() |> :httpc.request() data = List.to_string(body) if Regex.match?(~r|<!Doctype HTML.*<Title>URL Not Found</Title>|s, data) do {:error, "log file not found"} el...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#F.23
F#
#!/usr/bin/env fsharpi let server_tz = try // CLR on Windows System.TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time") with // Mono  :? System.TimeZoneNotFoundException -> System.TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin")   let get url = ...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Julia
Julia
using Primes   isRhonda(n, b) = prod(digits(n, base=b)) == b * sum([prod(pair) for pair in factor(n).pe])   function displayrhondas(low, high, nshow) for b in filter(!isprime, low:high) n, rhondas = 1, Int[] while length(rhondas) < nshow isRhonda(n, b) && push!(rhondas, n) n ...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[RhondaNumberQ] RhondaNumberQ[b_Integer][n_Integer] := Module[{l, r}, l = Times @@ IntegerDigits[n, b]; r = Total[Catenate[ConstantArray @@@ FactorInteger[n]]]; l == b r ] bases = Select[Range[2, 36], PrimeQ/*Not]; Do[ Print["base ", b, ":", Take[Select[Range[700000], RhondaNumberQ[b]], UpTo[15]]]; , {...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory qw<is_prime factor vecsum vecprod todigitstring todigits>;   sub rhonda { my($b, $cnt) = @_; my(@r,$n); while (++$n) { push @r, $n if ($b * vecsum factor($n)) == vecprod todigits($n,$b); return @r if $cnt == @r; } }   for my $b (gr...
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...
#Pure
Pure
using system;   encode s = strcat $ map (sprintf "%d%s") $ encode $ chars s with encode [] = []; encode xs@(x:_) = (#takewhile (==x) xs,x) : encode (dropwhile (==x) xs); end;   decode s = strcat [c | n,c = parse s; i = 1..n] with parse s::string = regexg item "([0-9]+)(.)" REG_EXTENDED s 0; item info = val (reg...
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...
#Logo
Logo
to rot13 :c make "a difference ascii lowercase :c ascii "a if or :a < 0 :a > 25 [output :c] make "delta ifelse :a < 13 [13] [-13] output char sum :delta ascii :c end   print map "rot13 "|abjurer NOWHERE| nowhere ABJURER
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 ...
#XPL0
XPL0
\Based on C example: include c:\cxpl\stdlib; \provides StrCmp routine, etc. int Haystack; \('int' is used instead of 'char' for 2D array)   func Search(Str, First); \Return first (or last) index for string in haystack char Str; int First; int I, SI; [I:= 0; SI:= 0; repeat if StrCmp(Str, Haystack(...
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 ...
#Yabasic
Yabasic
list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"   dim item$(1)   n = token(list$, item$(), ",")   line input "Enter string to search: " line$ for i = 1 to n if line$ = item$(i) then if not t print "First index for ", line$, ": ", i t = i j = j + 1 ...
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...
#Intercal
Intercal
PLEASE WRITE IN .1 DO READ OUT .1 DO GIVE UP
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...
#Lasso
Lasso
define br => '\r' //decode roman define decodeRoman(roman::string)::integer => { local(ref = array('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)) local(out = integer) while(#roman->size) => { // need to use neset while instead of query expr to utili...
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: ...
#Scala
Scala
object RockPaperScissors extends App { import scala.collection.mutable.LinkedHashMap def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) { val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match { case null => println; return case "" => retur...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" )   func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil }   func grep(n...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Phix
Phix
with javascript_semantics constant fmt = """ First 15 Rhonda numbers in base %d: In base 10:  %s In base %-2d:  %s """ function digit(integer d) return d-iff(d<='9'?'0':'a'-10) end function for base=2 to 36 do if not is_prime(base) then sequence rhondab = {}, -- (base) rhondad = {} -- ...
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...
#PureBasic
PureBasic
Procedure.s RLDecode(toDecode.s) Protected.s repCount, output, currChar, tmp Protected *c.Character = @toDecode   While *c\c <> #Null currChar = Chr(*c\c) Select *c\c Case '0' To '9' repCount + currChar Default If repCount tmp = Space(Val(repCount)) ReplaceS...
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...
#Lua
Lua
function rot13(s) local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" return (s:gsub("%a", function(c) return b:sub(a:find(c)) end)) end
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 ...
#Yorick
Yorick
haystack = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"]; needles = ["Bush", "Washington"]; for(i = 1; i <= numberof(needles); i++) { w = where(haystack == needles(i)); if(!numberof(w)) error, "Needle "+needles(i)+" not found"; write, format="Needle %s appears first ...
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 ...
#zkl
zkl
L("Krusty","Charlie","Bozo","Bozo").index("Charlie") //--> 1 L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error
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...
#Io
Io
Roman := Object clone do ( nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")   numeral := method(number, result := "" for(i, 0, nums size, if(number == 0, break) while(...
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...
#Liberty_BASIC
Liberty BASIC
print "MCMXCIX = "; romanDec( "MCMXCIX") '1999 print "MDCLXVI = "; romanDec( "MDCLXVI") '1666 print "XXV = "; romanDec( "XXV") '25 print "CMLIV = "; romanDec( "CMLIV") '954 print "MMXI = "; romanDec( "MMXI") '2011   end   function romanDec( roman$) arabic =0 lastval =0   for i = len...
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: ...
#Seed7
Seed7
$ include "seed7_05.s7i"; $ include "keybd.s7i";   const array string: rockPaperScissors is [] ("Rock", "Paper", "Scissors");   const proc: main is func local var char: command is ' '; var integer: user is 0; var integer: comp is 0; begin writeln("Hello, Welcome to rock-paper-scissors"); repeat ...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Julia
Julia
using Dates, TimeZones, HTTP, Printf   function geturlbyday(n) d = DateTime(now(tz"Europe/Berlin")) + Day(n) # n should be <= 0 uri = @sprintf("http://tclers.tk/conferences/tcl/%04d-%02d-%02d.tcl", year(d), month(d), day(d)) return uri, String(HTTP.request("GET", uri).body) end   function searchlog...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
matchFrom[url_String, str_String] := Select[StringSplit[Import[url, "String"], "\n"], StringMatchQ[str]] getLogLinks[n_] := Select[Import["http://tclers.tk/conferences/tcl/", "Hyperlinks"], First[ StringCases[#1, "tcl/" ~~ date__ ~~ ".tcl" :> DateDifference[DateObject[URLDecode[date], TimeZone -> "Europe/B...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Raku
Raku
use Prime::Factor;   my @factor-sum;   @factor-sum[1000000] = 42; # Sink a large index to make access thread safe   sub rhonda ($base) { (1..∞).hyper.map: { $_ if $base * (@factor-sum[$_] //= .&prime-factors.sum) == [×] .polymod($base xx *) } }   for (flat 2..16, 17..36).grep: { !.&is-prime } -> $b { put "\nF...
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...
#Python
Python
def encode(input_string): count = 1 prev = None lst = [] for character in input_string: if character != prev: if prev: entry = (prev, count) lst.append(entry) count = 1 prev = character else: count += 1 e...
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...
#Malbolge
Malbolge
  b'BA@?>=<;:9876543210/.-,+*)('&%$#"!Q=+^:('&Y$#m!1So.QOO=v('98$65a`_^]\[ZYXWVUTSRQ#I2MLKJIHGFE DCBA@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I,GF( D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLKJ-++FE ''<A$?>=<;:387xw43s10/(-&m*)('&}$...
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...
#J
J
R1000=. ;L:1 ,{ <@(<;._1);._2]0 :0 C CC CCC CD D DC DCC DCCC CM X XX XXX XL L LX LXX LXXX XC I II III IV V VI VII VIII IX )   rfd=: ('M' $~ <.@%&1000) , R1000 {::~ 1000&|
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#LiveScript
LiveScript
require! 'prelude-ls': {fold, sum}   # String → Number decimal_of_roman = do # [Number, Number] → String → [Number, Number] _convert = ([acc, last_value], ch) -> current_value = { M:1000 D:500 C:100 L:50 X:10 V:5 I:1 }[ch] ? 0 op = if last_value < current_value then (-) else (+) [op(acc, last_value), c...
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: ...
#Sidef
Sidef
const rps = %w(r p s)   const msg = [ "Rock breaks scissors", "Paper covers rock", "Scissors cut paper", ]   say <<"EOT" \n>> Rock Paper Scissors <<\n ** Enter 'r', 'p', or 's' as your play. ** Enter 'q' to exit the game. ** Running score shown as <your wins>:<my wins> EOT   var plays = 0 var aScore = 0 ...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Nim
Nim
import httpclient, os, re, strformat, strutils, sugar, times   const Template = "'http://tclers.tk/conferences/tcl/'yyyy-MM-dd'.tcl'"   proc get(url: string): string = var client = newHttpClient() result = client.getContent(url) if result.match(re"<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>"): result = ...
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Perl
Perl
# 20210316 Perl programming solution   use strict; use warnings; use Time::Piece; use IO::Socket::INET; use HTTP::Tiny; use feature 'say';   my $needle = shift @ARGV // ''; my @haystack = (); my $page = '';   # 10 days before today my $begin = Time::Piece->new - 10 * Time::Piece::ONE_DAY; say " Executed at: ",...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Rust
Rust
// [dependencies] // radix_fmt = "1.0"   fn digit_product(base: u32, mut n: u32) -> u32 { let mut product = 1; while n != 0 { product *= n % base; n /= base; } product }   fn prime_factor_sum(mut n: u32) -> u32 { let mut sum = 0; while (n & 1) == 0 { sum += 2; n >...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Sidef
Sidef
func is_rhonda_number(n, base = 10) { base.is_composite || return false n > 0 || return false n.digits(base).prod == base*n.factor.sum }   for b in (2..16 -> grep { .is_composite }) { say ("First 10 Rhonda numbers to base #{b}: ", 10.by { is_rhonda_number(_, b) }) }
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Swift
Swift
func digitProduct(base: Int, num: Int) -> Int { var product = 1 var n = num while n != 0 { product *= n % base n /= base } return product }   func primeFactorSum(_ num: Int) -> Int { var sum = 0 var n = num while (n & 1) == 0 { sum += 2 n >>= 1 } v...
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...
#Quackery
Quackery
[ lookandsay ] is encode ( $ --> $ )   [ $ "" 0 rot witheach [ dup char 0 char 9 1+ within iff [ char 0 - swap 10 * + ] else [ swap of join 0 ] ] drop ] is decode ( $ --> $ )   $ "WWWWWWWWWWWWBWWWWWWWWWWWW...
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...
#Maple
Maple
> StringTools:-Encode( "The Quick Brown Fox Jumped Over The Lazy Dog!", encoding = rot13 ); "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!"
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...
#Java
Java
public class RN {   enum Numeral { 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); int weight;   Numeral(int weight) { this.weight = weight; } };   public static String roman(long n) {   if( n <= 0) { ...
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...
#Logo
Logo
; Roman numeral decoder   ; First, some useful substring utilities to starts_with? :string :prefix if empty? :prefix [output "true] if empty? :string [output "false] if not equal? first :string first :prefix [output "false] output starts_with? butfirst :string butfirst :prefix end   to remove_prefix :string :pr...
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: ...
#SuperCollider
SuperCollider
// play it in the REPL, evaluating line by line a = RockPaperScissors.new; a.next(Scissors); a.next(Scissors); a.next(Scissors); a.next(Paper);
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Phix
Phix
include builtins\libcurl.e atom curl = NULL function download(string url) if curl=NULL then curl_global_init() curl = curl_easy_init() end if curl_easy_setopt(curl, CURLOPT_URL, url) object res = curl_easy_perform_ex(curl) if integer(res) then printf(1,"libcurl error %d (%s...
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Wren
Wren
import "./math" for Math, Int, Nums import "./fmt" for Fmt, Conv   for (b in 2..36) { if (Int.isPrime(b)) continue var count = 0 var rhonda = [] var n = 1 while (count < 15) { var digits = Int.digits(n, b) if (!digits.contains(0)) { if (b != 10 || (digits.contains(5) && d...
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...
#R
R
runlengthencoding <- function(x) { splitx <- unlist(strsplit(input, "")) rlex <- rle(splitx) paste(with(rlex, as.vector(rbind(lengths, values))), collapse="") }   input <- "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" runlengthencoding(input)