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/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
... | #8080_Assembly | 8080 Assembly | org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Given an array of bytes starting at HL with length BC,
;; remove all duplicates in the array. The new end of the array
;; is returned in HL. A page of memory (256 bytes) is required
;; to mark which bytes have been seen.
... |
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.
| #Factor | Factor | USING: assocs kernel math mirrors prettyprint strings ;
TUPLE: foo
{ bar string }
{ baz string initial: "hi" }
{ baxx integer initial: 50 read-only } ;
C: <foo> foo
"apple" "banana" 200 <foo> <mirror>
[ >alist ] [ object-slots ] bi [ . ] bi@ |
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.
| #Fortran | Fortran | package main
import (
"fmt"
"image"
"reflect"
)
// A type definition
type t struct {
X int
next *t
}
func main() {
report(t{})
report(image.Point{})
}
func report(x interface{}) {
t := reflect.TypeOf(x)
n := t.NumField()
fmt.Printf("Type %v has %d fields:\n", t, n)
fmt.Println("Name Type E... |
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... | #AutoHotkey | AutoHotkey | In := ["1001110011", "1110111011", "0010010010", "1010101010"
, "1111111111", "0100101101", "0100100", "101", "11", "00", "1"]
for k, v in In
Out .= RepString(v) "`t" v "`n"
MsgBox, % Out
RepString(s) {
Loop, % StrLen(s) // 2 {
i := A_Index
Loop, Parse, s
{
pos := Mod(A_Index, i)
if (A_LoopField !... |
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.
| #Java | Java |
public class ReflectionGetSource {
public static void main(String[] args) {
new ReflectionGetSource().method1();
}
public ReflectionGetSource() {}
public void method1() {
method2();
}
public void method2() {
method3();
}
public void method3() {
... |
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.
| #JavaScript | JavaScript | function foo() {...}
foo.toString();
// "function foo() {...}"
|
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.
| #Julia | Julia | # Definition
function foo() end
@which foo() # where foo is defined
@less foo() # first file where foo is defined |
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
| #AutoHotkey | AutoHotkey | MsgBox % foundpos := RegExMatch("Hello World", "World$")
MsgBox % replaced := RegExReplace("Hello World", "World$", "yourself") |
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
... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Reverse_String is
function Reverse_It (Item : String) return String is
Result : String (Item'Range);
begin
for I in Item'range loop
Result (Result'Last - I + Item'First) := Item (I);
end loop;
return Result;
end Reverse_It;
begin
... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Phix | Phix | without js -- (threads)
constant print_cs = init_cs()
enum NAME,INK
sequence printers = {{"main",5},
{"reserve",5}}
procedure printer(string name, sequence s)
try
for i=1 to length(s) do
enter_cs(print_cs)
for p=1 to length(printers) do
if print... |
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.
| #Clojure | Clojure | (defn repeat-function [f n]
(dotimes [i n] (f))) |
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.
| #Common_Lisp | Common Lisp | (defun repeat (f n)
(dotimes (i n) (funcall f)))
(repeat (lambda () (format T "Example~%")) 5) |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #C | C | #include <stdio.h>
int main()
{
rename("input.txt", "output.txt");
rename("docs", "mydocs");
rename("/input.txt", "/output.txt");
rename("/docs", "/mydocs");
return 0;
} |
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... | #C.23 | C# | using System;
using System.IO;
class Program {
static void Main(string[] args) {
File.Move("input.txt","output.txt");
File.Move(@"\input.txt",@"\output.txt");
Directory.Move("docs","mydocs");
Directory.Move(@"\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
| #Phix | Phix | function resistormesh(integer ni, nj, ai, aj, bi, bj)
integer n = ni*nj, k, c
sequence A = repeat(repeat(0,n),n),
B = repeat({0},n)
for i=1 to ni do
for j=1 to nj do
k = (i-1)*nj + j--1
if i=ai and j=aj then
A[k,k] = 1
else
... |
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... | #Delphi | Delphi | program RosettaCode_ReverseWordsInAString;
{$APPTYPE CONSOLE}
uses Classes, Types, StrUtils;
const
TXT =
'---------- Ice and Fire -----------'+sLineBreak+
sLineBreak+
'fire, in end will world the say Some'+sLineBreak+
'ice. in say Some'+sLineBreak+
'desire of tasted I''ve what From'+sLineBreak+
'fir... |
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... | #Pike | Pike |
import Crypto;
int main(){
string r = rot13("Hello, World");
write(r + "\n");
}
|
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... | #Peloton | Peloton | <@ DEFUDOLITLIT>_RO|__Transformer|<@ DEFKEYPAR>__NationalNumericID|2</@><@ LETRESCS%NNMPAR>...|1</@></@>
<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@> |
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... | #R | R | romanToArabic <- function(roman) {
romanLookup <- c(I=1L, V=5L, X=10L, L=50L, C=100L, D=500L, M=1000L)
rSplit <- strsplit(toupper(roman), character(0)) # Split input vector into characters
toArabic <- function(item) {
digits <- romanLookup[item]
if (length(digits) > 1L) {
smaller <- (digits[-length(... |
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... | #Babel | Babel | main: { "ha" 5 print_repeat }
print_repeat!: { <- { dup << } -> times } |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Dc | Dc | [ S1 S2 l2 l1 / L2 L1 % ] s~
1337 42 l~ x f |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Delphi.2FPascal | Delphi/Pascal | program ReturnMultipleValues;
{$APPTYPE CONSOLE}
procedure GetTwoValues(var aParam1, aParam2: Integer);
begin
aParam1 := 100;
aParam2 := 200;
end;
var
x, y: Integer;
begin
GetTwoValues(x, y);
Writeln(x);
Writeln(y);
end. |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #ACL2 | ACL2 | (remove-duplicates xs) |
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.
| #C.23 | C# | using System;
using System.Reflection;
public class Rosetta
{
public static void Main()
{
//Let's get all methods, not just public ones.
BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Declar... |
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.
| #Go | Go | package main
import (
"fmt"
"image"
"reflect"
)
// A type definition
type t struct {
X int
next *t
}
func main() {
report(t{})
report(image.Point{})
}
func report(x interface{}) {
t := reflect.TypeOf(x)
n := t.NumField()
fmt.Printf("Type %v has %d fields:\n", t, n)
fmt.Println("Name Type E... |
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.
| #Groovy | Groovy | import java.lang.reflect.Field
@SuppressWarnings("unused")
class ListProperties {
public int examplePublicField = 42
private boolean examplePrivateField = true
static void main(String[] args) {
ListProperties obj = new ListProperties()
Class clazz = obj.class
println "All publi... |
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... | #BaCon | BaCon | all$ = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1"
FOR word$ IN all$
FOR x = LEN(word$)/2 DOWNTO 1
ex$ = EXPLODE$(word$, x)
FOR st$ IN UNIQ$(ex$)
IF NOT(REGEX(HEAD$(ex$, 1), "^" & st$)) THEN CONTINUE 2
NEXT
PRINT "Repeat... |
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.
| #Kotlin | Kotlin | // Kotlin JS Version 1.2.31
fun hello() {
println("Hello")
}
fun main(args: Array<String>) {
val code = js("_.hello.toString()")
println(code)
}
|
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.
| #Lingo | Lingo | ----------------------------------------
-- Returns source code either for a class (parent script) or a class instance (object)
-- @param {script|instance} class
-- @return {string}
----------------------------------------
on getClassCode (class)
if ilk(class)=#instance then class=class.script
return class.text
end... |
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.
| #Lua | Lua | debug = require("debug")
function foo(bar)
info = debug.getinfo(1)
for k,v in pairs(info) do print(k,v) end
end
foo() |
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.
| #Nanoquery | Nanoquery | import Nanoquery.IO
println new(File, __file__).readAll() |
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
| #AWK | AWK | $ awk '{if($0~/[A-Z]/)print "uppercase detected"}'
abc
ABC
uppercase detected |
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
| #BBC_BASIC | BBC BASIC | SYS "LoadLibrary", "gnu_regex.dll" TO gnu_regex%
IF gnu_regex% = 0 ERROR 100, "Cannot load gnu_regex.dll"
SYS "GetProcAddress", gnu_regex%, "regcomp" TO regcomp
SYS "GetProcAddress", gnu_regex%, "regexec" TO regexec
DIM regmatch{start%, finish%}, buffer% 256
REM Find all 'words' ... |
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
... | #Agda | Agda | module reverse_string where
open import Data.String
open import Data.List
reverse_string : String → String
reverse_string s = fromList (reverse (toList s)) |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #PicoLisp | PicoLisp | (de rendezvous (Pid . Exe)
(when
(catch '(NIL)
(tell Pid 'setq 'Rendezvous (lit (eval Exe)))
NIL )
(tell Pid 'quit @) ) ) # Raise caught error in caller |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Python | Python | """An approximation of the rendezvous pattern found in Ada using asyncio."""
from __future__ import annotations
import asyncio
import sys
from typing import Optional
from typing import TextIO
class OutOfInkError(Exception):
"""Exception raised when a printer is out of ink."""
class Printer:
def __in... |
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.
| #Cowgol | Cowgol | include "cowgol.coh";
# Only functions that implement an interface can be passed around
# The interface is a type and must be defined before it is used
# This defines an interface for a function that takes no arguments
interface Fn();
# This function repeats a function that implements Fn
sub Repeat(f: Fn, n: uint32... |
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.
| #D | D | void repeat(void function() fun, in uint times) {
foreach (immutable _; 0 .. times)
fun();
}
void procedure() {
import std.stdio;
"Example".writeln;
}
void main() {
repeat(&procedure, 3);
} |
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... | #C.2B.2B | C++ | #include <cstdio>
int main()
{
std::rename("input.txt", "output.txt");
std::rename("docs", "mydocs");
std::rename("/input.txt", "/output.txt");
std::rename("/docs", "/mydocs");
return 0;
} |
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... | #Clipper | Clipper | FRename( "input.txt","output.txt")
or
RENAME input.txt TO output.txt
FRename("\input.txt","\output.txt")
or
RENAME \input.txt TO \output.txt |
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
| #Python | Python | DIFF_THRESHOLD = 1e-40
class Fixed:
FREE = 0
A = 1
B = 2
class Node:
__slots__ = ["voltage", "fixed"]
def __init__(self, v=0.0, f=Fixed.FREE):
self.voltage = v
self.fixed = f
def set_boundary(m):
m[1][1] = Node( 1.0, Fixed.A)
m[6][7] = Node(-1.0, Fixed.B)
def calc_dif... |
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... | #EchoLisp | EchoLisp |
(define S #<<
---------- 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 -----------------------
>>#)
(for-each writeln
(for/list ((line (string-sp... |
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... | #PL.2FI | PL/I |
rotate: procedure (in) options (main); /* 2 March 2011 */
declare in character (100) varying;
declare line character (500) varying;
declare input file;
open file (input) title ('/' || in || ',type(text),recsize(500)' );
on endfile (input) stop;
do forever;
get file (input) edit (line)... |
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... | #Perl | Perl | my @symbols = ( [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'] );
sub roman {
my($n, $r) = (shift, '');
($r, $n) = ('-', -$n) if $n < 0; # Optional handling of negative input
foreach my $s (@symbols) {
m... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Racket | Racket | #lang racket
(define (decode/roman number)
(define letter-values
(map cons '(#\M #\D #\C #\L #\X #\V #\I) '(1000 500 100 50 10 5 1)))
(define (get-value letter)
(cdr (assq letter letter-values)))
(define lst (map get-value (string->list number)))
(+ (last lst)
(for/fold ((sum 0))
((i (in-lis... |
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... | #BaCon | BaCon | DOTIMES 5
s$ = s$ & "ha"
DONE
PRINT s$ |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Dyalect | Dyalect | func divRem(x, y) {
(x / y, x % y)
} |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | function-returning-multiple-values:
10 20
!print !print function-returning-multiple-values
|
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
... | #Action.21 | Action! | INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC RemoveDuplicates(INT ARRAY src INT srcLen
INT ARRAY dst INT POINTER dstLen)
INT i
CHAR curr,prev
... |
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.
| #Clojure | Clojure |
; Including listing private methods in the clojure.set namespace:
=> (keys (ns-interns 'clojure.set))
(union map-invert join select intersection superset? index bubble-max-key subset? rename rename-keys project difference)
; Only public:
=> (keys (ns-publics 'clojure.set))
(union map-invert join select intersectio... |
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.
| #D | D | struct S {
bool b;
void foo() {}
private void bar() {}
}
class C {
bool b;
void foo() {}
private void bar() {}
}
void printMethods(T)() if (is(T == class) || is(T == struct)) {
import std.stdio;
import std.traits;
writeln("Methods of ", T.stringof, ":");
foreach (m; __t... |
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.
| #J | J | import java.lang.reflect.Field;
public class ListFields {
public int examplePublicField = 42;
private boolean examplePrivateField = true;
public static void main(String[] args) throws IllegalAccessException {
ListFields obj = new ListFields();
Class clazz = obj.getClass();
Syst... |
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.
| #Java | Java | import java.lang.reflect.Field;
public class ListFields {
public int examplePublicField = 42;
private boolean examplePrivateField = true;
public static void main(String[] args) throws IllegalAccessException {
ListFields obj = new ListFields();
Class clazz = obj.getClass();
Syst... |
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... | #BASIC | BASIC | 10 DEFINT I: DEFSTR S,T
20 READ S: IF S="" THEN END
30 IF LEN(S)<2 THEN 80 ELSE FOR I = LEN(S)\2 TO 1 STEP -1
40 T = ""
50 IF LEN(T)<LEN(S) THEN T=T+LEFT$(S,I): GOTO 50
60 IF LEFT$(T,LEN(S))=S THEN PRINT S;": ";LEFT$(S,I): GOTO 20
70 NEXT I
80 PRINT S;": none"
90 GOTO 20
100 DATA "1001110011","1110111011"
110 DATA "001... |
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... | #BCPL | BCPL | get "libhdr"
// Returns the length of the longest rep-string
// (0 if there are none)
let repstring(s) = valof
$( for i = s%0/2 to 1 by -1 do
$( for j = 1 to i
$( let k = i
while j+k <= s%0 do
$( unless s%(j+k)=s%j goto next
k := k + i
$)
$) ... |
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.
| #Nim | Nim | import macros, strformat
proc f(arg: int): int = arg+1
macro getSource(source: static[string]) =
let module = parseStmt(source)
for node in module.children:
if node.kind == nnkProcDef:
echo(&"source of procedure {node.name} is:\n{toStrLit(node).strVal}")
proc g(arg: float): float = arg*arg
getSour... |
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.
| #Perl | Perl | # 20211213 Perl programming solution
use strict;
use warnings;
use Class::Inspector;
print Class::Inspector->resolved_filename( 'IO::Socket::INET' ), "\n";
|
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.
| #Phix | Phix | {"C:\\Program Files (x86)\\Phix\\builtins\\",
"C:\\Program Files (x86)\\Phix\\builtins\\VM\\",
"C:\\Program Files (x86)\\Phix\\"}
|
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.
| #Python | Python | import os
os.__file__
# "/usr/local/lib/python3.5/os.pyc"
|
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.
| #Raku | Raku | say &sum.file;
say Date.^find_method("day-of-week").file; |
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.
| #REXX | REXX | /*REXX program gets the source function (source code) and */
/*───────────────────────── displays the number of lines. */
#=sourceline()
do j=1 for sourceline()
say 'line' right(j, length(#) ) '──►' ,
strip( sourceline(j), 'T')
end /*j*/... |
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
| #Bracmat | Bracmat | @("fesylk789/35768poq2art":? (#<7:?n & out$!n & ~) ?) |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Brat | Brat | str = "I am a string"
true? str.match(/string$/)
{ p "Ends with 'string'" }
false? str.match(/^You/)
{ p "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
... | #Aime | Aime | o_(b_reverse("Hello, World!"), "\n"); |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Racket | Racket |
#lang racket
;;; Rendezvous primitives implemented in terms of synchronous channels.
(define (send ch msg)
(define handshake (make-channel))
(channel-put ch (list msg handshake))
(channel-get handshake)
(void))
(define (receive ch action)
(match-define (list msg handshake) (channel-get ch))
(action ms... |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Raku | Raku | class X::OutOfInk is Exception {
method message() { "Printer out of ink" }
}
class Printer {
has Str $.id;
has Int $.ink = 5;
has Lock $!lock .= new;
has ::?CLASS $.fallback;
method print ($line) {
$!lock.protect: {
if $!ink { say "$!id: $line"; $!in... |
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.
| #Delphi | Delphi |
program Repeater;
{$APPTYPE CONSOLE}
{$R *.res}
type
TSimpleProc = procedure; // Can also define types for procedures (& functions) which
// require params.
procedure Once;
begin
writeln('Hello World');
end;
procedure Iterate(proc : TSimpleProc; Iterations : integer);
va... |
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... | #Clojure | Clojure | (import '(java.io File))
(.renameTo (File. "input.txt") (File. "output.txt"))
(.renameTo (File. "docs") (File. "mydocs"))
(.renameTo
(File. (str (File/separator) "input.txt"))
(File. (str (File/separator) "output.txt")))
(.renameTo
(File. (str (File/separator) "docs"))
(File. (str (File/separator) "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... | #Common_Lisp | Common Lisp | (rename-file "input.txt" "output.txt")
(rename-file "docs" "mydocs")
(rename-file "/input.txt" "/output.txt")
(rename-file "/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
| #Racket | Racket | #lang racket
(require racket/flonum)
(define-syntax-rule (fi c t f) (if c f t))
(define (neighbours w h)
(define h-1 (sub1 h))
(define w-1 (sub1 w))
(lambda (i j)
(+ (fi (zero? i) 1 0)
(fi (zero? j) 1 0)
(if (< i h-1) 1 0)
(if (< j w-1) 1 0))))
(define (mesh-R probes w h)
(define ... |
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... | #Elena | Elena | import extensions;
import system'routines;
public program()
{
var text := new string[]{"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
... |
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... | #Elixir | Elixir | defmodule RC do
def reverse_words(txt) do
txt |> String.split("\n") # split lines
|> Enum.map(&( # in each line
&1 |> String.split # split words
|> Enum.reverse # reverse words
|> Enum.join(" "))) # rejoin words
|> Enum.... |
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... | #PL.2FSQL | PL/SQL | -- Works for VARCHAR2 (up to 32k chars)
CREATE OR REPLACE FUNCTION fn_rot13_native(p_text VARCHAR2) RETURN VARCHAR2 IS
c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';
BEGIN
RETURN TR... |
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... | #Phix | Phix | function toRoman(integer v)
constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"},
decml = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
string res = ""
integer val = v
for i=1 to length(roman) do
while val>=decml[i] do
res &=... |
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... | #Raku | Raku | sub rom-to-num($r) {
[+] gather $r.uc ~~ /
^
[
| M { take 1000 }
| CM { take 900 }
| D { take 500 }
| CD { take 400 }
| C { take 100 }
| XC { take 90 }
| L { take 50 }
| XL { take 40 }
| X { take 10 }
| IX { take 9 ... |
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... | #BASIC | BASIC | function StringRepeat$ (s$, n)
cad$ = ""
for i = 1 to n
cad$ += s$
next i
return cad$
end function
print StringRepeat$("rosetta", 1)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
end |
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... | #Batch_File | Batch File | @echo off
if "%2" equ "" goto fail
setlocal enabledelayedexpansion
set char=%1
set num=%2
for /l %%i in (1,1,%num%) do set res=!res!%char%
echo %res%
:fail |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #EchoLisp | EchoLisp |
(define (plus-minus x y)
(values (+ x y) (- x y)))
(plus-minus 3 4)
→ 7
-1
(define (plus-minus x y)
(list (+ x y) (- x y)))
(plus-minus 3 4)
→ (7 -1)
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #ECL | ECL | MyFunc(INTEGER i1,INTEGER i2) := FUNCTION
RetMod := MODULE
EXPORT INTEGER Add := i1 + i2;
EXPORT INTEGER Prod := i1 * i2;
END;
RETURN RetMod;
END;
//Reference each return value separately:
MyFunc(3,4).Add;
MyFunc(3,4).Prod;
|
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
... | #Ada | Ada | with Ada.Containers.Ordered_Sets, Ada.Text_IO;
use Ada.Text_IO;
procedure Duplicate is
package Int_Sets is new Ada.Containers.Ordered_Sets (Integer);
Nums : constant array (Natural range <>) of Integer := (1,2,3,4,5,5,6,7,1);
Unique : Int_Sets.Set;
begin
for n of Nums loop
Unique.Include (n);
end loop;
for e... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #11l | 11l | :start:
V l = File(:argv[1]).read_lines()
l.del(Int(:argv[2]) - 1 .+ Int(:argv[3]))
File(:argv[1], ‘w’).write(l.join("\n")) |
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... | #AutoHotkey | AutoHotkey | name := "sample"
waitsec := 5
Tooltip Recording %name%.wav
MCI_SendString("close all wait")
MCI_SendString("open new type waveaudio alias " . name)
MCI_SendString("set " . name . " time format ms wait")
;MCI_SendString("set " . name . " bitspersample 16 wait")
;MCI_SendString("set " . name . " channels 1 wait")
;MCI_Se... |
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.
| #Elena | Elena | import system'routines;
import system'dynamic;
import extensions;
class MyClass
{
myMethod1() {}
myMethod2(x) {}
}
public program()
{
var o := new MyClass();
o.__getClass().__getMessages().forEach:(p)
{
console.printLine("o.",p)
}
} |
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.
| #Factor | Factor | USING: io math prettyprint see ;
"The list of methods contained in the generic word + :" print
\ + methods . nl
"The list of methods specializing on the fixnum class:" print
fixnum methods . |
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.
| #Frink | Frink | a = new array
methods[a] |
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.
| #JavaScript | JavaScript | var obj = Object.create({
name: 'proto',
proto: true,
doNothing: function() {}
}, {
name: {value: 'obj', writable: true, configurable: true, enumerable: true},
obj: {value: true, writable: true, configurable: true, enumerable: true},
'non-enum': {value: 'non-enumerable', writable: true, enumer... |
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.
| #jq | jq |
# Use jq's built-ins to generate a (recursive) synopsis of .
def synopsis:
if type == "boolean" then "Type: \(type)"
elif type == "object"
then "Type: \(type) length:\(length)",
(keys_unsorted[] as $k
| "\($k): \(.[$k] | synopsis )")
else "Type: \(type) length: \(length)"
end;
true, null, [1,2], {"a"... |
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... | #Bracmat | Bracmat | ( ( rep-string
= reps L x y
. ( reps
= x y z
. !arg:(?x.?y)
& ( @(!y:!x ?z)&reps$(!x.!z)
| @(!x:!y ?)
)
)
& ( :?L
& @( !arg
: %?x
!x
( ?y
& reps$(!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... | #BQN | BQN | # Returns a list of all rep-strings
Reps←(⌊≠÷2˙)((⊣≥≠¨∘⊢)/⊢)(<≡¨≠⥊¨1↓↑)/1↓↑
# Tests
tests←⟨
"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101",
"0100100", "101", "11", "00", "1"
⟩
∾´{ 𝕩∾':'∾(•Fmt Reps 𝕩)∾@+10 }¨tests |
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.
| #Ring | Ring |
# Project : Reflection/Get source
fp = fopen("C:\Ring\applications\fifteenpuzzle\CalmoSoftFifteenPuzzleGame.ring","r")
r = ""
str = ""
flag = 0
numline = 0
see "give the function: "
give funct
funct = "func " + funct
while isstring(r)
r = fgetc(fp)
if r = char(10)
flag = 1
num... |
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.
| #Ruby | Ruby | require 'mathn'
Math.method(:sqrt).source_location
# ["/usr/local/lib/ruby2.3/2.3.0/mathn.rb", 119]
Class.method(:nesting).source_location
# nil, since Class#nesting is native
|
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.
| #Smalltalk | Smalltalk | mthd := someClass compiledMethodAt:#nameOfMethod |
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.
| #Tcl | Tcl | proc getproc {name} {
set name [uplevel 1 [list namespace which -command $name]]
set args [info args $name]
set args [lmap arg $args { ;# handle default arguments, if it has them!
if {[info default $name $arg default]} {
list $name $default
} else {
return -level 0 $... |
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 | C | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
int main()
{
regex_t preg;
regmatch_t substmatch[1];
const char *tp = "string$";
const char *t1 = "this is a matching string";
const char *t2 = "this is not a matching string!";
const char *ss = "ist... |
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
... | #ALGOL_68 | ALGOL 68 | PROC reverse = (REF STRING s)VOID:
FOR i TO UPB s OVER 2 DO
CHAR c = s[i];
s[i] := s[UPB s - i + 1];
s[UPB s - i + 1] := c
OD;
main:
(
STRING text := "Was it a cat I saw";
reverse(text);
print((text, new line))
) |
http://rosettacode.org/wiki/Rendezvous | Rendezvous | Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
| #Tcl | Tcl | package require Tcl 8.6
package require Thread
# Really ought to go in a package
eval [set rendezvousEngine {
array set Select {w {} c 0}
# Turns the task into a coroutine, making it easier to write in "Ada style".
# The real thread ids are stored in shared variables.
proc task {id script} {
global rendezvousEn... |
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.
| #EchoLisp | EchoLisp |
(define (repeat f n) (for ((i n)) (f)))
(repeat (lambda () (write (random 1000))) 5)
→ 287 798 930 989 794
;; Remark
;; It is also possible to iterate a function : f(f(f(f( ..(f x)))))
(define cos10 (iterate cos 10)
(define cos100 (iterate cos10 10))
(cos100 0.6)
→ 0.7390851332151605
(cos 0.739085133215... |
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.
| #F.23 | F# | open System
let Repeat c f =
for _ in 1 .. c do
f()
let Hello _ =
printfn "Hello world"
[<EntryPoint>]
let main _ =
Repeat 3 Hello
0 // return an integer exit code |
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... | #D | D | std.file.rename("input.txt","output.txt");
std.file.rename("/input.txt","/output.txt");
std.file.rename("docs","mydocs");
std.file.rename("/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... | #DBL | DBL | XCALL RENAM ("output.txt","input.txt")
.IFDEF UNIX
XCALL SPAWN ("mv docs mydocs")
.ENDC
.IFDEF DOS
XCALL SPAWN ("ren docs mydocs")
.ENDC
.IFDEF VMS
XCALL SPAWN ("rename docs.dir mydocs.dir")
.ENDC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.