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/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
| #Raku | Raku | my $*TOLERANCE = 1e-12;
sub set-boundary(@mesh,@p1,@p2) {
@mesh[ @p1[0] ; @p1[1] ] = 1;
@mesh[ @p2[0] ; @p2[1] ] = -1;
}
sub solve(@p1, @p2, Int \w, Int \h) {
my @d = [0 xx w] xx h;
my @V = [0 xx w] xx h;
my @fixed = [0 xx w] xx h;
set-boundary(@fixed,@p1,@p2);
loop {
... |
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... | #Elm | Elm |
reversedPoem =
String.trim """
---------- 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 -----------------------
"""
reverseWords stri... |
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... | #Emacs_Lisp | Emacs Lisp | (defun reverse-words (line)
(insert
(format "%s\n"
(mapconcat 'identity (reverse (split-string line)) " "))))
(defun reverse-lines (lines)
(mapcar 'reverse-words lines))
(reverse-lines
'("---------- Ice and Fire ------------"
""
"fire, in end will world the say Some"
"ice. in say Some"
... |
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... | #Pop11 | Pop11 | define rot13(s);
lvars j, c;
for j from 1 to length(s) do
s(j) -> c;
if `A` <= c and c <= `M` or `a` <= c and c <= `m` then
c + 13 -> s(j);
elseif `N` <= c and c <= `Z` or `n` <= c and c <= `z` then
c - 13 -> s(j);
endif;
endfor;
s;
enddefine;
ro... |
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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def romanEnc /# n -- s #/
var number
"" var res
( ( 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" ) )
len for
get 1 get
number over / int
numbe... |
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... | #Red | Red | Red [
Purpose: "Arabic <-> Roman numbers converter"
Author: "Didier Cadieu"
Date: "07-Oct-2016"
]
table-r2a: reverse [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"]
roman-to-arabic: func [r [string!] /local a b e] [
a: 0
parse r [any [b: ["I" ["V" |... |
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... | #BBC_BASIC | BBC BASIC | PRINT STRING$(5, "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... | #beeswax | beeswax | p <
p0~1<}~< d@<
_VT@1~>yg~9PKd@M'd; |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Eiffel | Eiffel | some_feature: TUPLE
do
Result := [1, 'j', "r"]
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
... | #Aime | Aime | index x;
list(1, 2, 3, 1, 2, 3, 4, 1).ucall(i_add, 1, x, 0);
x.i_vcall(o_, 1, " ");
o_newline(); |
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... | #Ada | Ada | with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions;
use Ada.Text_IO;
procedure Remove_Lines_From_File is
Temporary: constant String := ".tmp";
begin
if Ada.Command_Line.Argument_Count /= 3 then
raise Constraint_Error;
end if;
declare
Filename: String := Ada.Command_Line.Arg... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #BBC_BASIC | BBC BASIC | wavfile$ = @dir$ + "capture.wav"
bitspersample% = 16
channels% = 2
samplespersec% = 44100
alignment% = bitspersample% * channels% / 8
bytespersec% = alignment% * samplespersec%
params$ = " bitspersample " + STR$(bitspersample%) + \
\ " channels " + STR$(channe... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #C | C | #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void * record(size_t bytes)
{
int fd;
if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
void *a = malloc(bytes);
read(fd, a, bytes);
close(fd);
return a;
}
int play(void *buf, size_t len)
{
int fd;
if (-1 == (fd = open("/... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Go | Go | package main
import (
"fmt"
"image"
"reflect"
)
type t int // A type definition
// Some methods on the type
func (r t) Twice() t { return r * 2 }
func (r t) Half() t { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}
func main() {
report(t(0))
report(im... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Julia | Julia | for obj in (Int, 1, 1:10, collect(1:10), now())
println("\nObject: $obj\nDescription:")
dump(obj)
end |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Kotlin | Kotlin | // version 1.1
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
open class BaseExample(val baseProp: String) {
protected val protectedProp: String = "inherited protected value"
}
class Example(val prop1: String, val prop2: Int, baseProp: String) : BaseExample(baseProp) {
... |
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... | #C | C |
#include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #Wren | Wren | import "os" for Platform, Process
import "io" for File
import "/pattern" for Pattern
var getSourceLines = Fn.new {
var fileName = Process.allArguments[1]
var text = File.read(fileName)
var sep = Platform.isWindows ? "\r\n" : "\n"
return [fileName, text.split(sep)]
}
var res = getSourceLines.call()
v... |
http://rosettacode.org/wiki/Reflection/Get_source | Reflection/Get source | Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
| #zkl | zkl | src:=File(__FILE__).read();
println("Src file is \"%s\" and has %d lines".fmt(__FILE__,src.len(1))); |
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
| #C.23 | C# | using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
... |
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
... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
s="mañana será otro día"
reverse(s),strtoutf8, println
{0}return
|
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Wren | Wren | class Printer {
construct new(id, ink) {
_id = id
_ink = ink
}
ink { _ink }
ink=(v) { _ink = v }
print(text) {
System.write("%(_id): ")
for (c in text) System.write(c)
System.print()
_ink = _ink - 1
}
}
var ptrMain = Printer.new("Main ... |
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.
| #Factor | Factor | 3 [ "Hello!" print ] times |
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.
| #Forth | Forth | : times ( xt n -- )
0 ?do dup execute loop drop ; |
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... | #DCL | DCL | rename input.txt output.txt
rename docs.dir mydocs.dir
rename [000000]input.txt [000000]output.txt
rename [000000]docs.dir [000000]mydocs.dir |
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... | #Delphi | Delphi | program RenameFile;
{$APPTYPE CONSOLE}
uses SysUtils;
begin
SysUtils.RenameFile('input.txt', 'output.txt');
SysUtils.RenameFile('\input.txt', '\output.txt');
// RenameFile works for both files and folders
SysUtils.RenameFile('docs', 'MyDocs');
SysUtils.RenameFile('\docs', '\MyDocs');
end. |
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
| #REXX | REXX | /*REXX program calculates the resistance between any two points on a resistor grid.*/
if 2=='f2'x then ohms = "ohms" /*EBCDIC machine? Then use 'ohms'. */
else ohms = "Ω" /* ASCII " " " Greek Ω.*/
parse arg high wide Arow Acol Brow Bcol digs ... |
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... | #F.23 | F# |
//Reverse words in a string. Nigel Galloway: July 14th., 2021
[" ---------- Ice and Fire ------------ ";
" ";
" fire, in end will world the say Some ";
" ice. in say Some ";
" desire of tasted I've what From ";
" fire. favour who tho... |
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... | #PostScript | PostScript |
/r13 {
4 dict begin
/rotc {
{
{{{64 gt} {91 lt}} all?} {65 - 13 + 26 mod 65 +} is?
{{{95 gt} {123 lt}} all?} {97 - 13 + 26 mod 97 +} is?
} cond
}.
{rotc} map cvstr
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... | #PHP | PHP |
/**
* int2roman
* Convert any positive value of a 32-bit signed integer to its modern roman
* numeral representation. Numerals within parentheses are multiplied by
* 1000. ie. M == 1 000, (M) == 1 000 000, ((M)) == 1 000 000 000
*
* @param number - an integer between 1 and 2147483647
* @return roman numeral... |
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... | #REXX | REXX | /* Rexx */
Do
/* 1990 2008 1666 */
years = 'MCMXC MMVIII MDCLXVI'
Do y_ = 1 to words(years)
Say right(word(years, y_), 10) || ':' decode(word(years, y_))
End y_
Return
End
Exit
decode:
Procedure
Do
Parse upper arg roman .
If verify(roman, 'MDCLXVI') = 0 then Do
/* alway... |
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... | #Befunge | Befunge | v> ">:#,_v
>29*+00p>~:"0"- #v_v $
v ^p0p00:-1g00< $ >
v p00&p0-1g00+4*65< >00g1-:00p#^_@ |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Elena | Elena | import system'routines;
import extensions;
extension op
{
MinMax(ref int minVal, ref int maxVal)
{
var ordered := self.ascendant();
minVal := ordered.FirstMember;
maxVal := ordered.LastMember
}
}
public program()
{
var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Elixir | Elixir | defmodule RC do
def addsub(a, b) do
{a+b, a-b}
end
end
{add, sub} = RC.addsub(7, 4)
IO.puts "Add: #{add},\tSub: #{sub}" |
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
... | #ALGOL_68 | ALGOL 68 | # use the associative array in the Associate array/iteration task #
# this example uses strings - for other types, the associative #
# array modes AAELEMENT and AAKEY should be modified as required #
PR read "aArray.a68" PR
# returns the unique elements of list #
PROC remov... |
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... | #ALGOL_68 | ALGOL 68 | # removes the specified number of lines from a file, starting at start line (numbered from 1) #
# returns TRUE if successful, FALSE otherwise #
PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOOL:
IF number of lines < 0 OR start line < 1
THEN
# invalid parameters #
... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
using namespace std;
class recorder
{
public:
void start()
{
paused = rec = false; action = "IDLE";
while( true )
{
cout << endl << "==" << action << "==" << endl << endl;
cou... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #J | J |
NB. define a stack class
coclass 'Stack'
create =: 3 : 'items =: i. 0'
push =: 3 : '# items =: items , < y'
top =: 3 : '> {: items'
pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;')
destroy =: codestroy
cocurrent 'base'
names_Stack_'' NB. all names
create destroy pop push ... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Java | Java | import java.lang.reflect.Method;
public class ListMethods {
public int examplePublicInstanceMethod(char c, double d) {
return 42;
}
private boolean examplePrivateInstanceMethod(String s) {
return true;
}
public static void main(String[] args) {
Class clazz = ListMethods... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Lingo | Lingo | obj = script("MyClass").new()
obj.foo = 23
obj.bar = 42
-- ...
-- show obj's property names and values
cnt = obj.count
repeat with i = 1 to cnt
put obj.getPropAt(i)&" = "&obj[i]
end repeat |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Lua | Lua | a = 1
b = 2.0
c = "hello world"
function listProperties(t)
if type(t) == "table" then
for k,v in pairs(t) do
if type(v) ~= "function" then
print(string.format("%7s: %s", type(v), k))
end
end
end
end
print("Global properties")
listProperties(_G)
print("... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Nanoquery | Nanoquery | // declare a class that has fields to be listed
class Fields
declare static field1 = "this is a static field. it will not be listed"
declare field2
declare field3
declare field4
end
// list all the fields in the class
for fieldname in Fields.getFieldNames()
println fieldname
end |
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... | #C.2B.2B | C++ | #include <string>
#include <vector>
#include <boost/regex.hpp>
bool is_repstring( const std::string & teststring , std::string & repunit ) {
std::string regex( "^(.+)\\1+(.*)$" ) ;
boost::regex e ( regex ) ;
boost::smatch what ;
if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
... |
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
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
// match the complete string
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
// ... |
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
... | #Apex | Apex |
String str = 'Hello World!';
str = str.reverse();
system.debug(str);
|
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #zkl | zkl | class OutOfInk(Exception.IOError){
const TEXT="Out of ink";
text=TEXT; // rename IOError to OutOfInk for this first/mother class
fcn init{ IOError.init(TEXT) } // this renames instances
}
class Printer{
var id, ink;
fcn init(_id,_ink){ id,ink=vm.arglist }
fcn print(line){
if(not ink) throw(OutO... |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub proc()
Print " proc called"
End Sub
Sub repeat(s As Sub, n As UInteger)
For i As Integer = 1 To n
Print Using "##"; i;
s()
Next
End Sub
repeat(@proc, 5)
Print
Print "Press any key to quit"
Sleep |
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... | #E | E | for where in [<file:.>, <file:///>] {
where["input.txt"].renameTo(where["output.txt"], null)
where["docs"].renameTo(where["mydocs"], null)
} |
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... | #Elixir | Elixir | File.rename "input.txt","output.txt"
File.rename "docs", "mydocs"
File.rename "/input.txt", "/output.txt"
File.rename "/docs", "/mydocs" |
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
| #Sidef | Sidef | var (w, h) = (10, 10)
var v = h.of { w.of(0) } # voltage
var f = h.of { w.of(0) } # fixed condition
var d = h.of { w.of(0) } # diff
var n = [] # neighbors
for i in ^h {
for j in (1 ..^ w ) { n[i][j] := [] << [i, j-1] }
for j in (0 ..^ w-1) { n[i][j] := [] << [i, j+1] }
}
for j in ^w {
f... |
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... | #Factor | Factor | USING: io sequences splitting ;
IN: rosetta-code.reverse-words
"---------- 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 -----------------------"
"\n" split [ " " spli... |
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... | #PowerBASIC | PowerBASIC |
#COMPILE EXE
#COMPILER PBWIN 9.05
#DIM ALL
FUNCTION ROT13(BYVAL a AS STRING) AS STRING
LOCAL p AS BYTE PTR
LOCAL n AS BYTE, e AS BYTE
LOCAL res AS STRING
res = a
p = STRPTR(res)
n = @p
DO WHILE n
SELECT CASE n
CASE 65 TO 90
e = 90
n += 13
CASE 97 TO 122
e = 12... |
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... | #Picat | Picat | go =>
List = [455,999,1990,1999,2000,2001,2008,2009,2010,2011,2012,1666,3456,3888,4000],
foreach(Val in List)
printf("%4d: %w\n", Val, roman_encode(Val))
end,
nl.
roman_encode(Val) = Res =>
if Val <= 0 then
Res := -1
else
Arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5,... |
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... | #Ring | Ring |
symbols = "MDCLXVI"
weights = [1000,500,100,50,10,5,1]
see "MCMXCIX = " + romanDec("MCMXCIX") + nl
see "MDCLXVI =" + romanDec("MDCLXVI") + nl
see "XXV = " + romanDec("XXV") + nl
see "CMLIV = " + romanDec("CMLIV") + nl
see "MMXI = " + romanDec("MMXI") + nl
func romanDec roman
n = 0
lastval = 0
arabi... |
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... | #BQN | BQN | Repeat ← ×⟜≠ ⥊ ⊢
•Show 5 Repeat "Hello" |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Erlang | Erlang | % Put this code in return_multi.erl and run it as "escript return_multi.erl"
-module(return_multi).
main(_) ->
{C, D, E} = multiply(3, 4),
io:format("~p ~p ~p~n", [C, D, E]).
multiply(A, B) ->
{A * B, A + B, A - B}.
|
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
... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
x=-1
{30} rand array (x), mulby(10), ceil, mov(x)
{"Original Array:\n",x}, println
{x}array(SORT),
{x}sets(UNIQUE), mov(x)
{"Final array:\n",x}, println
y={}
{"C","Go","Go","C","Cobol","java","Ada"} pushall(y)
{"java","algol-68","C","java","fortran"} pushall(... |
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... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
.ctrlc
fd=0,fw=0
fopen(OPEN_READ,"archivo.txt")(fd)
if file error?
{"no pude abrir el archivo de lectura: "}
jsub(show error)
else
fcreate(CREATE_NORMAL,"archivoTmp.txt")(fw)
if file error?
{"no pude crear el archivo para escritura: "}
... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #ChucK | ChucK | // chuck this with other shreds to record to file
// example> chuck foo.ck bar.ck rec
// arguments: rec:<filename>
// get name
me.arg(0) => string filename;
if( filename.length() == 0 ) "foo.wav" => filename;
// pull samples from the dac
dac => Gain g => WvOut w => blackhole;
// this is the output file name
file... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #JavaScript | JavaScript | // Sample classes for reflection
function Super(name) {
this.name = name;
this.superOwn = function() { return 'super owned'; };
}
Super.prototype = {
constructor: Super
className: 'super',
toString: function() { return "Super(" + this.name + ")"; },
doSup: function() { return 'did super stuff'; ... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Nim | Nim | type
Foo = object
a: float
b: string
c: seq[int]
let f = Foo(a: 0.9, b: "hi", c: @[1,2,3])
for n, v in f.fieldPairs:
echo n, ": ", v |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo : NSObject {
int exampleIvar;
}
@property (nonatomic) double exampleProperty;
@end
@implementation Foo
- (instancetype)init {
self = [super init];
if (self) {
exampleIvar = 42;
_exampleProperty = 3.14;
}
return self;
}
@end
... |
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... | #Clojure | Clojure | (defn rep-string [s]
(let [len (count s)
first-half (subs s 0 (/ len 2))
test-group (take-while seq (iterate butlast first-half))
test-reptd (map (comp #(take len %) cycle) test-group)]
(some #(= (seq s) %) test-reptd))) |
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
| #Clojure | Clojure | (let [s "I am a string"]
;; match
(when (re-find #"string$" s)
(println "Ends with 'string'."))
(when-not (re-find #"^You" s)
(println "Does not start with 'You'."))
;; substitute
(println (clojure.string/replace s " a " " another "))
) |
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
| #Common_Lisp | Common Lisp | (let ((string "I am a string"))
(when (cl-ppcre:scan "string$" string)
(write-line "Ends with string"))
(unless (cl-ppcre:scan "^You" string )
(write-line "Does not start with 'You'"))) |
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
... | #APL | APL | ⌽'asdf'
fdsa |
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.
| #Gambas | Gambas |
Public Sub Main()
RepeatIt("RepeatableOne", 2)
RepeatIt("RepeatableTwo", 3)
End
'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call()
Public Sub RepeatIt(sDelegateName As String, iCount As Integer)
For iCounter As Integer = 1 To iCount
Object.Call(Me, 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... | #Emacs_Lisp | Emacs Lisp | (rename-file "input.txt" "output.txt")
(rename-file "/input.txt" "/output.txt")
(rename-file "docs" "mydocs")
(rename-file "/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... | #Erlang | Erlang |
file:rename("input.txt","output.txt"),
file:rename( "docs", "mydocs" ),
file:rename( "/input.txt", "/output.txt" ),
file:rename( "/docs", "/mydocs" ).
|
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
| #Tcl | Tcl | package require Tcl 8.6; # Or 8.5 with the TclOO package
# This code is structured as a class with a little trivial DSL parser
# so it is easy to change what problem is being worked on.
oo::class create ResistorMesh {
variable forcePoints V fixed w h
constructor {boundaryConditions} {
foreach {op conditio... |
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... | #Forth | Forth | : not-empty? dup 0 > ;
: (reverse) parse-name not-empty? IF recurse THEN type space ;
: reverse (reverse) cr ;
reverse ---------- Ice and Fire ------------
reverse
reverse fire, in end will world the say Some
reverse ice. in say Some
reverse desire of tasted I've what From
reverse fire. favor who those with hold I... |
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... | #Fortran | Fortran |
character*40 words
character*40 reversed
logical inblank
ierr=0
read (5,fmt="(a)",iostat=ierr)words
do while (ierr.eq.0)
inblank=.true.
ipos=1
do i=40,1,-1
if(words(i:i).ne.' '.and.inblank) then
last=i
inblank=.false.
end if
if(.not.inblank.and.words(i:i).eq.' ') then
reversed(ipo... |
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... | #PowerShell | PowerShell |
$e = "This is a test Guvf vf n grfg"
[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join ""
|
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... | #PicoLisp | PicoLisp | (de roman (N)
(pack
(make
(mapc
'((C D)
(while (>= N D)
(dec 'N D)
(link C) ) )
'(M CM D CD C XC L XL X IX V IV I)
(1000 900 500 400 100 90 50 40 10 9 5 4 1) ) ) ) ) |
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... | #Ruby | Ruby | def fromRoman(roman)
r = roman.upcase
n = 0
until r.empty? do
case
when r.start_with?('M') then v = 1000; len = 1
when r.start_with?('CM') then v = 900; len = 2
when r.start_with?('D') then v = 500; len = 1
when r.start_with?('CD') then v = 400; len = 2
when r.start_with?('C') then v... |
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... | #Bracmat | Bracmat | (repeat=
string N rep
. !arg:(?string.?N)
& !string:?rep
& whl
' (!N+-1:>0:?N&!string !rep:?rep)
& str$!rep
); |
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... | #Brainf.2A.2A.2A | Brainf*** | +++++ +++++ init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround
Now we want to loop 5 times to follow std
+++++
[-> ++++ . ----- -- . +++<] print h and a each loop
and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- . |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #ERRE | ERRE |
PROGRAM RETURN_VALUES
PROCEDURE SUM_DIFF(A,B->C,D)
C=A+B
D=A-B
END PROCEDURE
BEGIN
SUM_DIFF(5,3->SUM,DIFF)
PRINT("Sum is";SUM)
PRINT("Difference is";DIFF)
END PROGRAM
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Euphoria | Euphoria | include std\console.e --only for any_key, to help make running this program easy on windows GUI
integer aWholeNumber = 1
atom aFloat = 1.999999
sequence aSequence = {3, 4}
sequence result = {} --empty initialized sequence
function addmultret(integer first, atom second, sequence third)--takes three kinds of input, a... |
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
... | #APL | APL | ∪ 1 2 3 1 2 3 4 1
1 2 3 4 |
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... | #11l | 11l | F recamanSucc(seen, n, r)
‘The successor for a given Recaman term,
given the set of Recaman terms seen so far.’
V back = r - n
R I 0 > back | (back C seen) {n + r} E back
F recamanUntil(p)
‘All terms of the Recaman series before the
first term for which the predicate p holds.’
V n = 1
V r = ... |
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... | #AutoHotkey | AutoHotkey | RemoveLines(filename, startingLine, numOfLines){
Loop, Read, %filename%
if ( A_Index < StartingLine )
|| ( A_Index >= StartingLine + numOfLines )
ret .= "`r`n" . A_LoopReadLine
FileDelete, % FileName
FileAppend, % SubStr(ret, 3), ... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Common_Lisp | Common Lisp |
(defun record (n)
(with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8))
(loop repeat n collect (read-byte in))
)
)
(defun play (byte-list)
(with-open-file (out "/dev/dsp" :direction :output :element-type '(unsigned-byte 8) :if-exists :append)
(mapcar (lambda (b) (write-byte b out)) byte-l... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
name := ""
for name == "" {
fmt.Print("Enter output file name (without ext... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Julia | Julia | methods(methods)
methods(println) |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Kotlin | Kotlin | // Version 1.2.31
import kotlin.reflect.full.functions
open class MySuperClass {
fun mySuperClassMethod(){}
}
open class MyClass : MySuperClass() {
fun myPublicMethod(){}
internal fun myInternalMethod(){}
protected fun myProtectedMethod(){}
private fun myPrivateMethod(){}
}
fun main(ar... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #ooRexx | ooRexx | /* REXX demonstrate uses of datatype() */
/* test values */
d.1=''
d.2='a23'
d.3='101'
d.4='123'
d.5='12345678901234567890'
d.6='abc'
d.7='aBc'
d.8='1'
d.9='0'
d.10='Walter'
d.11='ABC'
d.12='f23'
d.13='123'
/* supported options */
t.1='A' /* Alphanumeric */
t.2='... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Perl | Perl | {
package Point;
use Class::Spiffy -base;
field 'x';
field 'y';
}
{
package Circle;
use base qw(Point);
field 'r';
}
my $p1 = Point->new(x => 8, y => -5);
my $c1 = Circle->new(r => 4);
my $c2 = Circle->new(x => 1, y => 2, r => 3);
use Data::Dumper;
say Dumper $p1;
say Dumper $... |
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... | #CLU | CLU | rep_strings = iter (s: string) yields (string)
for len: int in int$from_to_by(string$size(s)/2, 1, -1) do
repstr: string := string$substr(s, 1, len)
attempt: string := ""
while string$size(attempt) < string$size(s) do
attempt := attempt || repstr
end
if s = string... |
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... | #Common_Lisp | Common Lisp |
(ql:quickload :alexandria)
(defun rep-stringv (a-str &optional (max-rotation (floor (/ (length a-str) 2))))
;; Exit condition if no repetition found.
(cond ((< max-rotation 1) "Not a repeating string")
;; Two checks:
;; 1. Truncated string must be equal to rotation by repetion size.
;; 2. ... |
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
| #D | D | void main() {
import std.stdio, std.regex;
immutable s = "I am a string";
// Test.
if (s.match("string$"))
"Ends with 'string'.".writeln;
// Substitute.
s.replace(" a ".regex, " another ").writeln;
} |
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
| #Dart | Dart | RegExp regexp = new RegExp(r'\w+\!');
String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';
void main(){
String hello = 'hello hello! world world!';
String hellomodified = hello.replaceAllMapped(regexp, capitalize);
print(hello);
print(hellomodified);
} |
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
... | #AppleScript | AppleScript | reverseString("Hello World!")
on reverseString(str)
reverse of characters of str as string
end reverseString |
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.
| #Go | Go | package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
} |
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.
| #Haskell | Haskell | import Control.Monad (replicateM_)
sampleFunction :: IO ()
sampleFunction = putStrLn "a"
main = replicateM_ 5 sampleFunction |
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... | #ERRE | ERRE | CMD$="REN "+OLDFILENAME$+" "+NEWFILENAME$
SHELL CMD$
|
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... | #F.23 | F# | open System.IO
[<EntryPoint>]
let main args =
File.Move("input.txt","output.txt")
File.Move(@"\input.txt",@"\output.txt")
Directory.Move("docs","mydocs")
Directory.Move(@"\docs",@"\mydocs")
0 |
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
| #Wren | Wren | class Node {
construct new(v, fixed) {
_v = v
_fixed = fixed
}
v { _v }
v=(value) { _v = value }
fixed { _fixed }
fixed=(value) { _fixed = value }
}
var setBoundary = Fn.new { |m|
m[1][1].v = 1
m[1][1].fixed = 1
m[6][7].v = -1
m[6][7].fixed = -1
}
var calc... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = ... |
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... | #Prolog | Prolog | :- use_module(library(ctypes)).
runtime_entry(start) :-
prompt(_, ''),
rot13.
rot13 :-
get0(Ch),
( is_endfile(Ch) ->
true
; rot13_char(Ch, Rot),
put(Rot),
rot13
).
rot13_char(Ch, Rot) :-
( is_alpha(Ch) ->
to_upper(Ch, Up),
Letter is Up - 0'A,
Rot is Ch + ((Letter + 13) mod 26) - Let... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.