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/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#jq
jq
# To produce a stream: def addsub(x; y): (x + y), (x - y);   # To produce an array: def add_subtract(x; y): [ x+y, x-y ];  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Julia
Julia
function addsub(x, y) return x + y, x - y end
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.2B.2B
C++
#include <set> #include <iostream> using namespace std;   int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4};   TySet unique_set(data, data + 6);   cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *ite...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#FreeBASIC
FreeBASIC
' version 26-01-2019 ' compile with: fbc -s console   Dim As UByte used() Dim As Integer sum, temp Dim As UInteger n, max, count, i   max = 1000 : ReDim used(max)   Print "The first 15 terms are 0";   For n = 0 To 14 temp = sum - n If temp < 1 OrElse used(temp) = 1 Then temp = sum + n End If If ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#BASIC256
BASIC256
arraybase 1 global matrix dim matrix = {{1, 2, -1, -4}, {2, 3, -1, -11}, { -2, 0, -3, 22}}   call RREF (matrix)   for row = 1 to 3 for col = 1 to 4 if matrix[row, col] = 0 then print "0"; chr(9); else print matrix[row, col]; chr(9); end if next print next end ...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Axe
Axe
√(X)
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#BASIC
BASIC
ABS(x) 'absolute value SQR(x) 'square root EXP(x) 'exponential LOG(x) 'natural logarithm x ^ y 'power 'floor, ceiling, e, and pi not available
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#F.23
F#
open System open System.IO   let cutOut (arr : 'a[]) from n = // confine syntax highlighting confusion' let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None ((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)   [<EntryPoint>] let main argv = let nums = Ar...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#C
C
#include <stdio.h> #include <stdlib.h>   int main() { char *buffer; FILE *fh = fopen("readentirefile.c", "rb"); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); // we can now clos...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Haskell
Haskell
import Data.List (inits, maximumBy) import Data.Maybe (fromMaybe)   repstring :: String -> Maybe String -- empty strings are not rep strings repstring [] = Nothing -- strings with only one character are not rep strings repstring [_] = Nothing repstring xs | any (`notElem` "01") xs = Nothing | otherwise = longest xs...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Inform_7
Inform 7
let T be indexed text; let T be "A simple string"; if T matches the regular expression ".*string$", say "ends with string."; replace the regular expression "simple" in T with "replacement";
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#J
J
load'regex' NB. Load regex library str =: 'I am a string' NB. String used in examples.
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Befunge
Befunge
55+~>:48>*#8\#4`#:!#<#~_$>:#,_@
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#PARI.2FGP
PARI/GP
repeat(f, n)=for(i=1,n,f()); repeat( ()->print("Hi!"), 2);
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Pascal
Pascal
program Repeater;   type TProc = procedure(I: Integer);   procedure P(I: Integer); begin WriteLn('Iteration ', I); end;   procedure Iterate(P: TProc; N: Integer); var I: Integer; begin for I := 1 to N do P(I); end;   begin Iterate(P, 3); end.
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Liberty_BASIC
Liberty BASIC
' LB has inbuilt 'name' command, but can also run batch files   nomainwin   name "input.txt" as "output.txt" run "cmd.exe /c ren docs mydocs", HIDE name "C:\input.txt" as "C:\output.txt" run "cmd.exe /c ren C:\docs mydocs", HIDE   end
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#LiveCode
LiveCode
rename file "input.txt" to "output.txt" rename folder "docs" to "mydocs" rename file "/input.txt" to "/output.txt" rename folder "/docs" to "/mydocs"
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Ksh
Ksh
  #!/bin/ksh   # Reverse words in a string   # # Variables: # typeset -a wArr integer i     ###### # main # ######   while read -A wArr; do for ((i=${#wArr[@]}-1; i>=0; i--)); do printf "%s " "${wArr[i]}" done echo done << EOF ---------- Ice and Fire ------------   fire, in end will world the say Some ice. in sa...
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...
#REXX
REXX
/*REXX program encodes several example text strings using the ROT-13 algorithm. */ $='foo'  ; say "simple text=" $; say 'rot-13 text=' rot13($); say $='bar'  ; say "simple text=" $; say 'rot-13 text=' rot13($); say $="Noyr jnf V, 'rer V fnj Ryon."; say "simple t...
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...
#Racket
Racket
#lang racket (define (encode/roman number) (cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000)))) ((>= number 900) (string-append "CM" (encode/roman (- number 900)))) ((>= number 500) (string-append "D" (encode/roman (- number 500)))) ((>= number 400) (string-append "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...
#Tcl
Tcl
proc fromRoman rnum { set map {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+} expr [string map $map $rnum]0} }
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#DWScript
DWScript
  PrintLn( StringOfString('abc',5) );  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Kotlin
Kotlin
// version 1.0.6   /* implicitly returns a Pair<Int, Int>*/ fun minmax(ia: IntArray) = ia.min() to ia.max()   fun main(args: Array<String>) { val ia = intArrayOf(17, 88, 9, 33, 4, 987, -10, 2) val(min, max) = minmax(ia) // destructuring declaration println("The smallest number is $min") println("The lar...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Lambdatalk
Lambdatalk
  {def foo {lambda {:n} {cons {- :n 1} {+ :n 1}}}} // two values -> foo   {foo 10} -> (9 11)   {def bar {lambda {:n} {A.new {- :n 1} :n {+ :n 1} }}} // three values and more -> bar   {bar 10} -> [9,10,11]  
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#CafeOBJ
CafeOBJ
  -- The parametrized module NO-DUP-LIST(ELEMENTS :: TRIV) defines the signature of simple Haskell like list structure. -- The removal of duplicates is handled by the equational properties listed after the signature in brackets {} -- The binary operation _,_ is associative, commutative, and idempotent. -- This list str...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#FOCAL
FOCAL
01.10 T "FIRST 15" 01.20 F N=0,14;D 2;T %2,A(N) 01.30 T !"FIRST REPEATED" 01.40 D 2;S Y=1 01.50 F M=0,N-1;S Y=Y*(A(M)-A(N)) 01.60 I (Y)1.7,1.8,1.7 01.70 S N=N+1;G 1.4 01.80 T A(N)," AT A(",N,")"! 01.90 Q   02.05 I (N)2.1,2.06,2.1 02.06 A(0)=0;R 02.10 S X=A(N-1)-N 02.20 I (X)2.7 02.30 S Y=1 02.40 F M=0,N-1;S Y=Y*(A(M)-X...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || use...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#BBC_BASIC
BBC BASIC
DIM matrix(2,3) matrix() = 1, 2, -1, -4, \ \ 2, 3, -1, -11, \ \ -2, 0, -3, 22 PROCrref(matrix()) FOR row% = 0 TO 2 FOR col% = 0 TO 3 PRINT matrix(row%,col%); NEXT PRINT NEXT row% END   DEF PROCrref(m()) LOCAL ...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#BASIC256
BASIC256
e = exp(1) # e not available print "e = "; e print "PI = "; PI   x = 12.345 y = 1.23   print "sqrt = "; sqr(x) # square root print "ln = "; log(e) # natural logarithm base e print "log10 = "; log10(e) # base 10 logarithm print "log = "; log(x)/log(y) # arbitrar...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Fortran
Fortran
  SUBROUTINE CROAK(GASP) !Something bad has happened. CHARACTER*(*) GASP !As noted. WRITE (6,*) "Oh dear. ",GASP !So, gasp away. STOP "++ungood." !Farewell, cruel world. END !No return from this.   SUBROUTINE FILEHACK(FNAME,IST,N) CHARACTER*(*) FNAME !Name for the file....
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#C.23
C#
using System.IO;   class Program { static void Main(string[] args) { var fileContents = File.ReadAllText("c:\\autoexec.bat"); // Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8) } }
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string> #include <iterator>   int main( ) { if (std::ifstream infile("sample.txt")) { // construct string from iterator range std::string fileData(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>());   cout << "File ...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every write(s := !A,": ",(repString(s) | "Not a rep string!")\1) end   procedure repString(s) rs := s[1+:*s/2] while (*rs > 0) & (s ~== lrepl(rs,*s,rs)) do rs := rs[1:-1] return (*rs > 0, rs) end   procedure lrepl(s1,n,s2) # The standard left() procedure won't work. while *s1 < n ...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Java
Java
String str = "I am a string"; if (str.matches(".*string")) { // note: matches() tests if the entire string is a match System.out.println("ends with 'string'"); }
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#JavaScript
JavaScript
var subject = "Hello world!";   // Two different ways to create the RegExp object // Both examples use the exact same pattern... matching "hello " var re_PatternToMatch = /Hello (World)/i; // creates a RegExp literal with case-insensitivity var re_PatternToMatch2 = new RegExp("Hello (World)", "i");   // Test for a matc...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#BQN
BQN
⌽"racecar" "racecar"
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Perl
Perl
sub repeat { my ($sub, $n) = @_; $sub->() for 1..$n; }   sub example { print "Example\n"; }   repeat(\&example, 4);
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Phix
Phix
procedure Repeat(integer rid, integer n) for i=1 to n do rid() end for end procedure procedure Hello() ?"Hello" end procedure Repeat(Hello,5)
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Locomotive_Basic
Locomotive Basic
|ren,"input.txt","output.txt"
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Lua
Lua
os.rename( "input.txt", "output.txt" ) os.rename( "/input.txt", "/output.txt" ) os.rename( "docs", "mydocs" ) os.rename( "/docs", "/mydocs" )
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Lambdatalk
Lambdatalk
  1) We write a function   {def line_reverse {def line_reverse.r {lambda {:i :txt :length} {if {> :i :length} then else {br}{A2S {A.reverse! {A.get :i :txt}}} {line_reverse.r {+ :i 1} :txt :length}}}} {lambda {:txt} {let { {:a {line_split {:txt}}} } {line_reverse.r 0 :a {- {A.length :a} 1}}...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Ring
Ring
  see "enter a string : " give s ans = "" for a = 1 to len(s) letter = substr(s, a, 1) if letter >= "a" and letter <= "z" char = char(ascii(letter) + 13) if char > "z" char = chr(asc(char) - 26) ok else if letter >= "a" and letter <= "z" char = char(ascii(letter) + 13) ok if c...
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...
#Raku
Raku
my %symbols = 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", 500 => "D", 1_000 => "M";   my @subtractors = 1_000, 100, 500, 100, 100, 10, 50, 10, 10, 1, 5, 1, 1, 0;   multi sub roman (0) { '' } multi sub roman (Int $n) { for @subtractors -> $cut, $minus { $n >= $cut and ...
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...
#TechBASIC
TechBASIC
    Main: !------------------------------------------------ ! CALLS THE romToDec FUNCTION WITH THE ROMAN ! NUMERALS AND RETURNS ITS DECIMAL EQUIVELENT. !   PRINT "MCMXC = "; romToDec("MCMXC")  !1990 PRINT "MMVIII = "; romToDec("MMVIII")  !2008 PRINT "MDCLXVI = "; romToDec("MDCLXVI") !1666 PRINT:PRINT ...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Dyalect
Dyalect
String.Repeat("ha", 5)
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. concat( rep 5 "ha" )
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Lasso
Lasso
define multi_value() => { return (:'hello word',date) } // shows that single method call will return multiple values // the two values returned are assigned in order to the vars x and y local(x,y) = multi_value   'x: '+#x '\ry: '+#y
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Liberty_BASIC
Liberty BASIC
data$ ="5 6 7 22 9 3 4 8 7 6 3 -5 2 1 8 9"   a$ =minMax$( data$) print " Minimum was "; word$( a$, 1, " "); " & maximum was "; word$( a$, 2, " ")   end   function minMax$( i$) min = 1E6 max =-1E6 i =1 do t$ =word$( i$, i, " ") if t$ ="" then exit do v =val( t$) min =min( min, v) max =max(...
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ceylon
Ceylon
<String|Integer>[] data = [1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"]; <String|Integer>[] unique = HashSet { *data }.sequence();
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Go
Go
package main   import "fmt"   func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || use...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#C
C
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ))   #define EL_Type int   typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix;   typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec;   Matrix NewMatrix( int x_dim, int y_dim...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#bc
bc
scale = 6 sqrt(2) /* 1.414213 square root */ 4.3 ^ -2 /* .054083 power (integer exponent) */
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#blz
blz
{e}
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub removeLines(fileName As String, startLine As UInteger, numLines As UInteger) If startLine = 0 Then Print "Starting line must be more than zero" Return End If If numLines = 0 Then Print "No lines to remove" Return End If Dim fileNum As Integer = FreeFile Open fileNam...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Clojure
Clojure
(slurp "myfile.txt") (slurp "my-utf8-file.txt" "UTF-8")
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#J
J
replengths=: >:@i.@<.@-:@# rep=: $@] $ $   isRepStr=: +./@((] -: rep)"0 1~ replengths)
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Java
Java
public class RepString {   static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"};   public static void main(String[] args) { for (String s : input) System.out.printf("%s...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#jq
jq
"I am a string" | test("string$")
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Bracmat
Bracmat
( reverse = L x .  :?L & @( !arg  :  ? ( %?x & utf$!x & !x !L:?L & ~` )  ? ) | str$!L ) & out$reverse$Ελληνικά
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Phixmonti
Phixmonti
def myFunc "Sure looks like a function in here..." print nl enddef   def rep /# func times -- #/ for drop dup exec endfor drop enddef   getid myFunc 4 rep  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#PicoLisp
PicoLisp
# The built-in function "do" can be used to achieve our goal, # however, it has a slightly different syntax than what the # problem specifies.   # Native solution. (do 10 (version))   # Our solution. (de dofn (Fn N) (do N (Fn)) )   (dofn version 10)
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#M2000_Interpreter
M2000 Interpreter
  Module checkit { Document A$={Alfa, beta} Save.Doc A$, "this.aaa" Print Exist("this.aaa")=true dos "cd "+quote$(dir$)+" && del this.bbb", 100; ' using; to close dos window, and 100ms for waiting Name this.aaa as this.bbb Rem : Name "this.aaa" as "this.bbb" ' we can use strings or...
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Maple
Maple
use FileTools in Rename( "input.txt", "output.txt" ); Rename( "docs", "mydocs" ); Rename( "/input.txt", "/output.txt" ); # assuming permissions in / Rename( "/docs", "/mydocs" ) # assuming permissions in / end use:
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Liberty_BASIC
Liberty BASIC
  for i = 1 to 10 read string$ print reverse$(string$) next end   function reverse$(string$) token$="*" while token$<>"" i=i+1 token$ = word$(string$, i) output$=token$+" "+output$ wend reverse$ = trim$(output$) end function   data "---------- Ice and Fire ------------" d...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Ruby
Ruby
# Returns a copy of _s_ with rot13 encoding. def rot13(s) s.tr('A-Za-z', 'N-ZA-Mn-za-m') end   # Perform rot13 on files from command line, or standard input. while line = ARGF.gets print rot13(line) 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...
#Red
Red
  table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]   to-Roman: function [n [integer!] return: [string!]][ out: copy "" foreach [a r] table [while [n >= a][append out r n: n - a]] out ]   foreach number [40 33 1888 2016][print [number ":" to-Roman number]]  
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#TI-83_BASIC
TI-83 BASIC
PROGRAM:ROM2DEC :Input Str1 :Disp real(21,Str1)
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#E
E
"ha" * 5
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#ECL
ECL
IMPORT STD; //Imports the Standard Library   STRING MyBaseString := 'abc'; RepeatedString := STD.Str.Repeat(MyBaseString,3); RepeatedString; //returns 'abcabcabc'
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Lily
Lily
define combine(a: Integer, b: String): Tuple[Integer, String] { return <[a, b]> }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Lua
Lua
function addsub( a, b ) return a+b, a-b end   s, d = addsub( 7, 5 ) print( s, d )
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
user=> (distinct [1 3 2 9 1 2 3 8 8 1 0 2]) (1 3 2 9 8 0) user=>
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Haskell
Haskell
recaman :: Int -> [Int] recaman n = fst <$> reverse (go n) where go 0 = [] go 1 = [(0, 1)] go x = let xs@((r, i):_) = go (pred x) back = r - i in ( if 0 < back && not (any ((back ==) . fst) xs) then back else r + i , succ i) : ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#C.23
C#
using System;   namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } ...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Bracmat
Bracmat
x \D (10^x) { \D is the differentiation operator }
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#C
C
#include <math.h>   M_E; /* e - not standard but offered by most implementations */ M_PI; /* pi - not standard but offered by most implementations */ sqrt(x); /* square root--cube root also available in C99 (cbrt) */ log(x); /* natural logarithm--log base 10 also available (log10) */ exp(x); /* exponential */ abs(x); /...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Frink
Frink
removeLines[filename, start, len] := { lines = array[lines[filenameToURL[filename]]] modified = lines.removeLen[start-1, len] if modified != len println["Was only able to remove $modified lines due to end-of-file."]   w = new Writer[filename] for line = lines w.println[line] w.close[] }
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Gambas
Gambas
sNewFile As String 'Global string for the 'New file' details   Public Sub Main() Dim sFileName As String = User.Home &/ "foobar.txt" 'File name   sNewFile = DeleteLines(sFileName, 1, 2) ...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#CMake
CMake
file(READ /etc/passwd string)
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Common_Lisp
Common Lisp
(defun file-string (path) (with-open-file (stream path) (let ((data (make-string (file-length stream)))) (read-sequence data stream) data)))
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => {   // REP-CYCLES -------------------------------------   // repCycles :: String -> [String] const repCycles = s => { const n = s.length; return filter( x => s === take(n, cycle(x)).join(''), ...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Jsish
Jsish
/* Regular expressions, in Jsish */   var re = /s[ai]mple/; var sentence = 'This is a sample sentence';   var matches = sentence.match(re); if (matches.length > 0) printf('%s found in "%s" using %q\n', matches[0], sentence, re);   var replaced = sentence.replace(re, "different"); printf("replaced sentence is: %s\n", re...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Julia
Julia
s = "I am a string" if ismatch(r"string$", s) println("'$s' ends with 'string'") end
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Brainf.2A.2A.2A
Brainf***
[-]>,[>,]<[.<]
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#PowerShell
PowerShell
  function Out-Example { "Example" }   function Step-Function ([string]$Function, [int]$Repeat) { for ($i = 1; $i -le $Repeat; $i++) { "$(Invoke-Expression -Command $Function) $i" } }   Step-Function Out-Example -Repeat 3  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Prolog
Prolog
repeat(_, 0). repeat(Callable, Times) :- succ(TimesLess1, Times), Callable, repeat(Callable, TimesLess1).   test :- write('Hello, World'), nl. test(Name) :- format('Hello, ~w~n', Name).
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SetDirectory[NotebookDirectory[]] RenameFile["input.txt", "output.txt"] RenameDirectory["docs", "mydocs"] SetDirectory[$RootDirectory] RenameFile["input.txt", "output.txt"] RenameDirectory["docs", "mydocs"]
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#MATLAB_.2F_Octave
MATLAB / Octave
[STATUS, MSG, MSGID] = movefile (F1, F2);
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#LiveCode
LiveCode
repeat for each line txtln in fld "Fieldtxt" repeat with i = the number of words of txtln down to 1 put word i of txtln & space after txtrev end repeat put cr after txtrev -- preserve line end repeat put txtrev
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#LiveScript
LiveScript
  poem = """ ---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert ----------------------- """   reverse-words = (.split ' ') >> (...
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...
#Run_BASIC
Run BASIC
INPUT "Enter a string: "; s$ ans$ = "" FOR a = 1 TO LEN(s$) letter$ = MID$(s$, a, 1) IF letter$ >= "A" AND letter$ <= "Z" THEN char$ = CHR$(ASC(letter$) + 13) IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) else if letter$ >= "a" AND letter$ <= "z" THEN cha...
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...
#Retro
Retro
  : vector ( ...n"- ) here [ &, times ] dip : .data ` swap ` + ` @ ` do ` ; ; : .I dup @ ^buffer'add ; : .V dup 1 + @ ^buffer'add ; : .X dup 2 + @ ^buffer'add ;   [ .I .X drop ] [ .V .I .I .I drop ] [ .V .I .I drop ] [ .V .I drop ] [ .V drop ] [ .I .V drop ] [ .I .I .I drop ] [...
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...
#TMG
TMG
loop: parse(roman)\loop; roman: string(!<<MDCLXVI>>) [n=0] num letter: num/render letter; num: <M> [n=+1750] | <D> [n=+764] | <C> ( <M> [n=+1604] | <D> [n=+620] | [n=+144] ) | <L> [n=+62] | <X> ( <C> [n=+132] | <L> [n=+50] | [n=+12] ) | <V> [n=+5] | <I...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Egison
Egison
  (S.concat (take 5 (repeat1 "ha")))  
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Eiffel
Eiffel
  repeat_string(a_string: STRING; times: INTEGER): STRING require times_positive: times > 0 do Result := a_string.multiply(times) end  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Maple
Maple
> sumprod := ( a, b ) -> (a + b, a * b): > sumprod( x, y ); x + y, x y   > sumprod( 2, 3 ); 5, 6
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
addsub [x_,y_]:= List [x+y,x-y] addsub[4,2]
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#CoffeeScript
CoffeeScript
data = [ 1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d" ] set = [] set.push i for i in data when not (i in set)   console.log data console.log set
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#J
J
positive =: >&0 unique =: -.@:e. condition =: (positive@:] *. unique~) ({: - #) NB. with the agenda set by the condition, add or subtract tail with tally recaman_term =: ({: + #)`({: - #)@.condition NB. generate four hundred thousand terms and display the first 15 15 {. R=:(, recaman_term)^:4000...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Java
Java
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;   public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0);   Set<Integer> used = new HashSet<>(); used.add(0);   Se...