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/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... | #ActionScript | ActionScript | function repeatString(string:String, numTimes:uint):String
{
var output:String = "";
for(var i:uint = 0; i < numTimes; i++)
output += string;
return output;
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #AutoIt | AutoIt |
Func _AddSub($iX, $iY)
Local $aReturn[2]
$aReturn[0] = $iX + $iY
$aReturn[1] = $iX - $iY
Return $aReturn
EndFunc
|
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.
| #11l | 11l | F repeat(f, n)
L 1..n
f()
F procedure()
print(‘Example’)
repeat(procedure, 3) |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #PicoLisp | PicoLisp | (de *R160-R1 . (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
8 5 14 2 11 7 16 4 13 1 10 6 3 15 12 9
4 11 15 5 10 16 9 2 3 8 1 7 14 12 6 13
2 10 12 11 1 9 13 5 14 4 8 16 15 6 7 3
5 1 6 10 8 13 3 11 15 2 4 9 12 7 16 14 .))
(de *R160-R2 . (6 15 8 1 10 3 12 5 14 7 16 9 ... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #PowerShell | PowerShell |
function Get-Hash
{
[CmdletBinding(DefaultParameterSetName="String")]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName="String",
Position=0)]
[string]
$String,
[Parameter(Mandatory=$true,
... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Go | Go | package main
import "fmt"
const (
S = 10
)
type node struct {
v float64
fixed int
}
func alloc2(w, h int) [][]node {
a := make([][]node, h)
for i := range a {
a[i] = make([]node, w)
}
return a
}
func set_boundary(m [][]node) {
m[1][1].fixed = 1
m[1][1].v = 1
m[6][7].fixed = -1
m[6][7].v = -... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Oforth | Oforth | 1 first
[1:interpreter] ExRuntime : 1 does not understand method <#first> |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #ooRexx | ooRexx | u = .unknown~new
u~foo(1, 2, 3)
::class unknown
::method unknown
use arg name, args
say "Unknown method" name "invoked with arguments:" args~tostring('l',', ') |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Oz | Oz | declare
class Example
meth init skip end
meth foo {System.showInfo foo} end
meth bar {System.showInfo bar} end
meth otherwise(Msg)
{System.showInfo "Unknown method "#{Label Msg}}
if {Width Msg} > 0 then
{System.printInfo "Arguments: "}
{System.show {Rec... |
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... | #BBC_BASIC | BBC BASIC | PRINT FNreverse("---------- Ice and Fire ------------")\
\ 'FNreverse("")\
\ 'FNreverse("fire, in end will world the say Some")\
\ 'FNreverse("ice. in say Some")\
\ 'FNreverse("desire of tasted I've what From")\
\ 'FNreverse("fire. favor who those with hold 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... | #Oforth | Oforth | : encryptRot13(c)
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c 13 + over - 26 mod + ;
: rot13 map(#encryptRot13) charsAsString ; |
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... | #Modula-2 | Modula-2 |
MODULE RomanNumeralsEncode;
FROM Strings IMPORT
Append;
FROM STextIO IMPORT
WriteString, WriteLn;
CONST
MaxChars = 15;
(* 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
with these symbols. *)
TYPE
TRomanNumeral = ARRAY [0 .. MaxChars - 1] OF CHAR;
PROCEDURE ToRoman(AV... |
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... | #PL.2FI | PL/I |
test_decode: procedure options (main); /* 28 January 2013 */
declare roman character (20) varying;
do roman = 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'iix',
'ix', 'x', 'xi', 'xiv', 'MCMLXIV', 'MCMXC', 'MDCLXVI',
'MIM', 'MM', 'MMXIII';
put skip list (roman, decode(ro... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #TMG | TMG | loop: ordcop [lch?]\loop;
ordcop: ord/copy;
ord: char(ch)/last [ch!=lch?]\new [cnt++] fail;
new: ( [lch?] parse(out) | () ) [lch=ch] [cnt=1] fail;
out: decimal(cnt) scopy = { 2 1 };
last: parse(out) [lch=0];
copy: smark any(!<<>>);
ch: 0;
lch: 0;
cnt: 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... | #Ada | Ada | with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure String_Multiplication is
begin
Put_Line (5 * "ha");
end String_Multiplication; |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #BASIC | BASIC | ' Return multiple values
RECORD multi
LOCAL num
LOCAL s$[2]
END RECORD
FUNCTION f(n) TYPE multi_type
LOCAL r = { 0 } TYPE multi_type
r.num = n
r.s$[0] = "Hitchhiker's Guide"
r.s$[1] = "Douglas Adams"
RETURN r
END FUNCTION
DECLARE rec TYPE multi_type
rec = f(42)
PRINT rec.num
PRINT rec.s$... |
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.
| #6502_Assembly | 6502 Assembly | macro RepeatProc,addr,count ;VASM macro syntax
; input:
; addr = the label of the routine you wish to call repeatedly
; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times.
lda #<\addr
sta z_L ;a label for a zero-page memory address
lda #>\addr
sta z_... |
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.
| #68000_Assembly | 68000 Assembly | lea foo,a5 ;function to execute
move.w #4-1,d7 ;times to repeat
jsr Repeater
jmp * ;halt the CPU, we're done
repeater:
jsr repeaterhelper ;this also need to be a call, so that the RTS of the desired procedure
;returns us to the loop rather than... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Python | Python | Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import hashlib
>>> h = hashlib.new('ripemd160')
>>> h.update(b"Rosetta Code")
>>> h.hexdigest()
'b3be159860842cebaa7174c8fff0aa9e50a5199f'
>>> |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Racket | Racket |
#lang racket
(require (planet soegaard/digest:1:2/digest))
(ripemd160 #"Rosetta Code")
|
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Haskell | Haskell | {-# LANGUAGE ParallelListComp #-}
import Numeric.LinearAlgebra (linearSolve, toDense, (!), flatten)
import Data.Monoid ((<>), Sum(..))
rMesh n (ar, ac) (br, bc)
| n < 2 = Nothing
| any (\x -> x < 1 || x > n) [ar, ac, br, bc] = Nothing
| otherwise = between a b <$> voltage
where
a = (ac - 1) + n*(ar - 1)
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Perl | Perl | package Example;
sub new {
bless {}
}
sub foo {
print "this is foo\n";
}
sub bar {
print "this is bar\n";
}
sub AUTOLOAD {
my $name = $Example::AUTOLOAD;
my ($self, @args) = @_;
print "tried to handle unknown method $name\n";
if (@args) {
print "it had arguments: @args\n";
}
}
su... |
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... | #Bracmat | Bracmat | ("---------- 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 -----------------------"
: ?text
& ( reverse
= token tokens reversed
... |
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... | #Ol | Ol | (import (scheme char))
(define (rot13 str)
(runes->string (map (lambda (ch)
(+ ch (cond
((char-ci<=? #\a ch #\m)
13)
((char-ci<=? #\n ch #\z)
-13)
(else 0))))
(string->runes str))))
(define str "`What a... |
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... | #MUMPS | MUMPS | TOROMAN(INPUT)
;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
;OUTPUT is the string to return
;I is a loop variable
;CURRVAL is the current value in the loop
QUIT:($FIND(INPUT,".")>1)!(INPUT<=0)!(INPUT>3999) "Invalid input"
NEW OUTPUT,I,CURRVAL
SET OUTPUT="",CURRVAL=INPUT
SET:... |
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... | #PL.2FM | PL/M | 100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* CP/M COMMAND LINE ARGUMENT */
DECLARE ARG$LPTR ADDRESS INITIAL (80H), ARG$LEN BASED ARG$LPTR BYTE;
DECLAR... |
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... | #TSE_SAL | TSE SAL |
STRING PROC FNStringGetDecodeStringCharacterEqualCountS( STRING inS )
STRING s1[255] = ""
STRING s2[255] = ""
STRING s3[255] = ""
STRING s4[255] = ""
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
INTEGER L = 0
K = Length( inS )
I = 1 - 1
REPEAT
J = 1 - 1
s3 = ""
REPEAT
I = I + 1
J = J + 1
s1 = S... |
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... | #Aime | Aime | call_n(5, o_text, "ha"); |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Bracmat | Bracmat | (addsub=x y.!arg:(?x.?y)&(!x+!y.!x+-1*!y)); |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #C | C | #include<stdio.h>
typedef struct{
int integer;
float decimal;
char letter;
char string[100];
double bigDecimal;
}Composite;
Composite example()
{
Composite C = {1, 2.3, 'a', "Hello World", 45.678};
return C;
}
int main()
{
Composite C = example();
printf("Values from a function returning a structure ... |
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
... | #0815 | 0815 | }:r: Start reader loop.
!~>& Push a character to the "stack".
<:a:=- Stop reading on newline.
^:r:
@> Rotate the newline to the end and enqueue a sentinel 0.
{~ Dequeue and rotate the first character into place.
}:p:
${~ Print the current character until it's 0.
^:p:
#:r: Read again. |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Detailed_Description_of_Programming_Task | Detailed Description of Programming Task | select
Server.Wake_Up (Parameters);
or delay 5.0;
-- No response, try something else
...
end select; |
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.
| #Action.21 | Action! | DEFINE PTR="CARD"
PROC OutputText(CHAR ARRAY s)
PrintE(s)
RETURN
PROC Procedure=*(CHAR ARRAY s)
DEFINE JSR="$20"
DEFINE RTS="$60"
[JSR $00 $00 ;JSR to address set by SetProcedure
RTS]
PROC SetProcedure(PTR p)
PTR addr
addr=Procedure+1 ;location of address of JSR
PokeC(addr,p)
RETURN
PROC Repe... |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Repeat_Example is
procedure Repeat(P: access Procedure; Reps: Natural) is
begin
for I in 1 .. Reps loop
P.all; -- P points to a procedure, and P.all actually calls that procedure
end loop;
end Repeat;
procedure Hello is
begin
Ada.Text_IO.Put("Hello! "... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Raku | Raku | =for CREDITS
Crypto-JS v2.0.0
http:#code.google.com/p/crypto-js/
Copyright (c) 2009, Jeff Mott. All rights reserved.
sub rotl($n, $b) { $n +< $b +| $n +> (32 - $b) }
sub prefix:<m^> { +^$^x % 2**32 }
sub infix:<m+> { ($^x + $^y) % 2**32 }
constant r1 = <
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
7 4 13 1 10 6 1... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #J | J | nodes=: 10 10 #: i. 100
nodeA=: 1 1
nodeB=: 6 7
NB. verb to pair up coordinates along a specific offset
conn =: [: (#~ e.~/@|:~&0 2) ([ ,: +)"1
ref =: ~. nodeA,nodes-.nodeB NB. all nodes, with A first and B omitted
wiring=: /:~ ref i. ,/ nodes conn"2 1 (,-)=i.2 NB. connected pairs (indices into ... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Phix | Phix | with javascript_semantics
enum METHODS
function invoke(object o, string name, sequence args={})
--(this works on any class, for any function, with any number or type of parameters)
integer mdict = o[METHODS]
integer node = getd_index(name,mdict)
if node!=0 then
return call_func(getd_by_index(node,... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #PHP | PHP | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$ex... |
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... | #Burlesque | Burlesque |
blsq ) "It is not raining"wd<-wd
"raining not is It"
blsq ) "ice. in say some"wd<-wd
"some say in ice."
|
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... | #C | C | #include <stdio.h>
#include <ctype.h>
void rev_print(char *s, int n)
{
for (; *s && isspace(*s); s++);
if (*s) {
char *e;
for (e = s; *e && !isspace(*e); e++);
rev_print(e, 0);
printf("%.*s%s", (int)(e - s), s, " " + n);
}
... |
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... | #Oz | Oz | declare
fun {RotChar C}
if C >= &A andthen C =< &Z then &A + (C - &A + 13) mod 26
elseif C >= &a andthen C =< &z then &a + (C - &a + 13) mod 26
else C
end
end
fun {Rot13 S}
{Map S RotChar}
end
in
{System.showInfo {Rot13 "NOWHERE Abjurer 42"}}
{System.showInfo {Rot13 {Rot13 "NO... |
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... | #Nim | Nim | import strutils
const nums = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
(50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
proc toRoman(n: Positive): string =
var n = n.int
for (a, r) in nums:
result.add(repeat(r, n div a))
n = n mo... |
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... | #PL.2FSQL | PL/SQL |
/*****************************************************************
* $Author: Atanas Kebedjiev $
*****************************************************************
* PL/SQL code can be run as anonymous block.
* To test, execute the whole script or create the functions and then e.g. 'select rdecode('2012') from dua... |
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... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT,{}
input="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",output=""
string=strings(input," ? ")
letter=ACCUMULATE(string,freq)
freq=SPLIT(freq),letter=SPLIT(letter)
output=JOIN(freq,"",letter)
output=JOIN(output,"")
PRINT input
PRINT output
|
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... | #ALGOL_68 | ALGOL 68 | print (5 * "ha")
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class ReturnMultipleValues
{
static void Main()
{
var values = new[] { 4, 51, 1, -3, 3, 6, 8, 26, 2, 4 };
int max, min;
MinMaxNum(values, out max, out min);
Console.WriteLine("Min: {0}\nMax: {1}", min, max);
... |
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
... | #11l | 11l | reversed(string) |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Ada | Ada | select
Server.Wake_Up (Parameters);
or delay 5.0;
-- No response, try something else
...
end select; |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #AutoHotkey | AutoHotkey | OnMessage(0x4a, "PrintMonitor")
SetTimer, print2, 400
print1:
print("Old Mother Goose")
print("When she wanted to wander,")
print("Would ride through the air")
print("On a very fine gander.")
print("Jack's mother came in,")
print("And caught the goose soon,")
print("And mounting its back,")
print("Fle... |
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.
| #ALGOL_68 | ALGOL 68 |
# operator that executes a procedure the specified number of times #
OP REPEAT = ( INT count, PROC VOID routine )VOID:
TO count DO routine OD;
# make REPEAT a low priority operater #
PRIO REPEAT = 1;
# can also create variant that passes the iteration count... |
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... | #11l | 11l | fs:rename(‘input.txt’, ‘output.txt’)
fs:rename(‘docs’, ‘mydocs’)
fs:rename(fs:path:sep‘input.txt’, fs:path:sep‘output.txt’)
fs:rename(fs:path:sep‘docs’, fs:path:sep‘mydocs’) |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Ruby | Ruby | require 'digest'
puts Digest::RMD160.hexdigest('Rosetta Code') |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Rust | Rust |
use ripemd160::{Digest, Ripemd160};
/// Create a lowercase hexadecimal string using the
/// RIPEMD160 hashing algorithm
fn ripemd160(text: &str) -> String {
// create a lowercase hexadecimal string
// using the shortand for the format macro
// https://doc.rust-lang.org/std/fmt/trait.LowerHex.html
fo... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class ResistorMesh {
private static final int S = 10;
private static class Node {
double v;
int fixed;
Node(double v, int fixed) {
this.v = v;
this.fixed = fixed;
}
}
private static ... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #PicoLisp | PicoLisp | (redef send (Msg Obj . @)
(or
(pass try Msg Obj)
(pass 'no-applicable-method> Obj Msg) ) )
(de no-applicable-method> (This Msg)
(pack "No method for " Msg " on " This) )
(class +A)
(dm do-something> ()
(pack "Do something to " This) ) |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Pike | Pike | class CatchAll
{
mixed `->(string name)
{
return lambda(int arg){ write("you are calling %s(%d);\n", name, arg); };
}
}
> CatchAll()->hello(5);
you are calling hello(5);
> CatchAll()->something(99);
you are calling something(99); |
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... | #C.23 | C# | using System;
public class ReverseWordsInString
{
public static void Main(string[] args)
{
string text = @"
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. fav... |
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... | #PARI.2FGP | PARI/GP | rot13(s)={
s=Vecsmall(s);
for(i=1,#s,
if(s[i]>109&s[i]<123,s[i]-=13,if(s[i]<110&s[i]>96,s[i]+=13,if(s[i]>77&s[i]<91,s[i]-=13,if(s[i]<78&s[i]>64,s[i]+=13))))
);
Strchr(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... | #Objeck | Objeck |
bundle Default {
class Roman {
nums: static : Int[];
rum : static : String[];
function : Init() ~ Nil {
nums := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
rum := ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
}
function : native : ToRoman(nu... |
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... | #PowerShell | PowerShell |
Filter FromRoman {
$output = 0
if ($_ -notmatch '^(M{1,3}|)(CM|CD|D?C{0,3}|)(XC|XL|L?X{0,3}|)(IX|IV|V?I{0,3}|)$') {
throw 'Incorrect format'
}
$current = 1000
$subtractor = 'M'
$whole = $False
$roman = $_
'C','D','X','L','I','V',' ' `
| %{
if ($whole = !$whole) {
$current /= 10
$subtractor = $_... |
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... | #UNIX_Shell | UNIX Shell | encode() {
local phrase=$1
[[ -z $phrase ]] && return
local result="" count=0 char=${phrase:0:1}
for ((i = 0; i < ${#phrase}; i++)); do
if [[ ${phrase:i:1} == "$char" ]]; then
((count++))
else
result+="$(encode_sequence "$count" "$char")"
char=${phrase... |
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... | #Amazing_Hopper | Amazing Hopper |
#!/usr/bin/hopper
#include <hopper.h>
main:
{"ha"}replyby(5), println
{"ha",5}replicate, println
{0}return
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #C.2B.2B | C++ | #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>
std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
const auto maximum = std::max_element(numbers, numbers + num);
const auto minimum = std::min_element(numbers, numbers + num);
return std::mak... |
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... | #11l | 11l | F reps(text)
R (1 .< 1 + text.len I/ 2).filter(x -> @text.starts_with(@text[x..])).map(x -> @text[0 .< x])
V matchstr =
|‘1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1’
L(line) matchstr.split("\n")
print(‘'#.' has reps #.’.format(line, reps(line))) |
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
| #11l | 11l | V string = ‘This is a string’
I re:‘string$’.search(string)
print(‘Ends with string.’)
string = string.replace(re:‘ a ’, ‘ another ’)
print(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
... | #360_Assembly | 360 Assembly | * Reverse a string 21/05/2016
REVERSE CSECT
USING REVERSE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #C | C |
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
/* The language task, implemented with pthreads for POSIX systems. */
/* Each rendezvous_t will be accepted by a single thread, and entered
* by one or more threads. accept_func() only returns an integer and
* is always run within the entering thread'... |
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.
| #ALGOL_W | ALGOL W | begin
% executes the procedure routine the specified number of times %
procedure repeat ( integer value count; procedure routine ) ;
for i := 1 until count do routine;
begin
integer x;
% print "hello" three times %
repeat( ... |
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.
| #AppleScript | AppleScript | -- applyN :: Int -> (a -> a) -> a -> a
on applyN(n, f, x)
script go
on |λ|(a, g)
|λ|(a) of mReturn(g)
end |λ|
end script
foldl(go, x, replicate(n, f))
end applyN
-------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION --------
on double(x)
2 * x
end double
on plusArrow(s... |
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... | #Action.21 | Action! | INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
PROC Dir(CHAR ARRAY filter)
BYTE dev=[1]
CHAR ARRAY line(255)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*",
cmd="D:INPUT.... |
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... | #Ada | Ada | with Ada.Directories; use Ada.Directories;
...
Rename ("input.txt", "output.txt");
Rename ("docs", "mydocs");
Rename ("/input.txt", "/output.txt");
Rename ("/docs", "/mydocs"); |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Scala | Scala | import org.bouncycastle.crypto.digests.RIPEMD160Digest
object RosettaRIPEMD160 extends App {
val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new RIPEMD160Digest())
messageDigest.update(raw, 0, raw.length)
val out = Array.fill[Byte](messageDigest.getDigestSize())(0)
messageDigest.doFinal(out, ... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Julia | Julia | N = 10
D1 = speye(N-1,N) - spdiagm(ones(N-1),1,N-1,N)
D = [ kron(D1, speye(N)); kron(speye(N), D1) ]
i, j = N*1 + 2, N*7+7
b = zeros(N^2); b[i], b[j] = 1, -1
v = (D' * D) \ b
v[i] - v[j] |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Kotlin | Kotlin | // version 1.1.4-3
typealias List2D<T> = List<List<T>>
const val S = 10
class Node(var v: Double, var fixed: Int)
fun setBoundary(m: List2D<Node>) {
m[1][1].v = 1.0; m[1][1].fixed = 1
m[6][7].v = -1.0; m[6][7].fixed = -1
}
fun calcDiff(m: List2D<Node>, d: List2D<Node>, w: Int, h: Int): Double {
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Python | Python | class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Racket | Racket |
#lang racket
(require racket/class)
(define-syntax-rule (send~ obj method x ...)
;; note: this is a naive macro, a real one should avoid evaluating `obj' and
;; the `xs' more than once
(with-handlers ([(λ(e) (and (exn:fail:object? e)
;; only do this if there *is* an `unknown-me... |
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... | #C.2B.2B | C++ |
#include <algorithm>
#include <functional>
#include <string>
#include <iostream>
#include <vector>
//code for a C++11 compliant compiler
template <class BidirectionalIterator, class T>
void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
std::reverse(first, last... |
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... | #Pascal | Pascal | program rot13;
var
line: string;
function rot13(someText: string): string;
var
i: integer;
ch: char;
result: string;
begin
result := '';
for i := 1 to Length(someText) do
begin
ch := someText[i];
case ch of
... |
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... | #OCaml | OCaml | 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]
let rec to_roman x =
if x = 0 then []
else if x < 0 then
invalid_arg "Negative roman numeral"
else if x >= 1000 then
'M' :: to_roman (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... | #Prolog | Prolog | decode_digit(i, 1).
decode_digit(v, 5).
decode_digit(x, 10).
decode_digit(l, 50).
decode_digit(c, 100).
decode_digit(d, 500).
decode_digit(m, 1000).
decode_string(Sum, _, [], Sum).
decode_string(LastSum, LastValue, [Digit|Rest], NextSum) :-
decode_digit(Digit, Value),
Value < LastValue,
Sum is LastSum - Va... |
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... | #Ursala | Ursala | #import std
#import nat
encode = (rlc ==); *= ^lhPrNCT\~&h %nP+ length
decode = (rlc ~&l-=digits); *=zyNCXS ^|DlS/~& iota+ %np
test_data = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
#show+
example =
<
encode test_data,
decode encode test_data> |
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... | #APL | APL | 10⍴'ha'
hahahahaha |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Clipper | Clipper | Function Addsub( x, y )
Return { x+y, x-y } |
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... | #Action.21 | Action! | BYTE FUNC IsCycle(CHAR ARRAY s,sub)
BYTE i,j,count
IF sub(0)=0 OR s(0)<sub(0) THEN
RETURN (0)
FI
j=1 count=0
FOR i=1 TO s(0)
DO
IF s(i)#sub(j) THEN
RETURN (0)
FI
j==+1
IF j>sub(0) THEN
j=1 count==+1
FI
OD
IF count>1 THEN
RETURN (1)
FI
RETURN (0)
PROC Test(... |
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
| #8th | 8th |
"haystack" /a./ r:match . cr
"haystack" /a./ "blah" s:replace! . cr
|
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
| #ABAP | ABAP |
DATA: text TYPE string VALUE 'This is a Test'.
FIND FIRST OCCURRENCE OF REGEX 'is' IN text.
IF sy-subrc = 0.
cl_demo_output=>write( 'Regex matched' ).
ENDIF.
REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'.
cl_demo_output=>write( text ).
cl_demo_output=>display( ).
|
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
... | #8080_Assembly | 8080 Assembly | org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reverse a string under HL in place
;; strrev0: reverse a zero-terminated string
;; strrev: reverse a string terminated by the value in A
;; arrayrev: reverse bytes starting at DE and ending at HL
;; Destroys a, b, d, e, h... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #D | D | import std.stdio, std.array, std.datetime, std.exception,
std.concurrency, core.thread, core.atomic;
final class OutOfInk: Exception {
this() pure nothrow {
super("Out of ink.");
}
}
struct Printer {
string id;
size_t ink;
void printIt(in string line) {
enforce(ink != 0,... |
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.
| #Applesoft_BASIC | Applesoft BASIC | print "---------------------------"
print "As a loop"
print "---------------------------"
loop 4 'x ->
print "Example 1"
repeatFunc: function [f,times][
loop times 'x ->
do f
]
print "---------------------------"
print "With a block param"
print "---------------------------"
repeatFunc [print "Examp... |
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.
| #Arturo | Arturo | print "---------------------------"
print "As a loop"
print "---------------------------"
loop 4 'x ->
print "Example 1"
repeatFunc: function [f,times][
loop times 'x ->
do f
]
print "---------------------------"
print "With a block param"
print "---------------------------"
repeatFunc [print "Examp... |
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... | #ALGOL_68 | ALGOL 68 | main:(
PROC rename = (STRING source name, dest name)INT:
BEGIN
FILE actual file;
INT errno = open(actual file, source name, stand back channel);
IF errno NE 0 THEN
errno
ELSE
IF reidf possible(actual file) THEN
reidf(actual file, dest name); # change the identification of the boo... |
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... | #Arturo | Arturo | fileFrom: "input.txt"
fileTo: "output.txt"
docsFrom: "docs"
docsTo: "mydocs"
rename fileFrom fileTo
rename.directory docsFrom docsTo
rename join.path ["/" fileFrom]
join.path ["/" fileTo]
rename.directory join.path ["/" docsFrom]
join.path ["/" docsTo] |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin
writeln(hex(ripemd160("Rosetta Code")));
end func; |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Swift | Swift | // Circular left shift: http://en.wikipedia.org/wiki/Circular_shift
// Precendence should be the same as <<
infix operator ~<< { precedence 160 associativity none }
public func ~<< (lhs: UInt32, rhs: Int) -> UInt32 {
return (lhs << UInt32(rhs)) | (lhs >> UInt32(32 - rhs));
}
public struct Block {
p... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ResistanceMatrix[g_Graph] := With[{n = VertexCount[g], km = KirchhoffMatrix[g]},
Table[ ReplacePart[ Diagonal[ DrazinInverse[ ReplacePart[km, k -> UnitVector[n, k]]]], k -> 0],
{k, n}]
]
rm = ResistanceMatrix[GridGraph[{10, 10}]];
N[rm[[12, 68]], 40] |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Maxima | Maxima | /* Place a current souce between A and B, providing 1 A. Then we are really looking
for the potential at A and B, since I = R (V(B) - V(A)) where I is given and we want R.
Atually, we will compute potential at each node, except A where we assume it's 0.
Without this assumption, there would be infinitely many... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Raku | Raku | class Farragut {
method FALLBACK ($name, *@rest) {
say "{self.WHAT.raku}: $name.tc() the @rest[], full speed ahead!";
}
}
class Sparrow is Farragut { }
Farragut.damn: 'torpedoes';
Sparrow.hoist: <Jolly Roger mateys>; |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Ring | Ring |
load "stdlibcore.ring"
new test {
anyMethodThatDoesNotExist() # Define and call the new method
anyMethodThatDoesNotExist() # Call the new method
}
class test
func braceerror
if substr(cCatchError,"Error (R3)")
? "You are calling a method that doesn't exist!"
aError =... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Ruby | Ruby | class Example
def foo
puts "this is foo"
end
def bar
puts "this is bar"
end
def method_missing(name, *args, &block)
puts "tried to handle unknown method %s" % name # name is a symbol
unless args.empty?
puts "it had arguments: %p" % [args]
end
e... |
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... | #Clojure | Clojure |
(def 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 -----------------------")
(dorun
(map println (map #(apply str (interpose "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.