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/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
#Pike
Pike
import String; int main(){ write(int2roman(2009) + "\n"); write(int2roman(1666) + "\n"); write(int2roman(1337) + "\n"); }
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.
#Run_BASIC
Run BASIC
print "MCMXCIX = "; romToDec( "MCMXCIX") '1999 print "MDCLXVI = "; romToDec( "MDCLXVI") '1666 print "XXV = "; romToDec( "XXV") '25 print "CMLIV = "; romToDec( "CMLIV") '954 print "MMXI = "; romToDec( "MMXI") '2011   function romToDec(roman$) for i = len(roman$) to 1 step -1 x$ = mid$(roman$, i, 1) n = 0 if x$ = "M" then n = 1000 if x$ = "D" then n = 500 if x$ = "C" then n = 100 if x$ = "L" then n = 50 if x$ = "X" then n = 10 if x$ = "V" then n = 5 if x$ = "I" then n = 1   if n < preNum then num = num - n else num = num + n preNum = n next   romToDec =num end function
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
#Brat
Brat
p "ha" * 5 #Prints "hahahahaha"
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
#Burlesque
Burlesque
  blsq ) 'h5?* "hhhhh" blsq ) "ha"5.*\[ "hahahahaha"  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#F.23
F#
let addSub x y = x + y, x - y   let sum, diff = addSub 33 12 printfn "33 + 12 = %d" sum printfn "33 - 12 = %d" diff
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Factor
Factor
USING: io kernel math prettyprint ; IN: script   : */ ( x y -- x*y x/y ) [ * ] [ / ] 2bi ;   15 3 */   [ "15 * 3 = " write . ] [ "15 / 3 = " write . ] bi*
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).
#AppleScript
AppleScript
unique({1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"})   on unique(x) set R to {} repeat with i in x if i is not in R then set end of R to i's contents end repeat return R end unique
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#ALGOL_W
ALGOL W
begin  % calculate Recaman's sequence values  %    % a hash table element - holds n, A(n) and a link to the next element with the  %  % same hash value  % record AValue ( integer eN, eAn ; reference(AValue) eNext );    % hash modulus  % integer HMOD; HMOD := 100000;   begin reference(AValue) array hashTable ( 0 :: HMOD - 1 ); integer array A ( 0 :: 14 ); integer le1000Count, firstN, duplicateN, duplicateValue, n, An, An1, prevN, maxS;    % adds an element to the hash table, returns true if an element with value An  %  % was already present, false otherwise  %  % if the value was already present, its eN value is returned in prevN  % logical procedure addAValue( integer value n, An ; integer result prevN ) ; begin integer hash; logical duplicate; reference(AValue) element; hash  := An rem HMOD; element  := hashTable( hash ); duplicate := false; while element not = null and eAn(element) not = An do element := eNext(element); duplicate := element not = null; if not duplicate then hashTable( hash ) := AValue( n, An, hashTable( hash ) ) else prevN := eN(element); duplicate end addAValue ;    % initialise the hash table  % for h := 0 until HMOD - 1 do hashTable( h ) := null;    % calculate the values of the sequence until we have found values that  %  % include all numbers in 1..1000  %  % also store the first 15 values  %   A( 0 ) := An1 := n := 0; le1000Count := 0; maxS := firstN := duplicateN := duplicateValue := -1; while le1000Count < 1000 do begin logical le0, duplicate; n  := n + 1; An := An1 - n; le0 := ( An <= 0 ); if le0 then An := An1 + n; prevN := -1; duplicate := addAValue( n, An, prevN ); if duplicate and not le0 then begin An := An1 + n; duplicate := addAValue( n, An, prevN ) end if_duplicate_and_not_le0 ; if duplicate then begin  % the value was already present % if firstN < 0 then begin  % have the first duplicate  % firstN  := n; duplicateN  := prevN; duplicateValue := An; end if_firstN_lt_0 end else if An <= 1000 then le1000Count := le1000Count + 1;; if n < 15 then A( n ) := An; if An > maxS then maxS := An; An1 := An end while_le1000Count_lt_1000 ;    % show the first 15 values of the sequence  % write( "A( 0 .. 14 ): " ); for n := 0 until 14 do writeon( i_w := 1, A( n ) );  % positions of the first duplicate  % write( i_w := 1 , s_w := 0 , "First duplicates: " , duplicateN , " " , firstN , " (" , duplicateValue , ")" );  % number of elements required to include the first 1000 integers  % write( i_w := 1, "first element to include all 1..1000: ", n ); write( i_w := 1, "max sequence value encountered: ", maxS ) end   end.
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#APL
APL
recaman←{⎕IO←0 genNext←{ R←⍵[N-1]-N←≢⍵ (R<0)∨(R∊⍵):⍵,⍵[N-1]+N ⍵,⍵[N-1]-N } ⎕←'First 15: ' ⎕←reca←(genNext⍣14),0 ⎕←'First repetition: ' ⎕←⊃⌽reca←genNext⍣{⍺≢∪⍺}⊢reca ⎕←'Length of sequence containing [0..1000]:' ⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca }
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.
#AWK
AWK
  # syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK # show files after lines are removed: # GAWK "FNR==1{print(FILENAME)};{print(FNR,$0)}" TEST1 TEST2 TEST3 BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { # create 3 files with 10 lines each for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { # read file fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { # write file printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }  
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.)
#Diego
Diego
begin_funct({wav}, Record sound); set_decision(linger); find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)  ? with_found()_microphone()_label(mic);  : err_funct[]_err(Sorry, no one has a microphone!); exit_funct[];  ; with_microphone[mic]_record()_durat({secs}, 30)_var(recording); [Record sound]_ret([recording]); reset_decision(); end_funct[];   // Record a monophonic 16-bit PCM sound into memory space: exec_funct(Record sound)_var(PCMRecording)_me(); // The variable 'PCMRecording' is the sound in memory space   // Record a monophonic 16-bit PCM sound into a file or array: exec_funct(Record sound)_file(foo.wav)_me(); // The file 'foo.wav' is the sound in a file
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.)
#GUISS
GUISS
Start,Programs,Accessories,Sound Recorder,Button:Record
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.)
#Julia
Julia
  using PortAudio, LibSndFile   stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) # 44100 samples/sec buf = read(stream, 441000) save("recorded10sec.wav", buf)  
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.)
#Kotlin
Kotlin
// version 1.1.3   import java.io.File import javax.sound.sampled.*   const val RECORD_TIME = 20000L // twenty seconds say   fun main(args: Array<String>) { val wavFile = File("RecordAudio.wav") val fileType = AudioFileFormat.Type.WAVE val format = AudioFormat(16000.0f, 16, 2, true, true) val info = DataLine.Info(TargetDataLine::class.java, format) val line = AudioSystem.getLine(info) as TargetDataLine   // Creates a new thread that waits for 'RECORD_TIME' before stopping Thread(object: Runnable { override fun run() { try { Thread.sleep(RECORD_TIME) } catch (ie: InterruptedException) { println(ie.message) } finally { line.stop() line.close() } println("Finished") } }).start()   // Captures the sound and saves it in a WAV file try { if (AudioSystem.isLineSupported(info)) { line.open(format) line.start() println("Recording started") AudioSystem.write(AudioInputStream(line), fileType, wavFile) } else println("Line not supported") } catch (lue: LineUnavailableException) { println(lue.message) } }
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
#11l
11l
File(filename).read()
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.
#Lingo
Lingo
-- parent script "MyClass"   on foo (me) put "foo" end   on bar (me) put "bar" end
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.
#Lua
Lua
function helloWorld() print "Hello World" end   -- Will list all functions in the given table, but does not recurse into nexted tables function printFunctions(t) local s={} local n=0 for k in pairs(t) do n=n+1 s[n]=k end table.sort(s) for k,v in ipairs(s) do f = t[v] if type(f) == "function" then print(v) end end end   printFunctions(_G)
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.
#Nanoquery
Nanoquery
// create a class with methods that will be listed class Methods def static method1() return "this is a static method. it will not be printed" end def method2() return "this is not a static method" end   def operator=(other) // operator methods are listed by both their defined name and // by their internal name, which in this case is isEqual return true end end   // lists all nanoquery and java native methods for method in dir(new(Methods)) println method end
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Phix
Phix
class c nullable integer int = 1 public atom atm = 2.3 string str = "4point5" sequence seq public: object obj = {"an object"} c child private function foo(); public procedure bar(); end class c c_instance = new() include builtins\structs.e as structs function nulls(object s) return iff(s=NULL?"NULL":s) end function sequence fields = structs:get_struct_fields(c) for i=1 to length(fields) do {string name, integer tid, integer flags} = fields[i] if not and_bits(flags,SF_RTN) then -- (exclude foo/bar) string t = nulls(structs:get_field_type(c,name,true)), f = nulls(structs:get_field_flags(c,name,true)) object v = nulls(structs:fetch_field(c_instance,name,c)) printf(1,"type:%-11s, name:%-5s, flags:%s, value:%v\n",{t,name,f,v}) end if end for
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.
#PHP
PHP
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true;   var_dump(get_object_vars($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
#Crystal
Crystal
def rep(s : String) : Int32 x = s.size // 2   while x > 0 return x if s.starts_with? s[x..] x -= 1 end   0 end   def main %w( 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 ).each do |s| n = rep s puts n > 0 ? "\"#{s}\" #{n} rep-string \"#{s[..(n - 1)]}\"" : "\"#{s}\" not a rep-string" end end   main  
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
#Delphi
Delphi
  program Regular_expressions;   {$APPTYPE CONSOLE} {$R *.res}   uses System.SysUtils, System.RegularExpressions;   const CPP_IF = '\s*if\s*\(\s*(?<COND>.*)\s*\)\s*\{\s*return\s+(?<RETURN>.+);\s*\}'; PASCAL_IF = 'If ${COND} then result:= ${RETURN};';   var RegularExpression: TRegEx; str: string;   begin str := ' if ( a < 0 ) { return -a; }';   Writeln('Expression: '#10#10, str);   if RegularExpression.Create(CPP_IF).IsMatch(str) then begin Writeln(#10' Is a single If in Cpp:'#10);   Writeln('Translate to Pascal:'#10); str := RegularExpression.Create(CPP_IF).Replace(str, PASCAL_IF); Writeln(str); end; readln; end.    
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting 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
#Applesoft_BASIC
Applesoft BASIC
10 A$ = "THE FIVE BOXING WIZARDS JUMP QUICKLY" 20 GOSUB 100REVERSE 30 PRINT R$ 40 END   100 REMREVERSE A$ 110 R$ = "" 120 FOR I = 1 TO LEN(A$) 130 R$ = MID$(A$, I, 1) + R$ 140 NEXT I 150 RETURN
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.
#Isabelle
Isabelle
theory Scratch imports Main begin   text‹ Given the function we want to execute multiple times is of type \<^typ>‹unit ⇒ unit›. › fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where "pure_repeat _ 0 = ()" | "pure_repeat f (Suc n) = f (pure_repeat f n)"   text‹ Functions are pure in Isabelle. They don't have side effects. This means, the \<^const>‹pure_repeat› we implemented is always equal to \<^term>‹() :: unit›, independent of the function \<^typ>‹unit ⇒ unit› or \<^typ>‹nat›. Technically, functions are not even "executed", but only evaluated. › lemma "pure_repeat f n = ()" by simp   text‹ But we can repeat a value of \<^typ>‹'a› \<^term>‹n› times and return the result in a list of length \<^term>‹n› › fun repeat :: "'a ⇒ nat ⇒ 'a list" where "repeat _ 0 = []" | "repeat f (Suc n) = f # (repeat f n)"   lemma "repeat ''Hello'' 4 = [''Hello'', ''Hello'', ''Hello'', ''Hello'']" by code_simp   lemma "length (repeat a n) = n" by(induction n) simp+   text‹ Technically, \<^typ>‹'a› is not a function. We can wrap it in a dummy function which takes a \<^typ>‹unit› as first argument. This gives a function of type \<^typ>‹unit ⇒ 'a›. ›   fun fun_repeat :: "(unit ⇒ 'a) ⇒ nat ⇒ 'a list" where "fun_repeat _ 0 = []" | "fun_repeat f (Suc n) = (f ()) # (fun_repeat f n)"   lemma "fun_repeat (λ_. ''Hello'') 4 = [''Hello'', ''Hello'', ''Hello'', ''Hello'']" by code_simp   text‹ Yet, \<^const>‹fun_repeat› with the dummy function \<^typ>‹unit ⇒ 'a› is equivalent to \<^const>‹repeat› with the value \<^typ>‹'a› directly. › lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+   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.
#J
J
  NB. ^: (J's power conjunction) repeatedly evaluates a verb.   NB. Appending to a vector the sum of the most recent NB. 2 items can generate the Fibonacci sequence.   (, [: +/ _2&{.) (^:4) 0 1 0 1 1 2 3 5     NB. Repeat an infinite number of times NB. computes the stable point at convergence   cosine =: 2&o.   cosine (^:_ ) 2 NB. 2 is the initial value 0.739085   cosine 0.739085 NB. demonstrate the stable point x==Cos(x) 0.739085     cosine^:(<_) 2 NB. show the convergence 2 _0.416147 0.914653 0.610065 0.819611 0.682506 0.775995 0.713725 0.755929 0.727635 0.74675 0.733901 0.742568 0.736735 0.740666 0.738019 0.739803 0.738602 0.739411 0.738866 0.739233 0.738986 0.739152 0.73904 0.739116 0.739065 0.739099 0.739076 0.739091 0.7...     # cosine^:(<_) 2 NB. iteration tallyft 78   f =: 3 :'smoutput ''hi'''   f'' hi   NB. pass verbs via a gerund repeat =: dyad def 'for_i. i.y do. (x`:0)0 end. EMPTY'   (f`'')repeat 4 hi hi hi hi       NB. pass a verb directly to an adverb   Repeat =: adverb def 'for_i. i.y do. u 0 end. EMPTY'   f Repeat 4 hi hi hi hi  
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.)
#Factor
Factor
"" "/" [ [ "input.txt" "output.txt" move-file "docs" "mydocs" move-file ] with-directory ] bi@
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.)
#Fantom
Fantom
  class Rename { public static Void main () { // rename file/dir in current directory File.rename("input.txt".toUri).rename("output.txt") File.rename("docs/".toUri).rename("mydocs/") // rename file/dir in root directory File.rename("/input.txt".toUri).rename("/output.txt") File.rename("/docs/".toUri).rename("/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
#XPL0
XPL0
code real RlRes=46, RlOut=48; def S = 10;   proc SetBoundary(MV, MF); real MV; int MF; [MF(1,1):= 1; MV(1,1):= 1.0; MF(6,7):= -1; MV(6,7):= -1.0; ];   func real CalcDiff(MV, MF, DV, W, H); real MV; int MF; real DV; int W, H; int I, J, N; real V, Total; [Total:= 0.0; for I:= 0 to H-1 do for J:= 0 to W-1 do [V:= 0.0; N:= 0; if I then [V:= V + MV(I-1,J); N:= N+1]; if J then [V:= V + MV(I,J-1); N:= N+1]; if I+1 < H then [V:= V + MV(I+1,J); N:= N+1]; if J+1 < W then [V:= V + MV(I,J+1); N:= N+1]; V:= MV(I,J) - V/float(N); DV(I,J):= V; if MF(I,J) = 0 then Total:= Total + V*V; ]; return Total; ];   func real Iter(MV, MF, W, H); real MV; int MF, W, H; real DV, Diff, Cur; int I, J; [DV:= RlRes(W); for I:= 0 to W-1 do DV(I):= RlRes(H); Diff:= 1E10; Cur:= [0.0, 0.0, 0.0]; while Diff > 1E-24 do [SetBoundary(MV, MF); Diff:= CalcDiff(MV, MF, DV, W, H); for I:= 0 to H-1 do for J:= 0 to W-1 do MV(I,J):= MV(I,J) - DV(I,J); ]; for I:= 0 to H-1 do for J:= 0 to W-1 do Cur(MF(I,J)+1):= Cur(MF(I,J)+1) + DV(I,J) * float(-(I>0) - (J>0) - (I<H-1) - (J<W-1)); \middle=4; side=3; corner=2 return (Cur(2)-Cur(0))/2.0; ];   real MeshV(S,S); int MeshF(S,S); RlOut(0, 2.0 / Iter(MeshV, MeshF, S, S))
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
#Frink
Frink
  lines=split["\n", """---------- 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 line = lines println[join[" ", reverse[split[%r/\s+/, line]]]]  
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
#FutureBasic
FutureBasic
  include "NSLog.incl"   CFStringRef frostStr CFArrayRef frostArr, tempArr CFMutableStringRef mutStr NSInteger i, count   frostStr = @"---------- Ice and Fire ------------\n¬ \n¬ fire, in end will world the say Some\n¬ ice. in say Some\n¬ desire of tasted I've what From\n¬ fire. favor who those with hold I\n¬ \n¬ … elided paragraph last …\n¬ \n¬ Frost Robert -----------------------\n"   frostArr = fn StringComponentsSeparatedByString( frostStr, @"\n" ) count = fn ArrayCount( frostArr ) mutStr = fn MutableStringWithCapacity( 0 )   for i = 0 to count - 1 tempArr = fn StringComponentsSeparatedByString( frostArr[i], @" " ) tempArr = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( tempArr ) ) MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) ) MutableStringAppendString( mutStr, @"\n" ) next   NSLog( @"%@", mutStr )   HandleEvents  
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
#PureBasic
PureBasic
Declare.s Rot13(text_to_code.s)   If OpenConsole() Define txt$   Print("Enter a string to encode: "): txt$=Input()   PrintN("Coded  : "+Rot13(txt$)) PrintN("Decoded: "+Rot13(Rot13(txt$)))   Print("Press ENTER to quit."): Input() CloseConsole() EndIf   Procedure.s Rot13(s.s) Protected.i i Protected.s t, u For i=1 To Len(s) t=Mid(s,i,1) Select Asc(t) Case Asc("a") To Asc("m"), Asc("A") To Asc("M") t=chr(Asc(t)+13) Case Asc("n") To Asc("z"), Asc("N") To Asc("Z") t=chr(Asc(t)-13) EndSelect u+t Next ProcedureReturn u EndProcedure
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
#PL.2FI
PL/I
  /* From Wiki Fortran */ roman: procedure (n) returns(character (32) varying); declare n fixed binary nonassignable; declare (d, m) fixed binary; declare (r, m_div) character (32) varying; declare d_dec(13) fixed binary static initial (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); declare d_rom(13) character (2) varying static initial ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'); r = ''; m = n; do d = 1 to 13; m_div = m / d_dec (d); r = r || copy (d_rom (d), m_div); m = m - d_dec (d) * m_div; end; return (r); end roman;  
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.
#Rust
Rust
struct RomanNumeral { symbol: &'static str, value: u32 }   const NUMERALS: [RomanNumeral; 13] = [ RomanNumeral {symbol: "M", value: 1000}, RomanNumeral {symbol: "CM", value: 900}, RomanNumeral {symbol: "D", value: 500}, RomanNumeral {symbol: "CD", value: 400}, RomanNumeral {symbol: "C", value: 100}, RomanNumeral {symbol: "XC", value: 90}, RomanNumeral {symbol: "L", value: 50}, RomanNumeral {symbol: "XL", value: 40}, RomanNumeral {symbol: "X", value: 10}, RomanNumeral {symbol: "IX", value: 9}, RomanNumeral {symbol: "V", value: 5}, RomanNumeral {symbol: "IV", value: 4}, RomanNumeral {symbol: "I", value: 1} ];   fn to_hindu(roman: &str) -> u32 { match NUMERALS.iter().find(|num| roman.starts_with(num.symbol)) { Some(num) => num.value + to_hindu(&roman[num.symbol.len()..]), None => 0, // if string empty, add nothing } }   fn main() { let roms = ["MMXIV", "MCMXCIX", "XXV", "MDCLXVI", "MMMDCCCLXXXVIII"]; for &r in &roms { // 15 is minimum formatting width of the first argument, there for alignment println!("{:2$} = {}", r, to_hindu(r), 15); } }
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   char * string_repeat( int n, const char * s ) { size_t slen = strlen(s); char * dest = malloc(n*slen+1);   int i; char * p; for ( i=0, p = dest; i < n; ++i, p += slen ) { memcpy(p, s, slen); } *p = '\0'; return dest; }   int main() { char * result = string_repeat(5, "ha"); puts(result); free(result); return 0; }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#FALSE
FALSE
[\$@$@*@@/]f: { in: a b, out: a*b a/b } 6 2f;! .` ,. { 3 12 }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Forth
Forth
: muldiv ( a b -- a*b a/b ) 2dup / >r * r> ;
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).
#Applesoft_BASIC
Applesoft BASIC
100 DIM L$(15) 110 L$(0) = "NOW" 120 L$(1) = "IS" 130 L$(2) = "THE" 140 L$(3) = "TIME" 150 L$(4) = "FOR" 160 L$(5) = "ALL" 170 L$(6) = "GOOD" 180 L$(7) = "MEN" 190 L$(8) = "TO" 200 L$(9) = "COME" 210 L$(10) = "TO" 220 L$(11) = "THE" 230 L$(12) = "AID" 240 L$(13) = "OF" 250 L$(14) = "THE" 260 L$(15) = "PARTY."   300 N = 15 310 GOSUB 400 320 FOR I = 0 TO N 330 PRINT L$(I) " " ; 340 NEXT 350 PRINT 360 END   400 REMREMOVE DUPLICATES 410 FOR I = N TO 1 STEP -1 420 I$ = L$(I) 430 FOR J = 0 TO I - 1 440 EQ = I$ = L$(J) 450 IF NOT EQ THEN NEXT J 460 IF EQ THEN GOSUB 500 470 NEXT I 480 RETURN   500 REMREMOVE ELEMENT 510 L$(I) = L$(N) 520 L$(N) = "" 530 N = N - 1 540 RETURN
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   on run   -- FIRST FIFTEEN RECAMANs ------------------------------------------------------   script term15 on |λ|(i) 15 = (i as integer) end |λ| end script set strFirst15 to unwords(snd(recamanUpto(true, term15)))   set strFirstMsg to "First 15 Recamans:" & linefeed display notification strFirstMsg & strFirst15 delay 2   -- FIRST DUPLICATE RECAMAN ----------------------------------------------------   script firstDuplicate on |λ|(_, seen, rs) setSize(seen) as integer is not (length of (rs as list)) end |λ| end script set strDuplicate to (item -1 of snd(recamanUpto(true, firstDuplicate))) as integer as string   set strDupMsg to "First duplicated Recaman:" & linefeed display notification strDupMsg & strDuplicate delay 2   -- NUMBER OF RECAMAN TERMS NEEDED TO GET ALL OF [0..1000] -- (takes about a minute, depending on system)   set setK to setFromList(enumFromTo(0, 1000)) script supersetK on |λ|(i, setR) setK's isSubsetOfSet:(setR) end |λ| end script   display notification "Superset size result will take c. 1 min to find ..." set dteStart to current date   set strSetSize to (fst(recamanUpto(false, supersetK)) - 1) as string   set dteEnd to current date   set strSetSizeMsg to "Number of Recaman terms needed to generate" & ¬ linefeed & "all integers from [0..1000]:" & linefeed set strElapsed to "(Last result took c. " & (dteEnd - dteStart) & " seconds to find)" display notification strSetSizeMsg & linefeed & strSetSize   -- CLEARED REFERENCE TO NSMUTABLESET ------------------------------------- set setK to missing value   -- REPORT ---------------------------------------------------------------- unlines({strFirstMsg & strFirst15, "", ¬ strDupMsg & strDuplicate, "", ¬ strSetSizeMsg & strSetSize, "", ¬ strElapsed}) end run   -- nextR :: Set Int -> Int -> Int on nextR(seen, i, n) set bk to n - i if 0 > bk or setMember(bk, seen) then n + i else bk end if end nextR   -- recamanUpto :: Bool -> (Int -> Set Int > [Int] -> Bool) -> (Int, [Int]) on recamanUpto(bln, p) script recaman property mp : mReturn(p)'s |λ| on |λ|() set i to 1 set r to 0 set rs to {r} set seen to setFromList(rs) repeat while not mp(i, seen, rs) set r to nextR(seen, i, r) setInsert(r, seen) if bln then set end of rs to r set i to i + 1 end repeat set seen to missing value -- clear pointer to NSMutableSet {i, rs} end |λ| end script recaman's |λ|() end recamanUpto   -- GENERIC FUNCTIONS -------------------------------------------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat return lst else return {} end if end enumFromTo   -- fst :: (a, b) -> a on fst(tpl) if class of tpl is record then |1| of tpl else item 1 of tpl end if end fst   -- intercalateS :: String -> [String] -> String on intercalateS(sep, xs) set {dlm, my text item delimiters} to {my text item delimiters, sep} set s to xs as text set my text item delimiters to dlm return s end intercalateS   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- NB All names of NSMutableSets should be set to *missing value* -- before the script exits. -- ( scpt files containing residual ObjC pointer values can not be saved) -- setFromList :: Ord a => [a] -> Set a on setFromList(xs) set ca to current application ca's NSMutableSet's ¬ setWithArray:(ca's NSArray's arrayWithArray:(xs)) end setFromList   -- setMember :: Ord a => a -> Set a -> Bool on setMember(x, objcSet) missing value is not (objcSet's member:(x)) end setMember   -- setInsert :: Ord a => a -> Set a -> Set a on setInsert(x, objcSet) objcSet's addObject:(x) objcSet end setInsert   -- setSize :: Set a -> Int on setSize(objcSet) objcSet's |count|() as integer end setSize   -- snd :: (a, b) -> b on snd(tpl) if class of tpl is record then |2| of tpl else item 2 of tpl end if end snd   -- unlines :: [String] -> String on unlines(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines   -- unwords :: [String] -> String on unwords(xs) intercalateS(space, xs) end unwords
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.
#BASIC
BASIC
  ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Remove File Lines V1.1 ' ' ' ' Developed by A. David Garza Marín in VB-DOS for ' ' RosettaCode. November 30, 2016. ' ' ' ' Date | Change ' '-------------------------------------------------- ' ' 2016/11/30| Original version ' ' 2016/12/30| Added functionality to read parameters' ' | from Command Line ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '   'OPTION _EXPLICIT ' For QB45 OPTION EXPLICIT ' For VBDOS, PDS 7.1   ' SUBs and FUNCTIONs DECLARE FUNCTION DeleteLinesFromFile% (WhichFile AS STRING, Start AS LONG, HowMany AS LONG) DECLARE FUNCTION FileExists% (WhichFile AS STRING) DECLARE FUNCTION GetDummyFile$ (WhichFile AS STRING) DECLARE FUNCTION getFileName$ (CommandString AS STRING) DECLARE FUNCTION getHowManyLines& (CommandLine AS STRING) DECLARE FUNCTION getStartPoint& (CommandLine AS STRING) DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER) DECLARE FUNCTION CountLines& (WhichFile AS STRING)   ' Var DIM iOk AS INTEGER, iErr AS INTEGER, lStart AS LONG, lHowMany AS LONG, lSize AS LONG DIM sFile AS STRING, sCommand AS STRING   ' Const CONST ProgramName = "RemFLine (Remove File Lines) Enhanced V1.1"   ' ----------------------------- Main program cycle -------------------------------- CLS PRINT ProgramName PRINT PRINT "This program will remove as many lines of a text file as you state, starting" PRINT "with the line number you also state. If the starting line number is beyond" PRINT "total lines in the text file stated, then the process will be aborted. If the" PRINT "quantity of lines stated to be deleted is beyond the total lines in the text" PRINT "file, the process also will be aborted. The program will give you a message" PRINT "if everything ran ok or if any error happened. Includes a function to count" PRINT "how many lines has the intended file." ' Verifies if parameters are specified sCommand = COMMAND$ IF sCommand <> "" THEN sFile = getFileName$(sCommand) lSize = CountLines&(sFile) lStart = getStartPoint&(sCommand) ' Defaults to 1 lHowMany = getHowManyLines&(sCommand) ' Defaults to 1 ELSE PRINT INPUT "Please, type the name of the file"; sFile sFile = LTRIM$(RTRIM$(sFile)) IF sFile <> "" THEN lSize = CountLines&(sFile) IF lSize > 0 THEN PRINT "Delete starting on which line (Default=1, Max="; lSize; ")"; INPUT lStart   IF lStart = 0 THEN lStart = 1 IF lStart < lSize THEN PRINT "How many lines do you want to remove (Default=1, Max="; (lSize - lStart) + 1; ")"; INPUT lHowMany IF lHowMany = 0 THEN lHowMany = 1 END IF END IF END IF END IF   PRINT PRINT "Erasing "; lHowMany; "lines from "; sFile; " starting on line"; lStart; "." IF lSize > 0 THEN IF lHowMany + lStart <= lSize THEN iOk = DeleteLinesFromFile%(sFile, lStart, lHowMany) ELSEIF lHowMany + lStart > lSize THEN iOk = 1 ELSEIF lStart > lSize THEN iOk = 2 END IF ELSEIF lSize = -1 THEN iOk = 3 END IF   IF lSize = -1 THEN iOk = 3 ELSEIF lSize = 0 THEN iOk = 4 ' The file is not a text file END IF   IF sFile = "" THEN iOk = 5 ' Null file name not allowed END IF   PRINT PRINT ErrorMessage$(iOk) '----------------End of Main program Cycle ----------------   END   FileError: iErr = ERR RESUME NEXT   FUNCTION CountLines& (WhichFile AS STRING) ' Var DIM iFile AS INTEGER DIM l AS LONG, li AS LONG, j AS LONG, lFileSize AS LONG, lLines AS LONG DIM sLine AS STRING, strR AS STRING   ' This function will count how many lines has the file IF FileExists%(WhichFile) THEN strR = CHR$(13) li = 1 iFile = FREEFILE sLine = SPACE$(128) lLines = 0 OPEN WhichFile FOR BINARY AS #iFile lFileSize = LOF(iFile) DO IF (LOC(iFile) + LEN(sLine)) > lFileSize THEN sLine = SPACE$(lFileSize - LOC(iFile)) END IF IF LEN(sLine) > 0 THEN GET #iFile, , sLine GOSUB AnalizeLine END IF LOOP UNTIL LEN(sLine) < 128 CLOSE iFile ELSE lLines = -1 END IF   CountLines& = lLines   EXIT FUNCTION   AnalizeLine: li = 1 DO l = INSTR(li, sLine, strR) IF l > 0 THEN lLines = lLines + 1 li = l + 1 END IF LOOP UNTIL l = 0 RETURN END FUNCTION   FUNCTION DeleteLinesFromFile% (WhichFile AS STRING, Start AS LONG, HowMany AS LONG) ' Var DIM lCount AS LONG, iFile AS INTEGER, iFile2 AS INTEGER, lhm AS LONG, iError AS INTEGER DIM sLine AS STRING, sDummyFile AS STRING   IF FileExists%(WhichFile) THEN sDummyFile = GetDummyFile$(WhichFile)   ' It is assumed a text file iFile = FREEFILE OPEN WhichFile FOR INPUT AS #iFile   iFile2 = FREEFILE OPEN sDummyFile FOR OUTPUT AS #iFile2   lhm = 0 DO WHILE NOT EOF(iFile) LINE INPUT #iFile, sLine lCount = lCount + 1 IF lCount >= Start AND lhm < HowMany THEN lhm = lhm + 1 ELSE PRINT #iFile2, sLine END IF LOOP   CLOSE iFile2, iFile   ' Check if everything went ok or not iError = 0 IF lCount < Start THEN iError = 2 ' Full file is shorter than the start line stated, ' process will be aborted. ELSEIF lhm < HowMany THEN iError = 1 ' File was shorter than lines requested to be removed, ' process will be aborted. END IF   IF iError > 0 THEN KILL sDummyFile ' Process aborted ELSE KILL WhichFile NAME sDummyFile AS WhichFile END IF ELSE iError = 3 ' The file doesn't exist. The process is aborted. END IF   DeleteLinesFromFile% = iError   END FUNCTION   FUNCTION ErrorMessage$ (WhichError AS INTEGER) ' Var DIM sError AS STRING   SELECT CASE WhichError CASE 0: sError = "Everything went Ok. Lines removed from file." CASE 1: sError = "File is shorter than the number of lines stated to remove. Process aborted." CASE 2: sError = "Whole file is shorter than the starting point stated. Process aborted." CASE 3: sError = "File doesn't exist. Process aborted." CASE 4: sError = "The file doesn't seem to be a text file. Process aborted." CASE 5: sError = "You need to provide a valid file name, please." END SELECT   ErrorMessage$ = sError END FUNCTION   FUNCTION FileExists% (WhichFile AS STRING) ' Var DIM iFile AS INTEGER DIM iItExists AS INTEGER SHARED iErr AS INTEGER   ON ERROR GOTO FileError iFile = FREEFILE iErr = 0 OPEN WhichFile FOR BINARY AS #iFile IF iErr = 0 THEN iItExists = LOF(iFile) > 0 CLOSE #iFile   IF NOT iItExists THEN KILL WhichFile END IF END IF ON ERROR GOTO 0 FileExists% = iItExists   END FUNCTION   FUNCTION GetDummyFile$ (WhichFile AS STRING) ' Var DIM i AS INTEGER, j AS INTEGER   ' Gets the path specified in WhichFile i = 1 DO j = INSTR(i, WhichFile, "\") IF j > 0 THEN i = j + 1 LOOP UNTIL j = 0   GetDummyFile$ = LEFT$(WhichFile, i - 1) + "$dummyf$.tmp" END FUNCTION   FUNCTION getFileName$ (CommandString AS STRING) ' Var DIM i AS INTEGER DIM sFileName AS STRING   i = INSTR(CommandString, ",") IF i > 0 THEN sFileName = LEFT$(CommandString, i - 1) ELSEIF LEN(CommandString) > 0 THEN sFileName = CommandString END IF   getFileName$ = sFileName END FUNCTION   FUNCTION getHowManyLines& (CommandLine AS STRING) ' Var DIM i AS INTEGER, j AS INTEGER DIM l AS LONG   i = INSTR(CommandLine, ",") IF i > 0 THEN j = INSTR(i + 1, CommandLine, ",") IF j = 0 THEN l = 1 ELSE l = CLNG(VAL(MID$(CommandLine, j + 1))) END IF END IF   getHowManyLines& = l   END FUNCTION   FUNCTION getStartPoint& (CommandLine AS STRING) ' Var DIM i AS INTEGER, j AS INTEGER DIM l AS LONG   i = INSTR(CommandLine, ",") IF i > 0 THEN j = INSTR(i + 1, CommandLine, ",") IF j = 0 THEN j = LEN(CommandLine) l = CLNG(VAL(MID$(CommandLine, i + 1, j - i))) ELSE i = 1 END IF   getStartPoint& = l   END FUNCTION    
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.)
#Liberty_BASIC
Liberty BASIC
  run "sndrec32.exe"  
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.)
#LiveCode
LiveCode
command makeRecording set the dontUseQT to false -- on windows use true set the recordFormat to "wave" -- can be wav,aiff, au set the recordRate to 44.1 -- sample at 44100 Hz set the recordSampleSize to 16 --default is 8 bit ask file "Save recording as" if it is not empty then answer record --show sound input dialog with presets above record sound file it -- actual record command wait 10 seconds stop recording end if end makeRecording
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.)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SystemDialogInput["RecordSound"]
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.)
#Nim
Nim
import osproc, strutils   var name = "" while name.len == 0: stdout.write "Enter output file name (without extension): " name = stdin.readLine().strip() name.add ".wav"   var rate = 0 while rate notin 2000..19_200: stdout.write "Enter sampling rate in Hz (2000 to 192000): " try: rate = parseInt(stdin.readLine().strip()) except ValueError: discard   var duration = 0 while duration notin 5..30: stdout.write "Enter duration in seconds (5 to 30): " try: duration = parseInt(stdin.readLine().strip()) except ValueError: discard   echo "OK, start speaking now..." # Default arguments: -c 1, -t wav. Note that only signed 16 bit format is supported. let args = ["-r", $rate, "-f", "S16_LE", "-d", $duration, name] echo execProcess("arecord", args = args, options = {poStdErrToStdOut, poUsePath})   echo "'$1' created on disk and will now be played back..." % name echo execProcess("aplay", args = [name], options = {poStdErrToStdOut, poUsePath}) echo "Playback completed"
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.)
#OCaml
OCaml
#load "unix.cma"   let record bytes = let buf = String.make bytes '\000' in let ic = open_in "/dev/dsp" in let chunk = 4096 in for i = 0 to pred (bytes / chunk) do ignore (input ic buf (i * chunk) chunk) done; close_in ic; (buf)   let play buf len = let oc = open_out "/dev/dsp" in output_string oc buf; close_out oc   let () = let bytes = 65536 in let p = record bytes in play p bytes
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
#8th
8th
  "somefile.txt" f:slurp >s  
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
#Action.21
Action!
proc MAIN() char array STRING open (1,"D:FILE.TXT",4,0) inputsd(1,STRING) close(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.
#Nim
Nim
type Foo = object proc bar(f:Foo) = echo "bar" var f:Foo f.bar()
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.
#Objective-C
Objective-C
#import <Foundation/Foundation.h> #import <objc/runtime.h>   @interface Foo : NSObject @end @implementation Foo - (int)bar:(double)x { return 42; } @end   int main() { unsigned int methodCount; Method *methods = class_copyMethodList([Foo class], &methodCount); for (unsigned int i = 0; i < methodCount; i++) { Method m = methods[i]; SEL selector = method_getName(m); const char *typeEncoding = method_getTypeEncoding(m); NSLog(@"%@\t%s", NSStringFromSelector(selector), typeEncoding); } free(methods); return 0; }
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.
#PicoLisp
PicoLisp
  # The Rectangle class (class +Rectangle +Shape) # dx dy   (dm T (X Y DX DY) (super X Y) (=: dx DX) (=: dy DY) )   (dm area> () (* (: dx) (: dy)) )   (dm perimeter> () (* 2 (+ (: dx) (: dy))) )   (dm draw> () (drawRect (: x) (: y) (: dx) (: dy)) ) # Hypothetical function 'drawRect'  
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.
#PL.2FI
PL/I
  Get-Date | Get-Member -MemberType Property  
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.
#PowerShell
PowerShell
  Get-Date | Get-Member -MemberType Property  
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
#D
D
import std.stdio, std.string, std.conv, std.range, std.algorithm, std.ascii, std.typecons;   Nullable!(size_t, 0) repString1(in string s) pure nothrow @safe @nogc in { //assert(s.all!isASCII); assert(s.representation.all!isASCII); } body { immutable sr = s.representation; foreach_reverse (immutable n; 1 .. sr.length / 2 + 1) if (sr.take(n).cycle.take(sr.length).equal(sr)) return typeof(return)(n); return typeof(return)(); }   Nullable!(size_t, 0) repString2(in string s) pure @safe /*@nogc*/ in { assert(s.countchars("01") == s.length); } body { immutable bits = s.to!ulong(2);   foreach_reverse (immutable left; 1 .. s.length / 2 + 1) { immutable right = s.length - left; if ((bits ^ (bits >> left)) == ((bits >> right) << right)) return typeof(return)(left); } return typeof(return)(); }   void main() { immutable words = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1".split;   foreach (immutable w; words) { immutable r1 = w.repString1; //assert(r1 == w.repString2); immutable r2 = w.repString2; assert((r1.isNull && r2.isNull) || r1 == r2); if (r1.isNull) writeln(w, " (no repeat)"); else writefln("%(%s %)", w.chunks(r1)); } }
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
#Elixir
Elixir
  str = "This is a string" if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"  
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Emacs_Lisp
Emacs Lisp
(let ((string "I am a string")) (when (string-match-p "string$" string) (message "Ends with 'string'")) (message "%s" (replace-regexp-in-string " a " " another " string)))
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting 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
#Arturo
Arturo
str: "Hello World"   print reverse str
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.
#Java
Java
import java.util.function.Consumer; import java.util.stream.IntStream;   public class Repeat {   public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); }   static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
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.
#jq
jq
def unoptimized_repeat(f; n): if n <= 0 then empty else f, repeat(f; n-1) 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.)
#Forth
Forth
s" input.txt" s" output.txt" rename-file throw s" /input.txt" s" /output.txt" rename-file throw
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.)
#Fortran
Fortran
PROGRAM EX_RENAME CALL RENAME('input.txt','output.txt') CALL RENAME('docs','mydocs') CALL RENAME('/input.txt','/output.txt') CALL RENAME('/docs','/mydocs') 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.)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim result As Long result = Name("input.txt", "output.txt") If result <> 0 Then Print "Renaming file failed" End If   result = Name("docs", "mydocs") If result <> 0 Then Print "Renaming directory failed" End If   Sleep
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
#Yabasic
Yabasic
N=10 NN=N*N DIM A(NN,NN+1)   NODE=0 FOR ROW=1 TO N FOR COL=1 TO N NODE=NODE+1 IF ROW>1 THEN A(NODE,NODE)=A(NODE,NODE)+1 A(NODE,NODE-N)=-1 END IF IF ROW<N THEN A(NODE,NODE)=A(NODE,NODE)+1 A(NODE,NODE+N)=-1 END IF IF COL>1 THEN A(NODE,NODE)=A(NODE,NODE)+1 A(NODE,NODE-1)=-1 END IF IF COL<N THEN A(NODE,NODE)=A(NODE,NODE)+1 A(NODE,NODE+1)=-1 END IF NEXT NEXT   AR=2 : AC=2 : A=AC+N*(AR-1) BR=7 : BC=8 : B=BC+N*(BR-1) A(A,NN+1)=-1 A(B,NN+1)=1   PRINT "Nodes ",A,B   // solve linear system // using Gauss-Seidel method // with pivoting R=NN   FOR J=1 TO R FOR I=J TO R IF A(I,J)<>0 BREAK NEXT IF I=R+1 THEN PRINT "No solution!" END END IF FOR K=1 TO R+1 T = A(J,K) A(J,K) = A(I,K) A(I,K) = T NEXT Y=1/A(J,J) FOR K=1 TO R+1 A(J,K)=Y*A(J,K) NEXT FOR I=1 TO R IF I<>J THEN Y=-A(I,J) FOR K=1 TO R+1 A(I,K)=A(I,K)+Y*A(J,K) NEXT END IF NEXT NEXT PRINT "Resistence = "; : PRINT ABS(A(A,NN+1)-A(B,NN+1)) USING "%1.13f"
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
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn onGrid(i,j,p,q){ ((0<=i<p) and (0<=j<q)) } fcn gridResistor(p,q, ai,aj, bi,bj){ n,A := p*q, GSL.Matrix(n,n); // zero filled foreach i,j in (p,q){ k:=i*q + j; if(i==ai and j==aj) A[k,k]=1; else{ c:=0; if(onGrid(i+1,j, p,q)){ c+=1; A[k, k+q]=-1 } if(onGrid(i-1,j, p,q)){ c+=1; A[k, k-q]=-1 } if(onGrid(i, j+1, p,q)){ c+=1; A[k, k+1]=-1 } if(onGrid(i, j-1, p,q)){ c+=1; A[k, k-1]=-1 } A[k,k]=c; } } b:=GSL.Vector(n); // zero filled b[k:=bi*q + bj]=1; A.AxEQb(b)[k]; }
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
#Gambas
Gambas
Public Sub Main() Dim sString As New String[10] 'Array for the input text Dim sLine As New String[] 'Array of each word in a line Dim siCount0, siCount1 As Short 'Counters Dim sOutput, sReverse, sTemp As String 'Strings   sString[0] = "---------- Ice And Fire ------------" 'Input text sString[1] = " " sString[2] = "fire, in end will world the say Some" sString[3] = "ice. in say Some " sString[4] = "desire of tasted I've what From " sString[5] = "fire. favor who those with hold I " sString[6] = " " sString[7] = "... elided paragraph last ... " sString[8] = " " sString[9] = "Frost Robert -----------------------"   For siCount0 = 0 To 9 'To work through each line of input text If Trim(sString[siCount0]) = "" Then sString[siCount0] = " " 'If the line is all spaces then make it 1 space   For Each sTemp In Split(Trim(sString[siCount0]), " ") 'Split the trimmed line by spaces sLine.Add(sTemp) 'Add each word to the sLine array Next   For siCount1 = sLine.max DownTo 0 'Loop from the last in the sLine array to 0 sReverse &= sLine[siCount1] & " " 'Fill sReverse with words reversed, adding a space Next   sOutput &= Trim(sReverse) & gb.NewLine 'Add the reversed words to sOutput and add a newline sReverse = "" 'Clear sReverse sLine.Clear 'Clear sLine array Next   Print sOutput 'Print the output   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
#Python
Python
>>> u'foo'.encode('rot13') 'sbb' >>> 'sbb'.decode('rot13') u'foo'
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
#PL.2FSQL
PL/SQL
    /***************************************************************** * $Author: Atanas Kebedjiev $ ***************************************************************** * Encoding an Arabic numeral to a Roman in the range 1..3999 is much simpler as Oracle provides the conversion formats. * Please see also the SQL solution for the same task. */   CREATE OR REPLACE FUNCTION rencode(an IN NUMBER) RETURN VARCHAR2 IS BEGIN RETURN to_char(an, 'RN'); END rencode;   BEGIN   DBMS_OUTPUT.PUT_LINE ('2012 = ' || rencode('2012')); -- MMXII DBMS_OUTPUT.PUT_LINE ('1951 = ' || rencode('1951')); -- MCMLI DBMS_OUTPUT.PUT_LINE ('1987 = ' || rencode('1987')); -- MCMLXXXVII DBMS_OUTPUT.PUT_LINE ('1666 = ' || rencode('1666')); -- MDCLXVI DBMS_OUTPUT.PUT_LINE ('1999 = ' || rencode('1999')); -- MCMXCIX   END;  
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.
#Scala
Scala
def fromRoman( r:String ) : Int = { val arabicNumerals = List("CM"->900,"M"->1000,"CD"->400,"D"->500,"XC"->90,"C"->100, "XL"->40,"L"->50,"IX"->9,"X"->10,"IV"->4,"V"->5,"I"->1)   var s = r arabicNumerals.foldLeft(0){ (n,t) => { val l = s.length; s = s.replaceAll(t._1,""); val c = (l - s.length)/t._1.length // Get the frequency n + (c*t._2) // Add the arabic numerals up } } }   // Here is a another version that does a simple running sum: def fromRoman2(s: String) : Int = { val numerals = Map('I' -> 1, 'V' -> 5, 'X' -> 10, 'L' -> 50, 'C' -> 100, 'D' -> 500, 'M' -> 1000)   s.toUpperCase.map(numerals).foldLeft((0,0)) { case ((sum, last), curr) => (sum + curr + (if (last < curr) -2*last else 0), curr) }._1 } }   // A small test def test( roman:String ) = println( roman + " => " + fromRoman( roman ) )   test("MCMXC") test("MMVIII") test("MDCLXVI")
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
#C.23
C#
string s = "".PadLeft(5, 'X').Replace("X", "ha");
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Fortran
Fortran
module multiple_values implicit none type res integer :: p, m end type   contains   function addsub(x,y) result(r) integer :: x, y type(res) :: r r%p = x+y r%m = x-y end function end module   program main use multiple_values print *, addsub(33, 22) end program  
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).
#Arturo
Arturo
arr: [1 2 3 2 1 2 3 4 5 3 2 1]   print unique arr
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#Arturo
Arturo
recamanSucc: function [seen, n, r].memoize[ back: r - n (or? 0 > back contains? seen back)? -> n + r -> back ]   recamanUntil: function [p][ n: new 1 r: 0 rs: new @[r] seen: rs blnNew: true while [not? do p][ r: recamanSucc seen n r blnNew: not? in? r seen seen: unique seen ++ r 'rs ++ r inc 'n ] return rs ]   print "First 15 Recaman numbers:" print recamanUntil [n = 15]   print "" print "First duplicate Recaman number:" print last recamanUntil [not? blnNew]
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#AWK
AWK
  # syntax: GAWK -f RECAMANS_SEQUENCE.AWK # converted from Microsoft Small Basic BEGIN { found_dup = 0 n = -1 do { n++ ap = a[n-1] + n if (a[n-1] <= n) { a[n] = ap b[ap] = 1 } else { am = a[n-1] - n if (b[am] == 1) { a[n] = ap b[ap] = 1 } else { a[n] = am b[am] = 1 } } if (n <= 14) { terms = sprintf("%s%s ",terms,a[n]) if (n == 14) { printf("first %d terms: %s\n",n+1,terms) } } if (!found_dup) { if (dup[a[n]] == 1) { printf("first duplicated term: a[%d]=%d\n",n,a[n]) found_dup = 1 } dup[a[n]] = 1 } if (a[n] <= 1000) { arr[a[n]] = "" } } while (n <= 15 || !found_dup || length(arr) < 1001) printf("terms needed to generate integers 0 - 1000: %d\n",n) exit(0) }  
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#11l
11l
F ToReducedRowEchelonForm(&M) V lead = 0 V rowCount = M.len V columnCount = M[0].len L(r) 0 .< rowCount I lead >= columnCount R V i = r L M[i][lead] == 0 i++ I i == rowCount i = r lead++ I columnCount == lead R swap(&M[i], &M[r]) V lv = M[r][lead] M[r] = M[r].map(mrx -> mrx / Float(@lv)) L(i) 0 .< rowCount I i != r lv = M[i][lead] M[i] = zip(M[r], M[i]).map((rv, iv) -> iv - @lv * rv) lead++   V mtx = [[ 1.0, 2.0, -1.0, -4.0], [ 2.0, 3.0, -1.0, -11.0], [-2.0, 0.0, -3.0, 22.0]]   ToReducedRowEchelonForm(&mtx)   L(rw) mtx print(rw.join(‘, ’))
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#11l
11l
math:e // e math:pi // pi sqrt(x) // square root log(x) // natural logarithm log10(x) // base 10 logarithm exp(x) // e raised to the power of x abs(x) // absolute value floor(x) // floor ceil(x) // ceiling x ^ y // exponentiation
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.
#C
C
#include <stdio.h> #include <stdlib.h> /* for atoi() and malloc() */ #include <string.h> /* for memmove() */   /* Conveniently print to standard error and exit nonzero. */ #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)   int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1;   /* Initialization and sanity checks */ if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]);   if ((count = atoi(argv[3])) < 1) /* We're a no-op. */ return 0;   if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start);   if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]);   /* Determine filesize and allocate a buffer accordingly. */ fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp);   /* Fill the buffer, count lines, and remember a few important offsets. */ while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } }   /* We've been asked to do something weird; clean up and bail. */ if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); }   /* Overwrite the lines to be deleted with the survivors. */ memmove(buf + dest, buf + src, pos - src);   /* Reopen the file and write back just enough of the buffer. */ freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp);   free(buf); fclose(fp); return 0; }
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.)
#Phix
Phix
-- -- demo\rosetta\Record_sound.exw -- ============================= -- without js -- (file i/o) constant wavfile = "capture.wav", bitspersample = 16, channels = 2, samplespersec = 44100, alignment = bitspersample * channels / 8, bytespersec = alignment * samplespersec, params = sprintf(" bitspersample %d channels %d alignment %d samplespersec %d bytespersec %d", {bitspersample, channels, alignment, samplespersec, bytespersec}), error_size = 2048 atom winmm = NULL, xmciSendString, pError procedure mciSendString(string msg) if winmm=NULL then winmm = open_dll("winmm.dll") xmciSendString = define_c_func(winmm,"mciSendStringA", {C_PTR, -- LPCTSTR lpszCommand C_PTR, -- LPTSTR lpszReturnString C_INT, -- UINT cchReturn C_PTR}, -- HANDLE hwndCallback C_INT) -- MCIERROR pError = allocate(error_size) end if atom res = c_func(xmciSendString,{msg,pError,error_size,NULL}) if res!=0 then crash("error %0x: %s",{res,peek_string(pError)}) end if end procedure include get.e -- get_bytes() function record(integer bytes) integer fn = open("/dev/dsp","rb") if fn=-1 then return "" end if string res = get_bytes(fn,bytes) close(fn) return res end function procedure play(string buf) if length(buf) then integer fn = open("/dev/dsp","wb") if fn!=-1 then puts(fn,buf) close(fn) end if end if end procedure if platform()=WINDOWS then mciSendString("close all") mciSendString("open new type waveaudio alias capture") mciSendString("set capture" & params) puts(1,"Press SPACE to start recording...") while wait_key()!=' ' do end while mciSendString("record capture") puts(1,"Recording, press SPACE to stop...") while wait_key()!=' ' do end while mciSendString("stop capture") mciSendString("save capture " & wavfile) mciSendString("delete capture") mciSendString("close capture") puts(1,"Captured audio is stored in "&wavfile) elsif platform()=LINUX then -- warning: untested play(record(65536)) -- -- alternative, from Go (ditto) -- string name = "test.wav", -- rate = "2000", -- (2000..192000 Hz) -- durn = "5" -- (5 to 30 seconds) -- printf(1,"OK, start speaking now...\n") -- -- Default arguments: -c 1, -t wav. Note only signed 16 bit format supported. -- string cmd = sprintf("arecord -r %s -f S16_LE -d %s %s", {rate,durn,name}) -- {} = system_exec(cmd) -- printf(1,"'%s' created on disk and will now be played back...\n", {name}) -- {} = system_exec("aplay "&name) -- printf(1,"Play-back completed.\n") end if
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
#Ada
Ada
with Ada.Directories, Ada.Direct_IO, Ada.Text_IO;   procedure Whole_File is   File_Name : String  := "whole_file.adb"; File_Size : Natural := Natural (Ada.Directories.Size (File_Name));   subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String);   File  : File_String_IO.File_Type; Contents : File_String;   begin File_String_IO.Open (File, Mode => File_String_IO.In_File, Name => File_Name); File_String_IO.Read (File, Item => Contents); File_String_IO.Close (File);   Ada.Text_IO.Put (Contents); end Whole_File;
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
#ALGOL_68
ALGOL 68
MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢ BOOK book;   FILE book file; INT errno = open(book file, "book.txt", stand in channel);   get(book file, book)
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.
#Perl
Perl
package Nums;   use overload ('<=>' => \&compare); sub new { my $self = shift; bless [@_] } sub flip { my @a = @_; 1/$a } sub double { my @a = @_; 2*$a } sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) }   my $a = Nums->new(42); print "$_\n" for %{ref ($a)."::" });
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.
#Phix
Phix
enum METHODS, PROPERTIES sequence all_methods = {} function method_visitor(object key, object /*data*/, /*user_data*/) all_methods = append(all_methods,key) return 1 end function function get_all_methods(object o) all_methods = {} traverse_dict(method_visitor,0,o[METHODS]) return all_methods end function function exists() return "exists" end function --class X: Xmethods emulates a vtable constant Xmethods = new_dict({{"exists",exists}}) --class X: destructor procedure destructor(object o) destroy_dict(o[PROPERTIES]) end procedure --class X: create new instances function newX(object x,y) integer Xproperties = new_dict({{"x",x},{"y",y}}) object res = delete_routine({Xmethods,Xproperties},destructor) return res end function object x = newX(2,"string") ?get_all_methods(x)
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.
#Python
Python
class Parent(object): __priv = 'private'   def __init__(self, name): self.name = name   def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name)   def doNothing(self): pass   import re   class Child(Parent): # prefix for "private" fields __rePrivate = re.compile('^_(Child|Parent)__') # used when setting dynamic property values __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh   def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args   def __dir__(self): myDir = filter( # filter out private fields lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( # dynamic properties lambda p: p + '_bleh', filter( # don't add dynamic properties for methods and other special properties lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir))   def __getattr__(self, name): if name[-5:] == '_bleh': # dynamic '_bleh' properties return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))   def __setattr__(self, name, value): if name[-5:] == '_bleh': # skip backing properties that are methods if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value   def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))   def doStuff(self): return (1+1.0/1e6) ** 1e6   par = Parent('par') par.parent = True dir(par) #['_Parent__priv', '__class__', ..., 'doNothing', 'name', 'parent'] inspect.getmembers(par) #[('_Parent__priv', 'private'), ('__class__', <class '__main__.Parent'>), ..., ('doNothing', <bound method Parent.doNothing of <__main__.Parent object at 0x100777650>>), ('name', 'par'), ('parent', True)]   chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) #['__class__', ..., 'args', 'args_bleh', 'doNothing', 'doStuff', 'name', 'name_bleh', 'own', 'own_bleh', 'reBleh', 'reBleh_bleh'] inspect.getmembers(chld) #[('__class__', <class '__main__.Child'>), ..., ('args', (0, 'I', 'two')), ('args_bleh', "(0, 'I', 'two') bleh"), ('doNothing', <bound method Child.doNothing of Child(chld, 0, 'I', 'two')>), ('doStuff', <bound method Child.doStuff of Child(chld, 0, 'I', 'two')>), ('name', 'chld'), ('name_bleh', 'chld bleh'), ('own', "chld's own"), ('own_bleh', "chld's own bleh"), ('reBleh', <_sre.SRE_Pattern object at 0x10067bd20>), ('reBleh_bleh', '<_sre.SRE_Pattern object at 0x10067bd20> bleh')]  
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
#Delphi
Delphi
  program Rep_string;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const m = '1001110011'#10 + '1110111011'#10 + '0010010010'#10 + '1010101010'#10 + '1111111111'#10 + '0100101101'#10 + '0100100'#10 + '101'#10 + '11'#10 + '00'#10 + '1';   function Rep(s: string; var sub:string): Integer; var x: Integer; begin for x := s.Length div 2 downto 1 do begin sub := s.Substring(x); if s.StartsWith(sub) then exit(x); end; sub := ''; Result := 0; end;   begin for var s in m.Split([#10]) do begin var sub := ''; var n := rep(s,sub); if n > 0 then writeln(format('"%s"  %d rep-string "%s"', [s, n, sub])) else writeln(format('"%s" not a rep-string', [s])); end; {$IFNDEF UNIX}readln;{$ENDIF} end.
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
#Erlang
Erlang
match() -> String = "This is a string", case re:run(String, "string$") of {match,_} -> io:format("Ends with 'string'~n"); _ -> ok end.   substitute() -> String = "This is a string", NewString = re:replace(String, " a ", " another ", [{return, list}]), io:format("~s~n",[NewString]).
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
#AutoHotkey
AutoHotkey
MsgBox % reverse("asdf")   reverse(string) { Loop, Parse, string reversed := A_LoopField . reversed Return reversed }
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.
#Julia
Julia
function sayHi() println("Hi") end   function rep(f, n) for i = 1:n f() end end   rep(sayHi, 3)
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Kotlin
Kotlin
// version 1.0.6   fun repeat(n: Int, f: () -> Unit) { for (i in 1..n) { f() println(i) } }   fun main(args: Array<String>) { repeat(5) { print("Example ") } }
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.)
#Go
Go
package main import "os"   func main() { os.Rename("input.txt", "output.txt") os.Rename("docs", "mydocs") os.Rename("/input.txt", "/output.txt") os.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.)
#Groovy
Groovy
['input.txt':'output.txt', 'docs':'mydocs'].each { src, dst -> ['.', ''].each { dir -> new File("$dir/$src").renameTo(new File("$dir/$dst")) } }
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
#Gema
Gema
\L<G> <U>=@{$2} $1
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
#Go
Go
package main   import ( "fmt" "strings" )   // a number of strings var n = []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 -----------------------", }   func main() { for i, s := range n { t := strings.Fields(s) // tokenize // reverse last := len(t) - 1 for j, k := range t[:len(t)/2] { t[j], t[last-j] = t[last-j], k } n[i] = strings.Join(t, " ") } // display result for _, t := range n { fmt.Println(t) } }
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
#QB64
QB64
INPUT "Enter a string: ", a$ PRINT rot13$(a$) FUNCTION rot13$ (stg$) inlist$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" outlist$ = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" FOR n = 1 TO LEN(stg$) letter$ = MID$(stg$, n, 1) letpos = INSTR(inlist$, letter$) IF letpos = 0 THEN rotated$ = letter$ ELSE rotated$ = MID$(outlist$, letpos, 1) END IF rot13$ = rot13$ + rotated$ NEXT END FUNCTION
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
#Plain_TeX
Plain TeX
\def\upperroman#1{\uppercase\expandafter{\romannumeral#1}} Anno Domini \upperroman{\year} \bye
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.
#Scheme
Scheme
(use gauche.collection) ;; for fold2   (define (char-val char) (define i (string-scan "IVXLCDM" char)) (* (expt 10 (div i 2)) (expt 5 (mod i 2))))   (define (decode roman) (fold2 (lambda (n sum prev-val) (values ((if (< n prev-val) - +) sum n) (max n prev-val))) 0 0 (map char-val (reverse (string->list roman)))))  
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
#C.2B.2B
C++
#include <string> #include <iostream>   std::string repeat( const std::string &word, int times ) { std::string result ; result.reserve(times*word.length()); // avoid repeated reallocation for ( int a = 0 ; a < times ; a++ ) result += word ; return result ; }   int main( ) { std::cout << repeat( "Ha" , 5 ) << std::endl ; return 0 ; }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' One way to return multiple values is to use ByRef parameters for the additional one(s) Function tryOpenFile (fileName As String, ByRef fileNumber As Integer) As Boolean Dim result As Integer fileNumber = FreeFile result = Open(fileName For Input As # fileNumber) If result <> 0 Then fileNumber = 0 Return False Else Return True End If End Function   Dim fn As Integer Var b = tryOpenFile("xxx.zyz", fn) '' this file doesn't exist Print b, fn b = tryOpenFile("input.txt", fn) '' this file does exist Print b, fn Close # fn   ' Another way is to use a user defined type   Type FileOpenInfo opened As Boolean fn As Integer End Type   Function tryOpenFile2(fileName As String) As FileOpenInfo Dim foi As FileOpenInfo foi.fn = FreeFile Dim result As Integer result = Open(fileName For Input As # foi.fn) If result <> 0 Then foi.fn = 0 foi.opened = False Else foi.Opened = True End If Return foi End Function   Print Var foi = tryOpenFile2("xxx.zyz") Print foi.opened, foi.fn foi = tryOpenFile2("input.txt") Print foi.opened, foi.fn Close # foi.fn   Print Print "Press any key to quit" Sleep
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).
#AutoHotkey
AutoHotkey
a = 1,2,1,4,5,2,15,1,3,4 Sort, a, a, NUD`, MsgBox % a ; 1,2,3,4,5,15
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the first 15 members of the sequence. Find and show here, the first duplicated number in the sequence. Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. References A005132, The On-Line Encyclopedia of Integer Sequences. The Slightly Spooky Recamán Sequence, Numberphile video. Recamán's sequence, on Wikipedia.
#BASIC
BASIC
10 DEFINT A-Z: DIM A(100) 20 PRINT "First 15 terms:" 30 FOR N=0 TO 14: GOSUB 100: PRINT A(N);: NEXT 35 PRINT 40 PRINT "First repeated term:" 50 GOSUB 100 55 FOR M=0 TO N-1: IF A(M)=A(N) THEN 70 ELSE NEXT 60 N=N+1: GOTO 50 70 PRINT "A(";N;") =";A(N) 80 END 100 IF N=0 THEN A(0)=0: RETURN 110 X = A(N-1)-N: IF X<0 THEN 160 120 FOR M=0 TO N-1 130 IF A(M)=X THEN 160 140 NEXT 150 A(N)=X: RETURN 160 A(N)=A(N-1)+N: RETURN
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: function ToReducedRowEchelonForm(Matrix M) is lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r while M[i, lead] = 0 do i = i + 1 if rowCount = i then i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r If M[r, lead] is not 0 divide row r by M[r, lead] for 0 ≤ i < rowCount do if i ≠ r do Subtract M[i, lead] multiplied by row r from row i end if end for lead = lead + 1 end for end function For testing purposes, the RREF of this matrix: 1 2 -1 -4 2 3 -1 -11 -2 0 -3 22 is: 1 0 0 -8 0 1 0 1 0 0 1 -2
#360_Assembly
360 Assembly
* reduced row echelon form 27/08/2015 RREF CSECT USING RREF,R12 LR R12,R15 LA R10,1 lead=1 LA R7,1 LOOPR CH R7,NROWS do r=1 to nrows BH ELOOPR CH R10,NCOLS if lead>=ncols BNL ELOOPR LR R8,R7 i=r WHILE LR R1,R8 do while m(i,lead)=0 BCTR R1,0 MH R1,NCOLS LR R6,R10 lead BCTR R6,0 AR R1,R6 SLA R1,2 L R6,M(R1) m(i,lead) LTR R6,R6 BNZ EWHILE m(i,lead)<>0 LA R8,1(R8) i=i+1 CH R8,NROWS if i=nrows BNE EIF LR R8,R7 i=r LA R10,1(R10) lead=lead+1 CH R10,NCOLS if lead=ncols BE ELOOPR EIF B WHILE EWHILE LA R9,1 LOOPJ1 CH R9,NCOLS do j=1 to ncols BH ELOOPJ1 LR R1,R7 r BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 LA R3,M(R1) R3=@m(r,j) LR R1,R8 i BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 LA R4,M(R1) R4=@m(i,j) L R2,0(R3) MVC 0(2,R3),0(R4) swap m(i,j),m(r,j) ST R2,0(R4) LA R9,1(R9) j=j+1 B LOOPJ1 ELOOPJ1 LR R1,R7 r BCTR R1,0 MH R1,NCOLS LR R6,R10 lead BCTR R6,0 AR R1,R6 SLA R1,2 L R11,M(R1) n=m(r,lead) CH R11,=H'1' if n^=1 BE ELOOPJ2 LA R9,1 LOOPJ2 CH R9,NCOLS do j=1 to ncols BH ELOOPJ2 LR R1,R7 r BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 LA R5,M(R1) R5=@m(i,j) L R2,0(R5) m(r,j) LR R1,R11 n SRDA R2,32 DR R2,R1 m(r,j)/n ST R3,0(R5) m(r,j)=m(r,j)/n LA R9,1(R9) j=j+1 B LOOPJ2 ELOOPJ2 LA R8,1 LOOPI3 CH R8,NROWS do i=1 to nrows BH ELOOPI3 CR R8,R7 if i^=r BE ELOOPJ3 LR R1,R8 i BCTR R1,0 MH R1,NCOLS LR R6,R10 lead BCTR R6,0 AR R1,R6 SLA R1,2 L R11,M(R1) n=m(i,lead) LA R9,1 LOOPJ3 CH R9,NCOLS do j=1 to ncols BH ELOOPJ3 LR R1,R8 i BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 LA R4,M(R1) R4=@m(i,j) L R5,0(R4) m(i,j) LR R1,R7 r BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 L R3,M(R1) m(r,j) MR R2,R11 m(r,j)*n SR R5,R3 m(i,j)-m(r,j)*n ST R5,0(R4) m(i,j)=m(i,j)-m(r,j)*n LA R9,1(R9) j=j+1 B LOOPJ3 ELOOPJ3 LA R8,1(R8) i=i+1 B LOOPI3 ELOOPI3 LA R10,1(R10) lead=lead+1 LA R7,1(R7) r=r+1 B LOOPR ELOOPR LA R8,1 LOOPI4 CH R8,NROWS do i=1 to nrows BH ELOOPI4 SR R10,R10 pgi=0 LA R9,1 LOOPJ4 CH R9,NCOLS do j=1 to ncols BH ELOOPJ4 LR R1,R8 i BCTR R1,0 MH R1,NCOLS LR R6,R9 j BCTR R6,0 AR R1,R6 SLA R1,2 L R6,M(R1) m(i,j) LA R3,PG AR R3,R10 XDECO R6,0(R3) edit m(i,j) LA R10,12(10) pgi=pgi+12 LA R9,1(R9) j=j+1 B LOOPJ4 ELOOPJ4 XPRNT PG,48 print m(i,j) LA R8,1(R8) i=i+1 B LOOPI4 ELOOPI4 XR R15,R15 BR R14 NROWS DC H'3' NCOLS DC H'4' M DC F'1',F'2',F'-1',F'-4' DC F'2',F'3',F'-1',F'-11' DC F'-2',F'0',F'-3',F'22' PG DC CL48' ' YREGS END RREF
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#6502_Assembly
6502 Assembly
GetAbs: ;assumes value we want to abs() is loaded into accumulator eor #$ff clc adc #1 rts
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest integer less than or equal to this number--not the same as truncate or int)   ceiling   (smallest integer not less than this number--not the same as round up)   power   (xy ) Related task   Trigonometric Functions
#ACL2
ACL2
(floor 15 2) ;; This is the floor of 15/2 (ceiling 15 2) (expt 15 2) ;; 15 squared
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.
#C.23
C#
using System; using System.IO; using System.Linq;   public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);   static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }