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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#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. uniqpage: equ 3 ; Page to use - a compile-time constant. ; This would need to be set to a page that ; the rest of the program doesn't need. uniq: xra a ; Zero out the page lxi d,uniqpage * 256 uniqzero: stax d ; Zero out a byte inr e ; And do the next byte jnz uniqzero mov d,h ; Keep a second pointer to the array in DE mov e,l uniqpos: ldax d ; Read from high pointer mov m,a ; Write to low pointer inx d ; Increment the high pointer push h ; Keep low pointer around mvi h,uniqpage mov l,a ; Have we seen this byte yet? cmp m mov m,a ; No matter what, we've certainly seen it now pop h ; Bring back the low pointer jz uniqno ; If we already had it, don't increment low ptr inx h ; IF we didn't, do increment it uniqno: dcx b ; One fewer byte left mov a,b ; If there are zero bytes left, ora c rz ; Then return to caller jmp uniqpos ; Otherwise, do the next byte ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Testing code: read a string from the CP/M console, run ;; uniq, then print the output. test: lxi d,bufdef ; Read a string mvi c,10 call 5 lxi d,nl ; Output on new line mvi c,9 call 5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; lda bufdef+1 ; Length of input string mov c,a ; Extend to 16-bit (since uniq supports mvi b,0 ; long arrays) lxi h,buf ; Location of input string call uniq ; Only the unique bytes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mvi m,'$' ; Mark the (string) end with '$' lxi d,buf ; Print the string, which now has had mvi c,9 ; all duplicates removed. jmp 5 nl: db 13,10,'$' bufdef: db 127,0 buf:
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 Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 != SubStr(s, !pos ? i : pos, 1)) continue, 2 } return SubStr(s, 1, i) } return "N/A" }
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() { Throwable t = new Throwable(); for ( StackTraceElement ste : t.getStackTrace() ) { System.out.printf("File Name = %s%n", ste.getFileName()); System.out.printf("Class Name = %s%n", ste.getClassName()); System.out.printf("Method Name = %s%n", ste.getMethodName()); System.out.printf("Line number = %s%n%n", ste.getLineNumber()); } }   }  
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Put_Line (Reverse_It (Get_Line)); end Reverse_String;
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 printers[p][INK]!=0 then printers[p][INK] -= 1 printf(1,"%s/%s: %s\n",{name,printers[p][NAME],s[i]}) exit elsif p=length(printers) then throw("out of ink") end if end for leave_cs(print_cs) end for exit_thread(0) catch e printf(1,"exception(%s): %s\n",{name,e[E_USER]}) leave_cs(print_cs) exit_thread(1) end try end procedure constant hd = {"Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men", "Couldn't put Humpty together again."}, mg = {"Old Mother Goose", "When she wanted to wander,", "Would ride through the air", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon."} sequence hThreads = {create_thread(printer,{"hd",hd}), create_thread(printer,{"mg",mg})} wait_thread(hThreads)
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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 c = 0 if i<ni then c += 1; A[k,k+nj] = -1 end if if i>1 then c += 1; A[k,k-nj] = -1 end if if j<nj then c += 1; A[k,k+1] = -1 end if if j>1 then c += 1; A[k,k-1] = -1 end if A[k,k] = c end if end for end for k = (bi-1)*nj +bj B[k,1] = 1 A = inverse(A) B = matrix_mul(A,B) return B[k,1] end function printf(1,"Resistance = %.13f ohms\n",resistormesh(10, 10, 2, 2, 8, 7))
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#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+ 'fire. favor who those with hold I'+sLineBreak+ sLineBreak+ '... elided paragraph last ...'+sLineBreak+ sLineBreak+ 'Frost Robert -----------------------'+sLineBreak;   var i, w: Integer; d: TStringDynArray; begin with TStringList.Create do try Text := TXT; for i := 0 to Count - 1 do begin d := SplitString(Strings[i], #32); Strings[i] := ''; for w := Length(d) - 1 downto 0 do Strings[i] := Strings[i] + #32 + d[w]; end; Writeln(Text); finally Free end; ReadLn; end.
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#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 decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#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(digits)] < digits[-1L]) digits[smaller] <- - digits[smaller] } sum(digits) } vapply(rSplit, toArabic, integer(1)) }
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#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.DeclaredOnly;   foreach (var method in typeof(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); }   class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {}   public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} }   }
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 Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
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 public fields (including inherited):" (clazz.fields).each { Field f -> printf "%s\t%s\n", f, f.get(obj) } println()   println "All declared fields (excluding inherited):" clazz.getDeclaredFields().each { Field f -> f.accessible = true printf "%s\t%s\n", f, f.get(obj) } } }
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 "Repeating string: ", word$, " -> ", HEAD$(ex$, 1) CONTINUE 2 NEXT   PRINT "Not a repeating string: ", word$ NEXT
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   ---------------------------------------- -- Returns the source code of the movie script that defines the specified global function -- @param {symbol} func - function specified as symbol -- @return {string|VOID} ---------------------------------------- on getGlobalFunctionCode (func) -- iterate over all members in all castlibs repeat with i = 1 to _movie.castlib.count repeat with j = 1 to _movie.castlib[i].member.count m = _movie.castlib[i].member[j] if m.type<>#script then next repeat if m.scriptType=#movie and m.script.handler(func) then return m.script.text end repeat end repeat 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' in a string: teststr$ = "I love PATTERN matching!" pattern$ = "([a-zA-Z]+)"   SYS regcomp, buffer%, pattern$, 1 TO result% IF result% ERROR 101, "Failed to compile regular expression"   first% = 1 REPEAT SYS regexec, buffer%, MID$(teststr$, first%), 1, regmatch{}, 0 TO result% IF result% = 0 THEN s% = regmatch.start% f% = regmatch.finish% PRINT "<" MID$(teststr$, first%+s%, f%-s%) ">" first% += f% ENDIF UNTIL result%   REM Replace 'PATTERN' with 'pattern': teststr$ = "I love PATTERN matching!" pattern$ = "(PATTERN)"   SYS regcomp, buffer%, pattern$, 1 TO result% IF result% ERROR 101, "Failed to compile regular expression" SYS regexec, buffer%, teststr$, 1, regmatch{}, 0 TO result% IF result% = 0 THEN s% = regmatch.start% f% = regmatch.finish% MID$(teststr$, s%+1, f%-s%) = "pattern" PRINT teststr$ ENDIF   SYS "FreeLibrary", gnu_regex%
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup   self.ink_level: int = 5 self.output_stream: TextIO = sys.stdout   async def print(self, msg): if self.ink_level <= 0: if self.backup: await self.backup.print(msg) else: raise OutOfInkError(self.name) else: self.ink_level -= 1 self.output_stream.write(f"({self.name}): {msg}\n")     async def main(): reserve = Printer("reserve", None) main = Printer("main", reserve)   humpty_lines = [ "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again.", ]   goose_lines = [ "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", ]   async def print_humpty(): for line in humpty_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Humpty Dumpty out of ink!") break   async def print_goose(): for line in goose_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Mother Goose out of ink!") break   await asyncio.gather(print_goose(), print_humpty())     if __name__ == "__main__": asyncio.run(main(), debug=True)
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) is while n != 0 loop f(); n := n - 1; end loop; end sub;   # Here is a function sub Foo implements Fn is print("foo "); end sub;   # Prints "foo foo foo foo" Repeat(Foo, 4); print_nl();
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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_difference(m, d): h = len(m) w = len(m[0]) total = 0.0   for i in xrange(h): for j in xrange(w): v = 0.0 n = 0 if i != 0: v += m[i-1][j].voltage; n += 1 if j != 0: v += m[i][j-1].voltage; n += 1 if i < h-1: v += m[i+1][j].voltage; n += 1 if j < w-1: v += m[i][j+1].voltage; n += 1 v = m[i][j].voltage - v / n   d[i][j].voltage = v if m[i][j].fixed == Fixed.FREE: total += v ** 2 return total   def iter(m): h = len(m) w = len(m[0]) difference = [[Node() for j in xrange(w)] for i in xrange(h)]   while True: set_boundary(m) # Enforce boundary conditions. if calc_difference(m, difference) < DIFF_THRESHOLD: break for i, di in enumerate(difference): for j, dij in enumerate(di): m[i][j].voltage -= dij.voltage   cur = [0.0] * 3 for i, di in enumerate(difference): for j, dij in enumerate(di): cur[m[i][j].fixed] += (dij.voltage * (bool(i) + bool(j) + (i < h-1) + (j < w-1)))   return (cur[Fixed.A] - cur[Fixed.B]) / 2.0   def main(): w = h = 10 mesh = [[Node() for j in xrange(w)] for i in xrange(h)] print "R = %.16f" % (2 / iter(mesh))   main()
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#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-split S "\n"))) (string-join (reverse (string-split line " ")) " ")))  
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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) (L); line = translate ( line, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'); put edit (line) (a); put skip; end; end;  
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#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) { my($arabic, $roman) = @$s; ($r, $n) = ($r .= $roman x int($n/$arabic), $n % $arabic) if $n >= $arabic; } $r; }   say roman($_) for 1..2012;
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 decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#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-list lst)) (i+1 (in-list (cdr lst)))) (+ sum (if (> i+1 i) (- i) i)))))   (map decode/roman '("MCMXC" "MMVIII" "MDCLXVI")) ;-> '(1990 2008 1666)
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#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   IF srcLen=0 THEN dstLen^=0 RETURN FI   SortI(src,srcLen,0) dst(0)=src(0) dstLen^=1 prev=src(0) FOR i=1 TO srcLen-1 DO curr=src(i) IF curr#prev THEN dst(dstLen^)=curr dstLen^==+1 FI prev=curr OD RETURN   PROC Test(INT ARRAY src INT srcLen) INT ARRAY dst(100) INT dstLen   PrintE("Input array:") PrintArray(src,srcLen) RemoveDuplicates(src,srcLen,dst,@dstLen) PrintE("Unique items:") PrintArray(dst,dstLen) PutE() RETURN   PROC Main() INT ARRAY src1(9)=[1 3 65534 0 12 1 65534 52 3] INT ARRAY src2(26)=[3 2 1 3 2 5 2 1 6 3 4 2 5 3 1 5 3 5 2 1 3 7 4 5 7 6] INT ARRAY src3(1)=[6502]   Put(125) PutE() ;clear screen Test(src1,9) Test(src2,26) Test(src3,1) RETURN
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 intersection superset? index subset? rename rename-keys project difference)
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; __traits(allMembers, T)) { static if (__traits(compiles, (typeof(__traits(getMember, T, m))))) { alias typeof(__traits(getMember, T, m)) ti; static if (isFunction!ti) { writeln(" ", m); } } } }   void main() { printMethods!S; printMethods!C; }
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();   System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
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();   System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 "0010010010","1010101010" 120 DATA "1111111111","0100101101" 130 DATA "0100100","101" 140 DATA "11","00" 150 DATA "1",""
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 $) $) resultis i next: loop $) resultis 0 $)   // Print first N characters of string let writefirst(s, n) be $( let x = s%0 s%0 := n writes(s) s%0 := x $)   // Test string let rep(s) be $( let n = repstring(s) writef("%S: ",s) test n=0 do writes("none") or writefirst(s,n) wrch('*N') $)   let start() be $( rep("1001110011") rep("1110111011") rep("0010010010") rep("1010101010") rep("1111111111") rep("0100101101") rep("0100100") rep("101") rep("11") rep("00") rep("1") $)
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   getSource(staticRead(currentSourcePath()))
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*/ say parse source x y sID say 'The name of the source file (program) is: ' sID say 'The number of lines in the source program: ' # /*stick a fork in it, we're all done.*/
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 msg) (channel-put handshake 'done))   ;;; A printer receives a line of text, then ;;; - prints it (still ink left) ;;; - sends it to the backup printer (if present) ;;; - raises exception (if no ink and no backup) (define (printer id ink backup) (define (on-line-received line) (cond [(and (= ink 0) (not backup)) (raise 'out-of-ink)] [(= ink 0) (send backup line)] [else (display (~a id ":")) (for ([c line]) (display c)) (newline)])) (define ch (make-channel)) (thread (λ () (let loop () (receive ch on-line-received) (set! ink (max 0 (- ink 1))) (loop)))) ch)   ;;; Setup two printers   (define reserve (printer "reserve" 5 #f)) (define main (printer "main" 5 reserve))   ;;; Two stories   (define humpty '("Humpty Dumpty sat on a wall." "Humpty Dumpty had a great fall." "All the king's horses and all the king's men," "Couldn't put Humpty together again."))   (define goose '("Old Mother Goose," "When she wanted to wander," "Would ride through the air," "On a very fine gander." "Jack's mother came in," "And caught the goose soon," "And mounting its back," "Flew up to the moon."))   ;;; Print the stories (for ([l humpty]) (send main l)) (for ([l goose]) (send main l))  
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"; $!ink-- } elsif $!fallback { $!fallback.print: $line } else { die X::OutOfInk.new } } } }   my $printer = Printer.new: id => 'main', fallback => Printer.new: id => 'reserve';   sub client ($id, @lines) { start { for @lines { $printer.print: $_; CATCH { when X::OutOfInk { note "<$id stops for lack of ink>"; exit } } } note "<$id is done>"; } }   await client('Humpty', q:to/END/.lines), Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall. All the king's horses and all the king's men, Couldn't put Humpty together again. END client('Goose', q:to/END/.lines); Old Mother Goose, When she wanted to wander, Would ride through the air, On a very fine gander. Jack's mother came in, And caught the goose soon, And mounting its back, Flew up to the moon. END
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); var i : integer; begin for i := 1 to Iterations do proc; end;   begin Iterate(Once, 3); readln; end.    
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type systems, only the user root would have sufficient permissions in the filesystem root.)
#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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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 h-1 (sub1 h)) (define w-1 (sub1 w))   (define-syntax-rule (v2ref v r c) ; 2D vector ref (flvector-ref v (+ (* r w) c)))   (define w*h (* w h))   (define (alloc2 (v 0.)) (make-flvector w*h v))   (define nghbrs (neighbours w h))   (match-define `((,fix+r ,fix+c) (,fix-r ,fix-c)) probes) (define fix+idx (+ fix+c (* fix+r w))) (define fix-idx (+ fix-c (* fix-r w))) (define fix-val (match-lambda** [((== fix+idx) _) 1.] [((== fix-idx) _) -1.] [(_ v) v]))   (define (calc-diff m) (define d (for*/flvector #:length w*h ((i (in-range h)) (j (in-range w))) (define v (+ (fi (zero? i) (v2ref m (- i 1) j) 0) (fi (zero? j) (v2ref m i (- j 1)) 0) (if (< i h-1) (v2ref m (+ i 1) j) 0) (if (< j w-1) (v2ref m i (+ j 1)) 0))) (- (v2ref m i j) (/ v (nghbrs i j)))))   (define Δ (for/sum ((i (in-naturals)) (d.v (in-flvector d)) #:when (= (fix-val i 0.) 0.)) (sqr d.v)))   (values d Δ))   (define final-d (let loop ((m (alloc2)) (d (alloc2))) (define m+ ; do this first will get the boundaries on (for/flvector #:length w*h ((j (in-naturals)) (m.v (in-flvector m)) (d.v (in-flvector d))) (fix-val j (- m.v d.v))))   (define-values (d- Δ) (calc-diff m+))   (if (< Δ 1e-24) d (loop m+ d-))))   (/ 2 (/ (- (* (v2ref final-d fix+r fix+c) (nghbrs fix+r fix+c)) (* (v2ref final-d fix-r fix-c) (nghbrs fix-r fix-c))) 2)))   (module+ main (printf "R = ~a~%" (mesh-R '((1 1) (6 7)) 10 10)))
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#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", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------"};   text.forEach:(line) { line.splitBy:" ".sequenceReverse().forEach:(word) { console.print(word," ") }; console.writeLine() } }
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);   the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result. Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) Input data (ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝ Cf. Phrase reversals
#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.join("\n") # rejoin lines end end
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 input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input." (A number of UNIX scripting languages and utilities, such as   awk   and   sed   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python). The   rot-13   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material. Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   z   to   a   as necessary). Thus the letters   abc   become   nop   and so on. Technically rot-13 is a   "mono-alphabetic substitution cipher"   with a trivial   "key". A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration. Related tasks   Caesar cipher   Substitution Cipher   Vigenère Cipher/Cryptanalysis Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 TRANSLATE(p_text, c_source, c_target); END; /   -- For CLOBs (translate only works with VARCHAR2, so do it in chunks) CREATE OR REPLACE FUNCTION fn_rot13_clob(p_text CLOB) RETURN CLOB IS c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'; c_chunk_size CONSTANT PLS_INTEGER := 4000; v_result CLOB := NULL; BEGIN FOR i IN 0..TRUNC(LENGTH(p_text) / c_chunk_size) LOOP v_result := v_result || TRANSLATE(DBMS_LOB.SUBSTR(p_text, c_chunk_size, i * c_chunk_size + 1), c_source, c_target); END LOOP; RETURN v_result; END; /   -- The full algorithm (Slower. And MUCH slower if using CLOB!) CREATE OR REPLACE FUNCTION fn_rot13_algorithm(p_text VARCHAR2) RETURN CLOB IS c_upper_a CONSTANT PLS_INTEGER := ASCII('A'); c_lower_a CONSTANT PLS_INTEGER := ASCII('a'); v_rot VARCHAR2(32000); v_char VARCHAR2(1); BEGIN FOR i IN 1..LENGTH(p_text) LOOP v_char := SUBSTR(p_text, i, 1); IF v_char BETWEEN 'A' AND 'Z' THEN v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_upper_a + 13, 26) + c_upper_a); ELSIF v_char BETWEEN 'a' AND 'z' THEN v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_lower_a + 13, 26) + c_lower_a); ELSE v_rot := v_rot || v_char; END IF; END LOOP; RETURN v_rot; 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 numerals: 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC 2008 is written as 2000=MM, 8=VIII; or MMVIII 1666 uses each Roman symbol in descending order: MDCLXVI
#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 &= roman[i] val -= decml[i] end while end for -- return res return {v,res} -- (for output) end function ?apply({1990,2008,1666},toRoman)
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 decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.
#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 } | V { take 5 } | IV { take 4 } | I { take 1 } ]+ $ /; }   say "$_ => &rom-to-num($_)" for <MCMXC MDCLXVI MMVIII>;
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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given an Array, derive a sequence of elements in which all duplicates are removed. There are basically three approaches seen here: Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user. Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting. Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
#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 of Unique loop Put (e'img); end loop; end Duplicate;
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 the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#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 might not record sound in the same format.)
#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_SendString("set " . name . " samplespersec 16000 wait") ;MCI_SendString("set " . name . " alignment 1 wait") ;MCI_SendString("set " . name . " bytespersec 8000 wait") MCI_SendString("record " . name) Sleep waitsec*1000 MCI_SendString("stop " . name . " wait") MCI_SendString("save " . name . " """ . name . ".wav""") Tooltip Finished ... Playing MCI_SendString("delete " . name) MCI_SendString("close " . name . " wait") MCI_SendString("open """ . name . ".wav"" type waveaudio alias " . name) MCI_SendString("play " . name . " wait") MCI_SendString("close " . name . " wait") Tooltip Return   MCI_SendString(p_lpszCommand,ByRef r_lpszReturnString="",p_hwndCallback=0) { VarSetCapacity(r_lpszReturnString,512,0) Return DllCall("winmm.dll\mciSendString" . (A_IsUnicode ? "W":"A") ,"Str",p_lpszCommand ;-- lpszCommand ,"Str",r_lpszReturnString ;-- lpszReturnString ,"UInt",512 ;-- cchReturn ,A_PtrSize ? "Ptr":"UInt",p_hwndCallback ;-- hwndCallback ,"Cdecl Int") ;-- Return type } ; For more intuitive functions, see the MCI library by jballi. ; doc: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.html ; download: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.ahk
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, enumerable: false}, doStuff: {value: function() {}, enumerable: true} });   // get enumerable properties on an object and its ancestors function get_property_names(obj) { var properties = []; for (var p in obj) { properties.push(p); } return properties; }   get_property_names(obj); //["name", "obj", "doStuff", "proto", "doNothing"]   Object.getOwnPropertyNames(obj); //["name", "obj", "non-enum", "doStuff"]   Object.keys(obj); //["name", "obj", "doStuff"]   Object.entries(obj); //[["name", "obj"], ["obj", true], ["doStuff", function()]]  
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": {"b": 3, "c": 4}, "x": "Rosetta Code"}, now | ("\n\(.) ::", synopsis)  
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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) & !x !L:?L & ~ ) ) |  !L: & out$(str$(!arg " is not a rep-string")) | out$(!arg ":" !L) ) ) & rep-string$1001110011 & rep-string$1110111011 & rep-string$0010010010 & rep-string$1010101010 & rep-string$1111111111 & rep-string$0100101101 & rep-string$0100100 & rep-string$101 & rep-string$11 & rep-string$00 & rep-string$1 );
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 example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string. Task Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice). There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 Show your output on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 numline = numline + 1 else flag = 0 str = str + r ok if flag = 1 if left(str,len(funct)) = funct see '"' + funct + '"' +" is in the line: " + numline + nl ok str = "" ok end fclose(fp)  
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 $arg } }] set body [info body $name] list proc $name $args $body }   puts [getproc getproc]
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 = "istyfied";   regcomp(&preg, "string$", REG_EXTENDED); printf("'%s' %smatched with '%s'\n", t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp); printf("'%s' %smatched with '%s'\n", t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp); regfree(&preg); /* change "a[a-z]+" into "istifyed"?*/ regcomp(&preg, "a[a-z]+", REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { //fprintf(stderr, "%d, %d\n", substmatch[0].rm_so, substmatch[0].rm_eo); char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf("mod string: '%s'\n", ns); free(ns); } else { printf("the string '%s' is the same: no matching!\n", t1); } regfree(&preg);   return 0; }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 rendezvousEngine set task [list coroutine RTask eval "$script;thread::exit"] tsv::set tasks $id [thread::create \ "$rendezvousEngine;$task;thread::wait"] }   # A simple yielding pause. proc pause t { after $t [info coroutine] yield }   # Wait for a message. Note that this is *not* pretty code and doesn't do # everything that the Ada rendezvous does. proc select args { global Select set var [namespace which -variable Select](m[incr Select(c)]) set messages {} foreach {message vars body} $args { dict set messages $message $body dict set bindings $message $vars } lappend Select(w) [list $var [dict keys $messages]] try { set Master "" while {$Master eq ""} { set Master [yield] } lassign $Master message responder payload foreach vbl [dict get $bindings $message] value $payload { upvar 1 $vbl v set v $value } set body [dict get $messages $message] set code [uplevel 1 [list catch $body ::Select(em) ::Select(op)]] set opts $Select(op) if {$code == 1} { dict append opts -errorinfo \ "\n while processing message\n$message $payload" } set $responder [list $code $Select(em) $opts] } finally { catch {unset $var} set Select(w) [lrange $Select(w) 0 end-1] } }   # This acts as a receiver for messages, feeding them into the waiting # [select]. It is incomplete as it should (but doesn't) queue messages that # can't be received currently. proc receive {message args} { global Select lassign [lindex $Select(w) end] var messages if {$message ni $messages} { throw BAD_MESSAGE "don't know message $message" } set responder [namespace which -variable Select](r[incr Select(c)]) set $responder "" RTask [list $message $responder $args] set response [set $responder] unset responder after 1 return $response }   # This dispatches a message to a task in another thread. proc send {target message args} { after 1 set t [tsv::get tasks $target] if {![thread::send $t [list receive $message {*}$args] response]} { lassign $response code msg opts return -options $opts $msg } else { return -code error $response } } }]   # The backup printer task. task BackupPrinter { set n 5 while {$n >= 0} { select Print msg { if {$n > 0} { incr n -1 puts Backup:$msg } else { throw OUT_OF_INK "out of ink" } } } }   # The main printer task. task MainPrinter { set n 5 set Backup BackupPrinter while 1 { select Print msg { try { if {$n > 0} { incr n -1 puts Main:$msg } elseif {$Backup ne ""} { send $Backup Print $msg } else { throw OUT_OF_INK "out of ink" } } trap OUT_OF_INK {} { set Backup "" throw OUT_OF_INK "out of ink" } } } }   # Tasks that generate messages to print. task HumptyDumpty { pause 100 try { send MainPrinter Print "Humpty Dumpty sat on a wall." send MainPrinter Print "Humpty Dumpty had a great fall." send MainPrinter Print "All the King's horses and all the King's men" send MainPrinter Print "Couldn't put Humpty together again." } trap OUT_OF_INK {} { puts "Humpty Dumpty out of ink!" } } task MotherGoose { pause 100 try { send MainPrinter Print "Old Mother Goose" send MainPrinter Print "When she wanted to wander," send MainPrinter Print "Would ride through the air" send MainPrinter Print "On a very fine gander." send MainPrinter Print "Jack's mother came in," send MainPrinter Print "And caught the goose soon," send MainPrinter Print "And mounting its back," send MainPrinter Print "Flew up to the moon." } trap OUT_OF_INK {} { puts "Mother Goose out of ink!" } }   # Wait enough time for the example to run and then finish after 1000 thread::broadcast thread::exit
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.7390851332151605) → 0.7390851332151608 ;; fixed point found  
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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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 systems, only the user root would have sufficient permissions in the filesystem root.)
#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