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/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:
... | #Nim | Nim | import random, strutils, tables
type
Choice {.pure.} = enum Rock, Paper, Scissors
History = tuple[total: int; counts: CountTable[Choice]]
const Successor: array[Choice, Choice] = [Paper, Scissors, Rock]
func `>`(a, b: Choice): bool =
## By construction, only the successor is greater than the choice.
a == ... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RunLengthEncode[input_String]:= (l |-> {First@l, Length@l}) /@ (Split@Characters@input) |
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... | #GW-BASIC | GW-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 ... | #Raku | Raku | my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
for <Washington Bush> -> $needle {
say "$needle -- { @haystack.first($needle, :k) // 'not in 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... | #Elena | Elena | import system'collections;
import system'routines;
import extensions;
import extensions'text;
static RomanDictionary = Dictionary.new()
.setAt(1000, "M")
.setAt(900, "CM")
.setAt(500, "D")
.setAt(400, "CD")... |
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... | #F.23 | F# | let decimal_of_roman roman =
let rec convert arabic lastval = function
| head::tail ->
let n = match head with
| 'M' | 'm' -> 1000
| 'D' | 'd' -> 500
| 'C' | 'c' -> 100
| 'L' | 'l' -> 50
| 'X' | '... |
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
| #PicoLisp | PicoLisp | (de findRoots (F Start Stop Step Eps)
(filter
'((N) (> Eps (abs (F N))))
(range Start Stop Step) ) )
(scl 12)
(mapcar round
(findRoots
'((X) (+ (*/ X X X `(* 1.0 1.0)) (*/ -3 X X 1.0) (* 2 X)))
-1.0 3.0 0.0001 0.00000001 ) ) |
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:
... | #NS-HUBASIC | NS-HUBASIC | 10 COMPUTER=RND(3)+1
20 COMPUTER$="ROCK"
30 IF COMPUTER=2 THEN COMPUTER$="PAPER"
40 IF COMPUTER=3 THEN COMPUTER$="SCISSORS"
50 INPUT "ROCK, PAPER OR SCISSORS? ",HUMAN$
60 IF HUMAN$="ROCK" THEN GOTO 100
70 IF HUMAN$="PAPER" THEN GOTO 100
80 IF HUMAN$="SCISSORS" THEN GOTO 100
90 PRINT "INVALID GUESS. TRY AGAIN.": GOTO 50... |
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... | #Maxima | Maxima | rle(a) := block(
[n: slength(a), b: "", c: charat(a, 1), k: 1],
for i from 2 thru n do
if cequal(c, charat(a, i)) then k: k + 1 else (b: sconcat(b, k, c), c: charat(a, i), k: 1),
sconcat(b, k, c)
)$
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW");
"12W1B12W3B24W1B14W" |
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... | #Haskell | Haskell | import Data.Char (chr, isAlpha, ord, toLower)
import Data.Bool (bool)
rot13 :: Char -> Char
rot13 c
| isAlpha c = chr $ bool (-) (+) ('m' >= toLower c) (ord c) 13
| otherwise = c
-- Simple test
main :: IO ()
main = print $ rot13 <$> "Abjurer nowhere" |
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 ... | #REBOL | REBOL | rebol [
Title: "List Indexing"
URL: http://rosettacode.org/wiki/Index_in_a_list
]
locate: func [
"Find the index of a string (needle) in string collection (haystack)."
haystack [series!] "List of values to search."
needle [string!] "String to find in value list."
/largest "Return the largest index if more than ... |
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... | #Elixir | Elixir | defmodule Roman_numeral do
def encode(0), do: ''
def encode(x) when x >= 1000, do: [?M | encode(x - 1000)]
def encode(x) when x >= 100, do: digit(div(x,100), ?C, ?D, ?M) ++ encode(rem(x,100))
def encode(x) when x >= 10, do: digit(div(x,10), ?X, ?L, ?C) ++ encode(rem(x,10))
def encode(x) when x >= 1, do:... |
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... | #Factor | Factor | USE: roman
( scratchpad ) "MMMCCCXXXIII" roman> .
3333 |
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
| #PL.2FI | PL/I |
f: procedure (x) returns (float (18));
declare x float (18);
return (x**3 - 3*x**2 + 2*x );
end f;
declare eps float, (x, y) float (18);
declare dx fixed decimal (15,13);
eps = 1e-12;
do dx = -5.03 to 5 by 0.1;
x = dx;
if sign(f(x)) ^= sign(f(dx+0.1)) then
call locate_root;
end;
locate_root:... |
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:
... | #OCaml | OCaml |
let pf = Printf.printf ;;
let looses a b = match a, b with
`R, `P -> true
| `P, `S -> true
| `S, `R -> true
| _, _ -> false ;;
let rec get_move () =
pf "[R]ock, [P]aper, [S]cisors [Q]uit? " ;
match String.uppercase (read_line ()) with
"P" -> `P
| "S" -> `S
| "R" -> `R
... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #MMIX | MMIX | LOC Data_Segment
GREG @
Buf OCTA 0,0,0,0 integer print buffer
Char BYTE 0,0 single char print buffer
task BYTE "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW"
BYTE "WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",0
len GREG @-1-task
// task should become this
tEnc BYTE "12W1B12W3B24W1B14W",0
GREG @
// tuple array... |
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... | #HicEst | HicEst | CHARACTER c, txt='abc? XYZ!', cod*100
DO i = 1, LEN_TRIM(txt)
c = txt(i)
n = ICHAR(txt(i))
IF( (c >= 'a') * (c <= 'm') + (c >= 'A') * (c <= 'M') ) THEN
c = CHAR( ICHAR(c) + 13 )
ELSEIF( (c >= 'n') * (c <= 'z') + (c >= 'N') * (c <= 'Z') ) THEN
c = CHAR( ICHAR(c) - 13 )
ENDIF
... |
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 ... | #REXX | REXX | /*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.= /*initialize the haystack collection. */
hay.1 = 'sodium'
hay.2 = 'phosphorous'
hay.3 = 'californium'
hay.4 = 'copernicium'
hay.5 = 'gold'
hay.6 = 'thallium'
hay.7 = 'carbo... |
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... | #Emacs_Lisp | Emacs Lisp | (defun ar2ro (AN)
"Translate from arabic number AN to roman number.
For example, (ar2ro 1666) returns (M D C L X V I)."
(cond
((>= AN 1000) (cons 'M (ar2ro (- AN 1000))))
((>= AN 900) (cons 'C (cons 'M (ar2ro (- AN 900)))))
((>= AN 500) (cons 'D (ar2ro (- AN 500))))
((>= AN 400) (cons 'C (cons 'D (ar... |
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... | #FALSE | FALSE | [ 32| {get value of Roman digit on stack}
$'m= $[\% 1000\]? ~[
$'d= $[\% 500\]? ~[
$'c= $[\% 100\]? ~[
$'l= $[\% 50\]? ~[
$'x= $[\% 10\]? ~[
$'v= $[\% 5\]? ~[
$'i= $[\% 1\]? ~[
% 0
]?]?]?]?]?]?]?
]r:
0 {accumulator}
^r;! {read first Roman digit}
[^r;!$][ {read another, and as l... |
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
| #PureBasic | PureBasic | Procedure.d f(x.d)
ProcedureReturn x*x*x-3*x*x+2*x
EndProcedure
Procedure main()
OpenConsole()
Define.d StepSize= 0.001
Define.d Start=-1, stop=3
Define.d value=f(start), x=start
Define.i oldsign=Sign(value)
If value=0
PrintN("Root found at "+StrF(start))
EndIf
While x<=stop
value=f(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:
... | #PARI.2FGP | PARI/GP | contest(rounds)={
my(v=[1,1,1],wins,losses); \\ Laplace rule
for(i=1,rounds,
my(computer,player,t);
t=random(v[1]+v[2]+v[3]);
if(t<v[1], computer = "R",
if(t<v[1]+v[2], computer = "P", computer = "S")
);
print("Rock, paper, or scissors?");
t = Str(input());
if(#t,
player=Vec(... |
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... | #Nim | Nim | import parseutils, strutils
proc compress(input: string): string =
var
count = 1
prev = '\0'
for ch in input:
if ch != prev:
if prev != '\0':
result.add $count & prev
count = 1
prev = ch
else:
inc count
result.add $count & prev
proc uncompress(text: string): 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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
file := open(arglist[1],"r") | &input
every write(rot13(|read(file)))
end
procedure rot13(s) #: returns rot13(string)
static a,n
initial {
a := &lcase || &ucase
(&lcase || &lcase) ? n := ( move(13), move(*&lcase) )
(&ucase || &ucase) ? n ||:= ( move(13), move(*&ucase) )
}
r... |
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 ... | #Ring | Ring |
haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf",
"hotel","india","juliet","kilo","lima","mike","needle",
"november","oscar","papa","quebec","romeo","sierra","tango",
"needle","uniform","victor","whisky","x-ray","yankee","zulu"]
needle = "needle"
maxindex = len(haystack)
for index = 1 to ... |
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 ... | #Ruby | Ruby | haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
%w(Bush Washington).each do |needle|
if (i = haystack.index(needle))
puts "#{i} #{needle}"
else
raise "#{needle} is not in haystack\n"
end
end |
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... | #Erlang | Erlang | -module(roman).
-export([to_roman/1]).
to_roman(0) -> [];
to_roman(X) when X >= 1000 -> [$M | to_roman(X - 1000)];
to_roman(X) when X >= 100 ->
digit(X div 100, $C, $D, $M) ++ to_roman(X rem 100);
to_roman(X) when X >= 10 ->
digit(X div 10, $X, $L, $C) ++ to_roman(X rem 10);
to_roman(X) when X >= 1 -> digit(X... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Forth | Forth | create (arabic)
1000 128 * char M + ,
500 128 * char D + ,
100 128 * char C + ,
50 128 * char L + ,
10 128 * char X + ,
5 128 * char V + ,
1 128 * char I + ,
does>
7 cells bounds do
i @ over over 127 and = if nip 7 rshift leave else drop then
1 cells +loop dup
;
: >arabic
0 dup >r ... |
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
| #Python | Python | f = lambda x: x * x * x - 3 * x * x + 2 * x
step = 0.001 # Smaller step values produce more accurate and precise results
start = -1
stop = 3
sign = f(start) > 0
x = start
while x <= stop:
value = f(x)
if value == 0:
# We hit a root
print "Root found at", x
elif (value > 0) != sign:
... |
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:
... | #Perl | Perl |
use 5.012;
use warnings;
use utf8;
use open qw(:encoding(utf-8) :std);
use Getopt::Long;
package Game {
use List::Util qw(shuffle first);
my $turns = 0;
my %human_choice = ( rock => 0, paper => 0, scissors => 0, );
my %comp_choice = ( rock => 0, paper => 0, scissors => 0, );
my %what_b... |
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... | #Objeck | Objeck | use RegEx;
class RunLengthEncoding {
function : Main(args : String[]) ~ Nil {
input := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
encoded := Encode(input);
"encoding: {$encoded}"->PrintLine();
test := encoded->Equals("12W1B12W3B24W1B14W");
"encoding match: {$test}"-... |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Rot13.bas"
110 DO
120 LINE INPUT PROMPT "Line: ":LINE$
130 PRINT ROT13$(LINE$)
140 LOOP UNTIL LINE$=""
150 DEF ROT13$(TEXT$)
160 LET RESULT$=""
170 FOR I=1 TO LEN(TEXT$)
180 LET CH$=TEXT$(I)
190 SELECT CASE CH$
200 CASE "A" TO "M","a" TO "m"
210 LET CH$=CHR$(ORD(CH$)+13)
220 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 ... | #Run_BASIC | Run BASIC | haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k... |
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... | #ERRE | ERRE |
PROGRAM ARAB2ROMAN
DIM ARABIC%[12],ROMAN$[12]
PROCEDURE TOROMAN(VALUE->ANS$)
LOCAL RESULT$
FOR I%=0 TO 12 DO
WHILE VALUE>=ARABIC%[I%] DO
RESULT$+=ROMAN$[I%]
VALUE-=ARABIC%[I%]
END WHILE
END FOR
ANS$=RESULT$
END PROCEDURE
BEGIN
!
!Testing
!
ARABIC%[]=(1000,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... | #Fortran | Fortran | program Roman_decode
implicit none
write(*,*) decode("MCMXC"), decode("MMVIII"), decode("MDCLXVI")
contains
function decode(roman) result(arabic)
character(*), intent(in) :: roman
integer :: i, n, lastval, arabic
arabic = 0
lastval = 0
do i = len(roman), 1, -1
select case(roman(i:i))
cas... |
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
| #R | R | f <- function(x) x^3 -3*x^2 + 2*x
findroots <- function(f, begin, end, tol = 1e-20, step = 0.001) {
se <- ifelse(sign(f(begin))==0, 1, sign(f(begin)))
x <- begin
while ( x <= end ) {
v <- f(x)
if ( abs(v) < tol ) {
print(sprintf("root at %f", x))
} else if ( ifelse(sign(v)==0, 1, sign(v)) != s... |
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:
... | #Phix | Phix | --standard game
constant rule3 = {"rock blunts scissors",
"paper wraps rock",
"scissors cut paper"}
--extended version
constant rule5 = {"rock blunts scissors",
"rock crushes lizard",
"paper wraps rock",
"paper disproves spock",
... |
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... | #Objective-C | Objective-C | let encode str =
let len = String.length str in
let rec aux i acc =
if i >= len then List.rev acc
else
let c1 = str.[i] in
let rec aux2 j =
if j >= len then (c1, j-i)
else
let c2 = str.[j] in
if c1 = c2
then aux2 (j+1)
else (c1, j-i)
... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #J | J | rot13=: {&((65 97+/~i.2 13) |.@[} i.256)&.(a.&i.) |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #Rust | Rust | fn main() {
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush"));
println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s==... |
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... | #Euphoria | Euphoria | constant arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
function toRoman(integer val)
sequence result
result = ""
for i = 1 to 13 do
while val >= arabic[i] do
result &= roman[i]
... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function romanDecode(roman As Const String) As Integer
If roman = "" Then Return 0 '' zero denotes invalid roman number
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 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
| #Racket | Racket |
#lang racket
;; Attempts to find all roots of a real-valued function f
;; in a given interval [a b] by dividing the interval into N parts
;; and using the root-finding method on each subinterval
;; which proves to contain a root.
(define (find-roots f a b
#:divisions [N 10]
... |
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
| #Raku | Raku | sub f(\x) { x³ - 3*x² + 2*x }
my $start = -1;
my $stop = 3;
my $step = 0.001;
for $start, * + $step ... $stop -> $x {
state $sign = 0;
given f($x) {
my $next = .sign;
when 0.0 {
say "Root found at $x";
}
when $sign and $next != $sign {
say "Root found ... |
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:
... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
0 var wh
0 var wc
( "Scissors cuts Paper"
"Paper covers Rock"
"Rock crushes Lizard"
"Lizard poisons Spock"
"Spock smashes Scissors"
"Scissors decapites Lizard"
"Lizard eats Paper"
"Paper disproves Spock"
"Spock vaporizes Rock"
"Rock blunts Scissors" )
"'Rock, Pa... |
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... | #OCaml | OCaml | let encode str =
let len = String.length str in
let rec aux i acc =
if i >= len then List.rev acc
else
let c1 = str.[i] in
let rec aux2 j =
if j >= len then (c1, j-i)
else
let c2 = str.[j] in
if c1 = c2
then aux2 (j+1)
else (c1, j-i)
... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Java | Java | import java.io.*;
public class Rot13 {
public static void main(String[] args) throws IOException {
if (args.length >= 1) {
for (String file : args) {
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
rot13(in, System.out);
... |
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 ... | #S-lang | S-lang | variable haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","Ronald"];
define find(needle)
{
variable i = where(haystack == needle);
if (length(i)) {
% print(sprintf("%s: first=%d, last=%d", needle, i[0], i[-1]));
return(i[0], i[-1]);
}
else
throw App... |
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... | #Excel | Excel |
=ROMAN(2013,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... | #FutureBasic | FutureBasic | window 1
local fn RomantoDecimal( roman as CFStringRef ) as long
long i, n, preNum = 0, num = 0
for i = len(roman) - 1 to 0 step -1
n = 0
select ( fn StringCharacterAtIndex( roman, i ) )
case _"M" : n = 1000
case _"D" : n = 500
case _"C" : n = 100
case _"L" : n = 50
case _"... |
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
| #REXX | REXX | /*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/
parse arg bot top inc . /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/
if top=='' | top=="," then top= +5 ... |
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:
... | #PHP | PHP |
<?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $pla... |
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... | #Oforth | Oforth | : encode(s)
StringBuffer new
s group apply(#[ tuck size asString << swap first <<c ]) ;
: decode(s)
| c i |
StringBuffer new
0 s forEach: c [
c isDigit ifTrue: [ 10 * c asDigit + continue ]
loop: i [ c <<c ] 0
]
drop ; |
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... | #JavaScript | JavaScript | function rot13(c) {
return c.replace(/([a-m])|([n-z])/ig, function($0,$1,$2) {
return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0;
});
}
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 ... | #Sather | Sather | class MAIN is
main is
haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|;
needles :ARRAY{STR} := | "Washington", "Bush" |;
loop needle ::= needles.elt!;
index ::= haystack.index_of(needle);
if index < 0 then
#OUT + needle + " is not in th... |
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 ... | #Scala | Scala | def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2)
def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head
def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last |
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... | #F.23 | F# | let digit x y z = function
1 -> x
| 2 -> x + x
| 3 -> x + x + x
| 4 -> x + y
| 5 -> y
| 6 -> y + x
| 7 -> y + x + x
| 8 -> y + x + x + x
| 9 -> x + z
| _ -> failwith "invalid call to digit"
let rec to_roman acc = function
| x when x >= 1000 -> to_roman (acc + "M") (x - 1000)
| x when x >... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Gambas | Gambas | 'This code will create a GUI Form and Objects and carry out the Roman Numeral convertion as you type
'The input is case insensitive
'A basic check for invalid charaters is made
hTextBox As TextBox 'To allow the creation of a TextBox
hValueBox As ValueBox ... |
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
| #Ring | Ring |
load "stdlib.ring"
function = "return pow(x,3)-3*pow(x,2)+2*x"
rangemin = -1
rangemax = 3
stepsize = 0.001
accuracy = 0.1
roots(function, rangemin, rangemax, stepsize, accuracy)
func roots funct, min, max, inc, eps
oldsign = 0
for x = min to max step inc
num = sign(eval(funct))
if num = ... |
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:
... | #Picat | Picat | go ?=>
println("\nEnd terms with '.'.\n'quit.' ends the session.\n"),
Prev = findall(P,beats(P,_)),
ChoiceMap = new_map([P=0 : P in Prev]),
ResultMap = new_map([computer_wins=0,user_wins=0,draw=0]),
play(Prev,ChoiceMap,ResultMap),
nl,
println("Summary:"),
println(choiceMap=ChoiceMap),
println(resultMa... |
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:
... | #PicoLisp | PicoLisp | (use (C Mine Your)
(let (Rock 0 Paper 0 Scissors 0)
(loop
(setq Mine
(let N (if (gt0 (+ Rock Paper Scissors)) (rand 1 @) 0)
(seek
'((L) (le0 (dec 'N (caar L))))
'(Rock Paper Scissors .) ) ) )
(prin "Enter R, P or S to play, or Q... |
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... | #Ol | Ol |
(define (RLE str)
(define iter (string->list str))
(let loop ((iter iter) (chr (car iter)) (n 0) (rle '()))
(cond
((null? iter)
(reverse (cons (cons n chr) rle)))
((char=? chr (car iter))
(loop (cdr iter) chr (+ n 1) rle))
(else
(loop (cdr ite... |
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... | #jq | jq | #!/usr/bin/env jq -M -R -r -f
# or perhaps:
#!/usr/local/bin/jq -M -R -r -f
# If your operating system does not allow more than one option
# to be specified on the command line,
# then consider using a version of jq that allows
# command-line options to be squished together (-MRrf),
# or see the following subsection.... |
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 ... | #Scheme | Scheme | (define haystack
'("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
(define index-of
(lambda (needle hackstack)
(let ((tail (member needle haystack)))
(if tail
(- (length haystack) (length tail))
(throw 'needle-missing)))))
(define last-index-of
(lambda (nee... |
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... | #Factor | Factor | USE: roman
( scratchpad ) 3333 >roman .
"mmmcccxxxiii" |
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... | #Go | Go | package main
import (
"errors"
"fmt"
)
var m = map[rune]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
func parseRoman(s string) (r int, err error) {
if s == "" {
return 0, errors.New("Empty string")
}
is := []rune(s) // easier to co... |
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
| #RLaB | RLaB |
f = function(x)
{
rval = x .^ 3 - 3 * x .^ 2 + 2 * x;
return rval;
};
>> findroot(f, , [-5,5])
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:
... | #PL.2FI | PL/I |
rock: procedure options (main); /* 30 October 2013 */
declare move character (1), cm fixed binary;
put ('The Rock-Paper-Scissors game');
put skip list ("please type 'r' for rock, 'p' for paper, 's' for scissors.");
put skip list ("Anything else finishes:");
do forever;
get edit (move) (a(1));... |
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... | #Oz | Oz | declare
fun {RLEncode Xs}
for G in {Group Xs} collect:C do
{C {Length G}#G.1}
end
end
fun {RLDecode Xs}
for C#Y in Xs append:Ap do
{Ap {Replicate Y C}}
end
end
%% Helpers
%% e.g. "1122" -> ["11" "22"]
fun {Group Xs}
case Xs of nil then nil
[] X|Xr then
Ys Zs
{L... |
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... | #Jsish | Jsish | #!/usr/local/bin/jsish
/* ROT-13 in Jsish */
function rot13(msg:string) {
return msg.replace(/([a-m])|([n-z])/ig, function(m,p1,p2,ofs,str) {
return String.fromCharCode(
p1 ? p1.charCodeAt(0) + 13 : p2 ? p2.charCodeAt(0) - 13 : 0) || m;
});
}
provide('rot13', Util.verConvert("1.0"));
/* ro... |
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 ... | #SenseTalk | SenseTalk |
put ("apple", "banana", "cranberry" ,"durian", "eggplant", "grape", "banana", "appl", "blackberry") into fruitList
put findInList(fruitList,"banana") // 2
put findInList(fruitList,"banana", true) // 7
put findInList(fruitList,"tomato") // throws an exception
function findInList paramList, paramItem, findLast
... |
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... | #FALSE | FALSE | ^$." "
[$999>][1000- "M"]#
$899> [ 900-"CM"]?
$499> [ 500- "D"]?
$399> [ 400-"CD"]?
[$ 99>][ 100- "C"]#
$ 89> [ 90-"XC"]?
$ 49> [ 50- "L"]?
$ 39> [ 40-"XL"]?
[$ 9>][ 10- "X"]#
$ 8> [ 9-"IX"]?
$ 4> [ 5- "V"]?
$ 3> [ 4-"IV"]?
[$ ][ 1- "I"]#% |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Golo | Golo | #!/usr/bin/env golosh
----
This module converts a Roman numeral into a decimal number.
----
module Romannumeralsdecode
augment java.lang.Character {
function decode = |this| -> match {
when this == 'I' then 1
when this == 'V' then 5
when this == 'X' then 10
when this == 'L' then 50
when this =... |
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
| #Ruby | Ruby | def sign(x)
x <=> 0
end
def find_roots(f, range, step=0.001)
sign = sign(f[range.begin])
range.step(step) do |x|
value = f[x]
if value == 0
puts "Root found at #{x}"
elsif sign(value) == -sign
puts "Root found between #{x-step} and #{x}"
end
sign = sign(value)
end
end
f = lam... |
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:
... | #Prolog | Prolog | play :-
findall(P,beats(P,_),Prev),
play(Prev).
play(Prev) :-
write('your choice? '),
read(P),
random_member(C, Prev),
format('The computer chose ~p~n', C),
result(C,P,Prev,Next),
!,
play(Next).
result(C,P,R,[C|R]) :-
beats(C,P),
format('Computer wins.~n').
result(C,P,R,[B|R]) :-
beats(P,C),... |
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... | #PARI.2FGP | PARI/GP | rle(s)={
if(s=="", return(s));
my(v=Vec(s),cur=v[1],ct=1,out="");
v=concat(v,99); \\ sentinel
for(i=2,#v,
if(v[i]==cur,
ct++
,
out=Str(out,ct,cur);
cur=v[i];
ct=1
)
);
out
};
elr(s)={
if(s=="", return(s));
my(v=Vec(s),ct=eval(v[1]),out="");
v=concat(v,99); \\ sentin... |
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... | #Julia | Julia |
# Julia 1.0
function rot13(c::Char)
shft = islowercase(c) ? 'a' : 'A'
isletter(c) ? c = shft + (c - shft + 13) % 26 : c
end
rot13(str::AbstractString) = map(rot13, str) |
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 ... | #Sidef | Sidef | var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
%w(Bush Washington).each { |needle|
var i = haystack.first_index{|item| item == needle};
if (i >= 0) {
say "#{i} #{needle}";
} else {
die "#{needle} is not in 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... | #Fan | Fan | **
** converts a number to its roman numeral representation
**
class RomanNumerals
{
private Str digit(Str x, Str y, Str z, Int i)
{
switch (i)
{
case 1: return x
case 2: return x+x
case 3: return x+x+x
case 4: return x+y
case 5: return y
case 6: return y+x
case 7... |
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... | #Groovy | Groovy | enum RomanDigits {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private magnitude;
private RomanDigits(magnitude) { this.magnitude = magnitude }
String toString() { super.toString() + "=${magnitude}" }
static BigInteger parse(String numeral) {
assert numeral != null && !numeral.e... |
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
| #Rust | Rust | // 202100315 Rust programming solution
use roots::find_roots_cubic;
fn main() {
let roots = find_roots_cubic(1f32, -3f32, 2f32, 0f32);
println!("Result : {:?}", roots);
} |
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:
... | #PureBasic | PureBasic | Enumeration
;choices are in listed according to their cycle, weaker followed by stronger
#rock
#paper
#scissors
#numChoices ;this comes after all possible choices
EndEnumeration
;give names to each of the choices
Dim choices.s(#numChoices - 1)
choices(#rock) = "rock"
choices(#paper) = "paper"
choices(#sciss... |
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... | #Pascal | Pascal | Program RunLengthEncoding(output);
procedure encode(s: string; var counts: array of integer; var letters: string);
var
i, j: integer;
begin
j := 0;
letters := '';
if length(s) > 0 then
begin
j := 1;
letters := letters + s[1];
counts[1] := 1;
for i := 2 to length(s) do
... |
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... | #K | K | rot13: {a:+65 97+\:2 13#!26;_ci@[!256;a;:;|a]_ic x}
rot13 "Testing! 1 2 3"
"Grfgvat! 1 2 3" |
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 ... | #Slate | Slate | define: #haystack -> ('Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' splitWith: $,).
{'Washington'. 'Bush'} do: [| :needle |
(haystack indexOf: needle)
ifNil: [inform: word ; ' is not in the haystack']
ifNotNilDo: [| :firstIndex lastIndex |
inform: word ; ' is in the haystack at index ' ; firstInd... |
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... | #Forth | Forth | : vector create ( n -- ) 0 do , loop does> ( n -- ) swap cells + @ execute ;
\ these are ( numerals -- numerals )
: ,I dup c@ C, ; : ,V dup 1 + c@ C, ; : ,X dup 2 + c@ C, ;
\ these are ( numerals -- )
:noname ,I ,X drop ; :noname ,V ,I ,I ,I drop ; :noname ,V ,I ,I drop ;
:noname ,V ,I dr... |
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... | #Haskell | Haskell |
module Main where
------------------------
-- DECODER FUNCTION --
------------------------
decodeDigit :: Char -> Int
decodeDigit 'I' = 1
decodeDigit 'V' = 5
decodeDigit 'X' = 10
decodeDigit 'L' = 50
decodeDigit 'C' = 100
decodeDigit 'D' = 500
decodeDigit 'M' = 1000
decodeDigit _ = error "invalid digit"
-- W... |
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
| #Scala | Scala | object Roots extends App {
val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x
private def printRoots(f: Double => Double,
lowerBound: Double,
upperBound: Double,
step: Double): Unit = {
val y = f(lowerBound)
var (ox, oy, os) =... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Python | Python | from random import choice
rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
previous = ['rock', 'paper', 'scissors']
while True:
human = input('\nchoose your weapon: ')
computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous"
if huma... |
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... | #Perl | Perl | sub encode {
shift =~ s/(.)\1*/length($&).$1/grse;
}
sub decode {
shift =~ s/(\d+)(.)/$2 x $1/grse;
} |
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... | #Kotlin | Kotlin | import java.io.*
fun String.rot13() = map {
when {
it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x }
it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x }
else -> it
} }.toCharArray()
fun InputStreamReader.println() =
try { BufferedReader(this)... |
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 ... | #Smalltalk | Smalltalk | | haystack |
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
{ 'Washington' . 'Bush' } do: [:word |
|t|
((t := haystack indexOf: word) = 0)
ifTrue: [ ('%1 is not in the haystack' % { word }) displayNl ]
ifFalse: [
|l|
('%1 is at ... |
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... | #Fortran | Fortran | program roman_numerals
implicit none
write (*, '(a)') roman (2009)
write (*, '(a)') roman (1666)
write (*, '(a)') roman (3888)
contains
function roman (n) result (r)
implicit none
integer, intent (in) :: n
integer, parameter :: d_max = 13
integer :: d
integer :: m... |
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... | #Icon_and_Unicon | Icon and Unicon | link numbers
procedure main()
every R := "MCMXC"|"MDCLXVI"|"MMVIII" do
write(R, " = ",unroman(R))
end |
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
| #Sidef | Sidef | func f(x) {
x*x*x - 3*x*x + 2*x
}
var step = 0.001
var start = -1
var stop = 3
for x in range(start+step, stop, step) {
static sign = false
given (var value = f(x)) {
when (0) {
say "Root found at #{x}"
}
case (sign && ((value > 0) != sign)) {
say "Root fo... |
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:
... | #R | R | play <- function()
{
bias <- c(r = 1, p = 1, s = 1)
repeat
{
playerChoice <- readline(prompt = "Rock (r), Paper (p), Scissors (s), or Quit (q)? ")
if(playerChoice == "q") break
rps <- c(Rock = "r", Paper = "p", Scissors = "s")
if(!playerChoice %in% rps) next
compChoice <- sample(rps, 1, prob =... |
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... | #Phix | Phix | with javascript_semantics
function encode(string s)
sequence r = {}
if length(s) then
integer ch = s[1],
count = 1
for i=2 to length(s) do
if s[i]!=ch then
r &= {count,ch}
ch = s[i]
count = 1
else
... |
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... | #Ksh | Ksh |
#!/bin/ksh
# rot-13 function
# # Variables:
#
integer ROT_NUM=13 # Generalize to any ROT
string1="A2p" # Default "test"
string=${1:-${string1}} # Allow command line input
typeset -a lcalph=( a b c d e f g h i j k l m n o p q r s t u v w x y z )
typeset -a ucalph=( A B C D E F G H I J K L M N O P Q R S T... |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #Standard_ML | Standard ML | fun find_index (pred, lst) = let
fun loop (n, []) = NONE
| loop (n, x::xs) = if pred x then SOME n
else loop (n+1, xs)
in
loop (0, lst)
end;
val haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
app (fn needle =>
case find_index (f... |
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 ... | #Swift | Swift | let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
for needle in ["Washington","Bush"] {
if let index = haystack.indexOf(needle) {
print("\(index) \(needle)")
} else {
print("\(needle) is not in haystack")
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.