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/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.)
|
#PicoLisp
|
PicoLisp
|
(in '(rec -q -c1 -tu16 - trim 0 2) # Record 2 seconds
(make
(while (rd 2)
(link @) ) ) )
|
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.)
|
#Python
|
Python
|
import pyaudio
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
data = stream.read(chunk)
print [ord(i) for i in data]
|
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.)
|
#Racket
|
Racket
|
#lang racket
(define (record n) (with-input-from-file "/dev/dsp" ( () (read-bytes n))))
(define (play bs) (display-to-file bs "/dev/dsp" #:exists 'append))
(play (record 65536))
|
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.)
|
#Raku
|
Raku
|
use Audio::PortAudio;
use Audio::Sndfile;
sub MAIN(Str $filename, Str :$source, Int :$buffer = 256) {
my $pa = Audio::PortAudio.new;
my $format = Audio::Sndfile::Info::Format::WAV +| Audio::Sndfile::Info::Subformat::PCM_16;
my $out-file = Audio::Sndfile.new(:$filename, channels => 1, samplerate => 44100, :$format, :w);
my $st;
if $source.defined {
my $index = 0;
for $pa.devices -> $device {
if $device.name eq $source {
else {
my $la = $device.default-high-input-latency;
my $si = Audio::PortAudio::StreamParameters.new(device => $index,
channel-count => 1,
sample-format => Audio::PortAudio::StreamFormat::Float32,
suggested-latency => ($la || 0.05e0 ));
$st = $pa.open-stream($si, Audio::PortAudio::StreamParameters, 44100, $buffer );
last;
}
}
$index++;
}
die "Couldn't find a device for '$source'" if !$st.defined;
}
else {
$st = $pa.open-default-stream(2,0, Audio::PortAudio::StreamFormat::Float32, 44100, $buffer);
}
$st.start;
my $p = Promise.new;
signal(SIGINT).act({
say "stopping recording";
$p.keep: "stopped";
$out-file.close;
$st.close;
exit;
});
my Channel $write-channel = Channel.new;
my $write-promise = start {
react {
whenever $write-channel -> $item {
if $p.status ~~ Planned {
$out-file.write-float($item[0], $item[1]);
$out-file.sync;
}
else {
done;
}
}
}
};
loop {
if $p.status ~~ Planned {
my $f = $buffer || $st.read-available;
if $f > 0 {
my $buff = $st.read($f,2, num32);
$write-channel.send([$buff, $f]);
}
}
else {
last;
}
}
}
|
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.
|
#Amazing_Hopper
|
Amazing Hopper
|
#include <hopper.h>
main:
s=""
load str ("archivo.txt") (s)
println ( "File loaded:\n",s )
exit(0)
|
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.
|
#AppleScript
|
AppleScript
|
set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")
-- short way: open, read and close in one step
set fileContent to read file pathToTextFile
-- long way: open a file reference, read content and close access
set fileRef to open for access pathToTextFile
set fileContent to read fileRef
close access fileRef
|
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.
|
#PHP
|
PHP
|
<?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
|
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.
|
#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.
|
#Raku
|
Raku
|
class Foo {
has $!a = now;
has Str $.b;
has Int $.c is rw;
}
my $object = Foo.new: b => "Hello", c => 42;
for $object.^attributes {
say join ", ", .name, .readonly, .container.^name, .get_value($object);
}
|
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.
|
#REXX
|
REXX
|
j=2
abc.j= -4.12
say 'variable abc.2 (length' length(abc.2)')=' abc.2
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Ruby
|
Ruby
|
class Foo
@@xyz = nil
def initialize(name, age)
@name, @age = name, age
end
def add_sex(sex)
@sex = sex
end
end
p foo = Foo.new("Angel", 18) #=> #<Foo:0x0000000305a688 @name="Angel", @age=18>
p foo.instance_variables #=> [:@name, :@age]
p foo.instance_variable_defined?(:@age) #=> true
p foo.instance_variable_get(:@age) #=> 18
p foo.instance_variable_set(:@age, 19) #=> 19
p foo #=> #<Foo:0x0000000305a688 @name="Angel", @age=19>
foo.add_sex(:woman)
p foo.instance_variables #=> [:@name, :@age, :@sex]
p foo #=> #<Foo:0x0000000305a688 @name="Angel", @age=19, @sex=:woman>
foo.instance_variable_set(:@bar, nil)
p foo.instance_variables #=> [:@name, :@age, :@sex, :@bar]
p Foo.class_variables #=> [:@@xyz]
p Foo.class_variable_defined?(:@@xyz) #=> true
p Foo.class_variable_get(:@@xyz) #=> nil
p Foo.class_variable_set(:@@xyz, :xyz) #=> :xyz
p Foo.class_variable_get(:@@xyz) #=> :xyz
p Foo.class_variable_set(:@@abc, 123) #=> 123
p Foo.class_variables #=> [:@@xyz, :@@abc]
|
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
|
#Dyalect
|
Dyalect
|
func rep(s) {
var x = s.Length() / 2
while x > 0 {
if s.StartsWith(s.Substring(x)) {
return x
}
x -= 1
}
return 0
}
let m = [
"1001110011",
"1110111011",
"0010010010",
"1010101010",
"1111111111",
"0100101101",
"0100100",
"101",
"11",
"00",
"1"
]
for s in m {
if (rep(s) is n) && n > 0 {
print("\(s) \(n) rep-string \(s.Substring(n))")
} else {
print("\(s) not a rep-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
|
#F.23
|
F#
|
open System
open System.Text.RegularExpressions
[<EntryPoint>]
let main argv =
let str = "I am a string"
if Regex("string$").IsMatch(str) then Console.WriteLine("Ends with string.")
let rstr = Regex(" a ").Replace(str, " another ")
Console.WriteLine(rstr)
0
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Factor
|
Factor
|
USING: io kernel prettyprint regexp ;
IN: rosetta-code.regexp
"1000000" R/ 10+/ matches? . ! Does the entire string match the regexp?
"1001" R/ 10+/ matches? .
"1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere?
"blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print
|
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
|
#AutoIt
|
AutoIt
|
#AutoIt Version: 3.2.10.0
$mystring="asdf"
$reverse_string = ""
$string_length = StringLen($mystring)
For $i = 1 to $string_length
$last_n_chrs = StringRight($mystring, $i)
$nth_chr = StringTrimRight($last_n_chrs, $i-1)
$reverse_string= $reverse_string & $nth_chr
Next
MsgBox(0, "Reversed string is:", $reverse_string)
|
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.
|
#Lean
|
Lean
|
def repeat : ℕ → (ℕ → string) → string
| 0 f := "done"
| (n + 1) f := (f n) ++ (repeat n f)
#eval repeat 5 $ λ b : ℕ , "me "
|
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.
|
#LiveCode
|
LiveCode
|
rep "answer",3
command rep x,n
repeat n times
do merge("[[x]] [[n]]")
end repeat
end rep
|
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.)
|
#Harbour
|
Harbour
|
FRename( "input.txt","output.txt")
// or
RENAME input.txt TO output.txt
FRename( hb_ps() + "input.txt", hb_ps() + "output.txt")
|
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.)
|
#Haskell
|
Haskell
|
import System.IO
import System.Directory
main = do
renameFile "input.txt" "output.txt"
renameDirectory "docs" "mydocs"
renameFile "/input.txt" "/output.txt"
renameDirectory "/docs" "/mydocs"
|
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
|
#Groovy
|
Groovy
|
def text = new StringBuilder()
.append('---------- Ice and Fire ------------\n')
.append(' \n')
.append('fire, in end will world the say Some\n')
.append('ice. in say Some \n')
.append('desire of tasted I\'ve what From \n')
.append('fire. favor who those with hold I \n')
.append(' \n')
.append('... elided paragraph last ... \n')
.append(' \n')
.append('Frost Robert -----------------------\n').toString()
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
}
|
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
|
#Quackery
|
Quackery
|
[ $ "" swap
witheach
[ dup char A char M 1+ within
over char a char m 1+ within or
iff [ 13 + ]
else
[ dup char N char Z 1+ within
over char n char z 1+ within or
if [ 13 - ] ]
join ] ] is rot-13 ( $ --> $ )
|
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
|
#PowerBASIC
|
PowerBASIC
|
FUNCTION toRoman(value AS INTEGER) AS STRING
DIM arabic(0 TO 12) AS INTEGER
DIM roman(0 TO 12) AS STRING
ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
DIM i AS INTEGER
DIM result AS STRING
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
result = result & roman(i)
value = value - arabic(i)
LOOP
NEXT i
toRoman = result
END FUNCTION
FUNCTION PBMAIN
'Testing
? "2009 = " & toRoman(2009)
? "1666 = " & toRoman(1666)
? "3888 = " & toRoman(3888)
END FUNCTION
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func integer: ROMAN parse (in string: roman) is func
result
var integer: arabic is 0;
local
var integer: index is 0;
var integer: number is 0;
var integer: lastval is 0;
begin
for index range length(roman) downto 1 do
case roman[index] of
when {'M', 'm'}: number := 1000;
when {'D', 'd'}: number := 500;
when {'C', 'c'}: number := 100;
when {'L', 'l'}: number := 50;
when {'X', 'x'}: number := 10;
when {'V', 'v'}: number := 5;
when {'I', 'i'}: number := 1;
otherwise: raise RANGE_ERROR;
end case;
if number < lastval then
arabic -:= number;
else
arabic +:= number;
end if;
lastval := number;
end for;
end func;
const proc: main is func
begin
writeln(ROMAN parse "MCMXC");
writeln(ROMAN parse "MMVIII");
writeln(ROMAN parse "MDCLXVI");
end func;
|
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
|
#Ceylon
|
Ceylon
|
shared void repeatAString() {
print("ha".repeat(5));
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Frink
|
Frink
|
divMod[a, b] := [a div b, a mod b]
[num, remainder] = divMod[10, 3]
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#FunL
|
FunL
|
def addsub( x, y ) = (x + y, x - y)
val (sum, difference) = addsub( 33, 12 )
println( sum, difference, addsub(33, 12) )
|
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).
|
#AWK
|
AWK
|
$ awk 'BEGIN{split("a b c d c b a",a);for(i in a)b[a[i]]=1;r="";for(i in b)r=r" "i;print r}'
a b c d
|
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.
|
#BCPL
|
BCPL
|
get "libhdr"
// Generate the N'th term of the Recaman sequence
// given terms 0 to N-1.
let generate(a, n) be
a!n := n=0 -> 0, valof
$( let subterm = a!(n-1) - n
let addterm = a!(n-1) + n
if subterm <= 0 resultis addterm
for i=0 to n-1
if a!i = subterm resultis addterm
resultis subterm
$)
let start() be
$( let a = vec 50 and n = 15 and rep = ?
writef("First %N members:*N", n)
for i = 0 to n-1
$( generate(a, i)
writef("%N ", a!i)
$)
writef("*NFirst repeated term:*N")
rep := valof
$( generate(a, n)
for i = 0 to n-1
if a!i = a!n resultis n
n := n + 1
$) repeat
writef("a!%N = %N*N", rep, a!rep)
$)
|
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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 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
|
#ActionScript
|
ActionScript
|
public function RREF():Matrix {
var lead:uint, i:uint, j:uint, r:uint = 0;
for(r = 0; r < rows; r++) {
if(columns <= lead)
break;
i = r;
while(_m[i][lead] == 0) {
i++;
if(rows == i) {
i = r;
lead++;
if(columns == lead)
return this;
}
}
rowSwitch(i, r);
var val:Number = _m[r][lead];
for(j = 0; j < columns; j++)
_m[r][j] /= val;
for(i = 0; i < rows; i++) {
if(i == r)
continue;
val = _m[i][lead];
for(j = 0; j < columns; j++)
_m[i][j] -= val * _m[r][j];
}
lead++;
}
return this;
}
|
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
|
#Action.21
|
Action!
|
INCLUDE "H6:REALMATH.ACT"
PROC Euler(REAL POINTER e)
REAL x
IntToReal(1,x)
Exp(x,e)
RETURN
PROC Main()
REAL a,b,c
INT i
Put(125) PutE() ;clear screen
MathInit()
Euler(a)
Print("e=") PrintR(a)
PrintE(" by Exp(1)")
ValR("2",a)
Sqrt(a,b)
Print("Sqrt(") PrintR(a)
Print(")=") PrintR(b)
Print(" by Power(") PrintR(a)
PrintE(",0.5)")
ValR("2.5",a)
Ln(a,b)
Print("Ln(") PrintR(a)
Print(")=") PrintRE(b)
ValR("14.2",a)
Log10(a,b)
Print("Log10(") PrintR(a)
Print(")=") PrintRE(b)
ValR("-3.7",a)
Exp(a,b)
Print("Exp(") PrintR(a)
Print(")=") PrintRE(b)
ValR("2.6",a)
Exp10(a,b)
Print("Exp10(") PrintR(a)
Print(")=") PrintRE(b)
ValR("25.3",a)
ValR("1.3",b)
Power(a,b,c)
Print("Power(") PrintR(a)
Print(",") PrintR(b)
Print(")=") PrintRE(c)
ValR("-32.5",a)
RealAbs(a,b)
Print("Abs(") PrintR(a)
Print(")=") PrintR(b)
PrintE(" by bit manipulation")
ValR("23.15",a)
i=Floor(a)
Print("Floor(") PrintR(a)
PrintF(")=%I by own function%E",i)
ValR("-23.15",a)
i=Floor(a)
Print("Floor(") PrintR(a)
PrintF(")=%I by own function%E",i)
ValR("23.15",a)
i=Ceiling(a)
Print("Ceiling(") PrintR(a)
PrintF(")=%I by own function%E",i)
ValR("-23.15",a)
i=Ceiling(a)
Print("Ceiling(") PrintR(a)
PrintF(")=%I by own function%E",i)
PutE()
PrintE("There is no support in Action! for pi.")
RETURN
|
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
|
#ActionScript
|
ActionScript
|
Math.E; //e
Math.PI; //pi
Math.sqrt(u); //square root of u
Math.log(u); //natural logarithm of u
Math.exp(u); //e to the power of u
Math.abs(u); //absolute value of u
Math.floor(u);//floor of u
Math.ceil(u); //ceiling of u
Math.pow(u,v);//u to the power of v
|
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.2B.2B
|
C++
|
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
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.)
|
#Scala
|
Scala
|
import java.io.{File, IOException}
import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream}
import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine}
object SoundRecorder extends App {
// record duration, in milliseconds
final val RECORD_TIME = 60000 // 1 minute
// path and format of the wav file
val (wavFile, fileType) = (new File("RecordAudio.wav"), AudioFileFormat.Type.WAVE)
val format = new AudioFormat(/*sampleRate =*/ 16000f,
/*sampleSizeInBits =*/ 16,
/*channels =*/ 2,
/*signed =*/ true,
/*bigEndian =*/ true)
val info = new DataLine.Info(classOf[TargetDataLine], format)
val line: TargetDataLine = AudioSystem.getLine(info).asInstanceOf[TargetDataLine]
// Entry to run the program
// Creates a new thread that waits for a specified of time before stopping
new Thread(new Runnable() {
def run() {
try {
Thread.sleep(RECORD_TIME)
} catch {
case ex: InterruptedException => ex.printStackTrace()
}
finally {
line.stop()
line.close()
}
println("Finished")
}
}).start()
//Captures the sound and record into a WAV file
try {
// checks if system supports the data line
if (AudioSystem.isLineSupported(info)) {
line.open(format)
line.start() // start capturing
println("Recording started")
AudioSystem.write(new AudioInputStream(line), fileType, wavFile)
} else println("Line not supported")
} catch {
case ex: LineUnavailableException => ex.printStackTrace()
case ioe: IOException => ioe.printStackTrace()
}
}
|
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.
|
#Arturo
|
Arturo
|
contents: read "input.txt"
|
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.
|
#ATS
|
ATS
|
val s = fileref_get_file_string (stdin_ref)
|
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.
|
#Python
|
Python
|
import inspect
# Sample classes for inspection
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Super method'
@staticmethod
def supStatic():
return 'static method'
class Other(object):
def otherMethod(self):
return 'other method'
class Sub(Other, Super):
def __init__(self, name, *args):
super(Sub, self).__init__(name);
self.rest = args;
self.methods = {}
def __dir__(self):
return list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
+ self.methods.keys() \
))
def __getattr__(self, name):
if name in self.methods:
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
if self.methods[name].__code__.co_varnames[0] == 'self':
return self.methods[name].__get__(self, type(self))
if self.methods[name].__code__.co_varnames[0] == 'cls':
return self.methods[name].__get__(type(self), type)
return self.methods[name]
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __str__(self):
return "Sub(%s)" % self.name
def doSub():
return 'did sub stuff'
@classmethod
def cls(cls):
return 'cls method (in Sub)'
@classmethod
def subCls(cls):
return 'Sub method'
@staticmethod
def subStatic():
return 'Sub method'
sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x
# names
[method for method in dir(sub) if callable(getattr(sub, method))]
# instance methods
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
#['__dir__', '__getattr__', '__init__', '__str__', 'doSub', 'doSup', 'otherMethod', 'strs']
# class methods
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
#['__subclasshook__', 'cls', 'subCls', 'supCls']
# static & free dynamic methods
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
#['incr', 'subStatic', 'supStatic']
# names & values; doesn't include wrapped, C-native methods
inspect.getmembers(sub, predicate=inspect.ismethod)
# names using inspect
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
#['__dir__', '__getattr__', '__init__', '__str__', 'cls', 'doSub', 'doSup', 'otherMethod', 'strs', 'subCls', 'supCls']
|
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.
|
#Scala
|
Scala
|
object ListProperties extends App {
private val obj = new {
val examplePublicField: Int = 42
private val examplePrivateField: Boolean = true
}
private val clazz = obj.getClass
println("All public methods (including inherited):")
clazz.getFields.foreach(f => println(s"${f}\t${f.get(obj)}"))
println("\nAll declared fields (excluding inherited):")
clazz.getDeclaredFields.foreach(f => println(s"${f}}"))
}
|
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.
|
#Smalltalk
|
Smalltalk
|
someObject class instVarNames
|
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.
|
#Tcl
|
Tcl
|
% package require Tk
8.6.5
% . configure
{-bd -borderwidth} {-borderwidth borderWidth BorderWidth 0 0} {-class class Class Toplevel Tclsh}
{-menu menu Menu {} {}} {-relief relief Relief flat flat} {-screen screen Screen {} {}} {-use use Use {} {}}
{-background background Background #d9d9d9 #d9d9d9} {-bg -background} {-colormap colormap Colormap {} {}}
{-container container Container 0 0} {-cursor cursor Cursor {} {}} {-height height Height 0 0}
{-highlightbackground highlightBackground HighlightBackground #d9d9d9 #d9d9d9}
{-highlightcolor highlightColor HighlightColor #000000 #000000}
{-highlightthickness highlightThickness HighlightThickness 0 0} {-padx padX Pad 0 0} {-pady padY Pad 0 0}
{-takefocus takeFocus TakeFocus 0 0} {-visual visual Visual {} {}} {-width width Width 0 0}
|
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
|
#EchoLisp
|
EchoLisp
|
(lib 'list) ;; list-rotate
;; a list is a rep-list if equal? to itself after a rotation of lam units
;; lam <= list length / 2
;; truncate to a multiple of lam before rotating
;; try cycles in decreasing lam order (longest wins)
(define (cyclic? cyclic)
(define len (length cyclic))
(define trunc null)
(if (> len 1)
(for ((lam (in-range (quotient len 2) 0 -1)))
(set! trunc (take cyclic (- len (modulo len lam))))
#:break (equal? trunc (list-rotate trunc lam)) => (list->string (take cyclic lam))
'no-rep )
'too-short-no-rep))
|
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
|
#Forth
|
Forth
|
include ffl/rgx.fs
\ Create a regular expression variable 'exp' in the dictionary
rgx-create exp
\ Compile an expression
s" Hello (World)" exp rgx-compile [IF]
.( Regular expression successful compiled.) cr
[THEN]
\ (Case sensitive) match a string with the expression
s" Hello World" exp rgx-cmatch? [IF]
.( String matches with the expression.) cr
[ELSE]
.( No match.) cr
[THEN]
|
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
|
#FreeBASIC
|
FreeBASIC
|
Dim As String text = "I am a text"
If Right(text, 4) = "text" Then
Print "'" + text + "' ends with 'text'"
End If
Dim As Integer i = Instr(text, "am")
text = Left(text, i - 1) + "was" + Mid(text, i + 2)
Print "replace 'am' with 'was' = " + text
Sleep
|
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
|
#Avail
|
Avail
|
"asfd" 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.
|
#Lua
|
Lua
|
function myFunc ()
print("Sure looks like a function in here...")
end
function rep (func, times)
for count = 1, times do
func()
end
end
rep(myFunc, 4)
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
repeat[f_, n_] := Do[f[], {n}];
repeat[Print["Hello, world!"] &, 5];
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#HicEst
|
HicEst
|
WRITE(FIle='input.txt', REName='.\output.txt')
SYSTEM(DIR='E:\HicEst\Rosetta')
WRITE(FIle='.\docs', REName='.\mydocs')
WRITE(FIle='\input.txt', REName='\output.txt')
SYSTEM(DIR='\')
WRITE(FIle='\docs', REName='\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.)
|
#Icon_and_Unicon
|
Icon and Unicon
|
every dir := !["./","/"] do {
rename(f := dir || "input.txt", dir || "output.txt") |stop("failure for file rename ",f)
rename(f := dir || "docs", dir || "mydocs") |stop("failure for directory rename ",f)
}
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); 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
|
#Haskell
|
Haskell
|
revstr :: String -> String
revstr = unwords . reverse . words -- point-free style
--equivalent:
--revstr s = unwords (reverse (words s))
revtext :: String -> String
revtext = unlines . map revstr . lines -- applies revstr to each line independently
test = revtext "---------- 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" --multiline string notation requires \ at end and start of lines, and \n to be manually input
|
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
|
#R
|
R
|
rot13 <- function(x)
{
old <- paste(letters, LETTERS, collapse="", sep="")
new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="")
chartr(old, new, x)
}
x <- "The Quick Brown Fox Jumps Over The Lazy Dog!.,:;'#~[]{}"
rot13(x) # "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!.,:;'#~[]{}"
x2 <- paste(letters, LETTERS, collapse="", sep="")
rot13(x2) # "nNoOpPqQrRsStTuUvVwWxXyYzZaAbBcCdDeEfFgGhHiIjJkKlLmM"
|
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
|
#PowerShell
|
PowerShell
|
Filter ToRoman {
$output = ''
if ($_ -ge 4000) {
throw 'Number too high'
}
$current = 1000
$subtractor = 'M'
$whole = $False
$decimal = $_
'C','D','X','L','I','V',' ' `
| %{
$divisor = $current
if ($whole = !$whole) {
$current /= 10
$subtractor = $_ + $subtractor[0]
$_ = $subtractor[1]
}
else {
$divisor *= 5
$subtractor = $subtractor[0] + $_
}
$multiple = [Math]::floor($decimal / $divisor)
if ($multiple) {
$output += [string]$_ * $multiple
$decimal %= $divisor
}
if ($decimal -ge ($divisor -= $current)) {
$output += $subtractor
$decimal -= $divisor
}
}
$output
}
|
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.
|
#SenseTalk
|
SenseTalk
|
function RomanNumeralsDecode numerals
put {
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1
} into values
put 0 into total
repeat with each character letter of numerals
if values.(character the counter + 1 of numerals) is less than or equal to values.(letter)
add values.(letter) to total
else
subtract values.(letter) from total
end if
end repeat
return total
end RomanNumeralsDecode
|
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
|
#Clipper
|
Clipper
|
Replicate( "Ha", 5 )
|
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
|
#Clojure
|
Clojure
|
(apply str (repeat 5 "ha"))
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#FutureBasic
|
FutureBasic
|
include "ConsoleWindow"
local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long )
dim as Str255 s
// Test if incoming string is empty, and exit function if it is
if strIn[0] == 0 then exit fn
// Prepend this string to incoming string and return it
s = "Here is your original string: "
strOut.nil$ = s + strIn
// Get length of combined string and return it
// Note: In FutureBasic string[0] is interchangeable with Len(string)
letterCount.nil& = strIn[0] + s[0]
end fn
dim as Str255 outStr
dim as long outCount
fn ReturnMultipleValues( "Hello, World!", @outStr, @outCount )
print outStr; ". The combined strings have"; outCount; " letters in them."
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
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).
|
#BASIC256
|
BASIC256
|
arraybase 1
max = 10
dim res(max)
dim dat(max)
dat[1] = 1: dat[2] = 2: dat[3] = 1: dat[4] = 4: dat[5] = 5
dat[6] = 2: dat[7] = 15: dat[8] = 1: dat[9] = 3: dat[10] = 4
res[1] = dat[1]
cont = 1
posic = 1
while posic < max
posic += 1
esnuevo = 1
indice = 1
while indice <= cont and esnuevo = 1
if dat[posic] = res[indice] then esnuevo = 0
indice += 1
end while
if esnuevo = 1 then
cont += 1
res[cont] = dat[posic]
end if
end while
for i = 1 to cont
print res[i]; " ";
next i
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.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
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
|
#Ada
|
Ada
|
generic
type Element_Type is private;
Zero : Element_Type;
with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
type Matrix is
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
|
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
|
#Ada
|
Ada
|
Ada.Numerics.e -- Euler's number
Ada.Numerics.pi -- pi
sqrt(x) -- square root
log(x, base) -- logarithm to any specified base
exp(x) -- exponential
abs(x) -- absolute value
S'floor(x) -- Produces the floor of an instance of subtype S
S'ceiling(x) -- Produces the ceiling of an instance of subtype S
x**y -- x raised to the y power
|
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.
|
#Clojure
|
Clojure
|
(require '[clojure.java.io :as jio]
'[clojure.string :as str])
(defn remove-lines1 [filepath start nskip]
(let [lines (str/split-lines (slurp filepath))
new-lines (concat (take (dec start) lines)
(drop (+ (dec start) nskip) lines))
diff (- (count lines) (count new-lines))]
(when-not (zero? diff)
(println "WARN: You are trying to remove lines beyond EOF"))
(with-open [wrt (jio/writer (str filepath ".tmp"))]
(.write wrt (str/join "\n" new-lines)))
(.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
|
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.)
|
#Tcl
|
Tcl
|
package require sound
# Helper to do a responsive wait
proc delay t {after $t {set ::doneDelay ok}; vwait ::doneDelay}
# Make an in-memory recording object
set recording [snack::sound -encoding "Lin16" -rate 44100 -channels 1]
# Set it doing the recording, wait for a second, and stop
$recording record -append true
delay 1000
$recording stop
# Convert the internal buffer to viewable numbers, and print them out
binary scan [$recording data -byteorder littleEndian] s* words
puts [join $words ", "]
# Destroy the recording object
$recording destroy
|
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.)
|
#Wee_Basic
|
Wee Basic
|
print 1 "Recording..."
micrec
print 1 "Playing..."
micpla
end
|
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.
|
#AutoHotkey
|
AutoHotkey
|
fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.
|
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.
|
#AutoIt
|
AutoIt
|
$fileOpen = FileOpen("file.txt")
$fileRead = FileRead($fileOpen)
FileClose($fileOpen)
|
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.
|
#Raku
|
Raku
|
class Foo {
method foo ($x) { }
method bar ($x, $y) { }
method baz ($x, $y?) { }
}
my $object = Foo.new;
for $object.^methods {
say join ", ", .name, .arity, .count, .signature.gist
}
|
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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p In obj.GetType().GetProperties(flags)
Where p.GetIndexParameters().Length = 0
Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
End Function
Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
End Function
Sub Main()
Dim t As New TestClass()
Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
For Each prop In GetPropertyValues(t, flags)
Console.WriteLine(prop)
Next
For Each field In GetFieldValues(t, flags)
Console.WriteLine(field)
Next
End Sub
End Module
|
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
|
#Elixir
|
Elixir
|
defmodule Rep_string do
def find(""), do: IO.puts "String was empty (no repetition)"
def find(str) do
IO.puts str
rep_pos = Enum.find(div(String.length(str),2)..1, fn pos ->
String.starts_with?(str, String.slice(str, pos..-1))
end)
if rep_pos && rep_pos>0 do
IO.puts String.duplicate(" ", rep_pos) <> String.slice(str, 0, rep_pos)
else
IO.puts "(no repetition)"
end
IO.puts ""
end
end
strs = ~w(1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1)
Enum.each(strs, fn str -> Rep_string.find(str) 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
|
#Frink
|
Frink
|
line = "My name is Inigo Montoya."
for [first, last] = line =~ %r/my name is (\w+) (\w+)/ig
{
println["First name is: $first"]
println["Last name is: $last"]
}
|
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
|
#AWK
|
AWK
|
function reverse(s)
{
p = ""
for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) }
return p
}
BEGIN {
print reverse("edoCattesoR")
}
|
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.
|
#min
|
min
|
("Hello" puts!) 3 times
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#MiniScript
|
MiniScript
|
sayHi = function()
print "Hi!"
end function
rep = function(f, n)
for i in range(1, n)
f
end for
end function
rep @sayHi, 3
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Io
|
Io
|
// rename file in current directory
f := File with("input.txt")
f moveTo("output.txt")
// rename file in root directory
f := File with("/input.txt")
f moveTo("/output.txt")
// rename directory in current directory
d := Directory with("docs")
d moveTo("mydocs")
// rename directory in root directory
d := Directory with("/docs")
d moveTo("/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.)
|
#J
|
J
|
frename=: 4 : 0
if. x -: y do. return. end.
if. IFUNIX do.
hostcmd=. [: 2!:0 '('"_ , ] , ' || true)'"_
hostcmd 'mv "',y,'" "',x,'"'
else.
'kernel32 MoveFileA i *c *c' 15!:0 y;x
end.
)
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
every write(rWords(&input))
end
procedure rWords(f)
every !f ? {
every (s := "") := genWords() || s
suspend s
}
end
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
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
|
#Racket
|
Racket
|
#!/usr/bin/env racket
#lang racket/base
(define (run i o)
(for ([ch (in-producer regexp-match #f #rx#"[a-zA-Z]" i 0 #f o)])
(define b (bytes-ref (car ch) 0))
(define a (if (< b 96) 65 97))
(write-byte (+ (modulo (+ 13 (- b a)) 26) a))))
(require racket/cmdline)
(command-line
#:help-labels "(\"-\" specifies standard input)"
#:args files
(for ([f (if (null? files) '("-") files)])
(if (equal? f "-")
(run (current-input-port) (current-output-port))
(call-with-input-file f (λ(i) (run i (current-output-port)))))))
|
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
|
#Prolog
|
Prolog
|
:- use_module(library(clpfd)).
roman :-
LA = [ _ , 2010, _, 1449, _],
LR = ['MDCCLXXXIX', _ , 'CX', _, 'MDCLXVI'],
maplist(roman, LA, LR),
maplist(my_print,LA, LR).
roman(A, R) :-
A #> 0,
roman(A, [u, t, h, th], LR, []),
label([A]),
parse_Roman(CR, LR, []),
atom_chars(R, CR).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% using DCG
roman(0, []) --> [].
roman(N, [H | T]) -->
{N1 #= N / 10,
N2 #= N mod 10},
roman(N1, T),
unity(N2, H).
unity(1, u) --> ['I'].
unity(1, t) --> ['X'].
unity(1, h) --> ['C'].
unity(1, th)--> ['M'].
unity(4, u) --> ['IV'].
unity(4, t) --> ['XL'].
unity(4, h) --> ['CD'].
unity(4, th)--> ['MMMM'].
unity(5, u) --> ['V'].
unity(5, t) --> ['L'].
unity(5, h) --> ['D'].
unity(5, th)--> ['MMMMM'].
unity(9, u) --> ['IX'].
unity(9, t) --> ['XC'].
unity(9, h) --> ['CM'].
unity(9, th)--> ['MMMMMMMMM'].
unity(0, _) --> [].
unity(V, U)-->
{V #> 5,
V1 #= V - 5},
unity(5, U),
unity(V1, U).
unity(V, U) -->
{V #> 1, V #< 4,
V1 #= V-1},
unity(1, U),
unity(V1, U).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extraction of roman "lexeme"
parse_Roman(['C','M'|T]) -->
['CM'],
parse_Roman(T).
parse_Roman(['C','D'|T]) -->
['CD'],
parse_Roman(T).
parse_Roman(['X','C'| T]) -->
['XC'],
parse_Roman(T).
parse_Roman(['X','L'| T]) -->
['XL'],
parse_Roman(T).
parse_Roman(['I','X'| T]) -->
['IX'],
parse_Roman(T).
parse_Roman(['I','V'| T]) -->
['IV'],
parse_Roman(T).
parse_Roman([H | T]) -->
[H],
parse_Roman(T).
parse_Roman([]) -->
[].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
my_print(A, R) :-
format('~w in roman is ~w~n', [A, R]).
|
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.
|
#Sidef
|
Sidef
|
func roman2arabic(roman) {
var arabic = 0
var last_digit = 1000
static m = Hash(
I => 1,
V => 5,
X => 10,
L => 50,
C => 100,
D => 500,
M => 1000,
)
roman.uc.chars.map{m{_} \\ 0}.each { |digit|
if (last_digit < digit) {
arabic -= (2 * last_digit)
}
arabic += (last_digit = digit)
}
return arabic
}
%w(MCMXC MMVIII MDCLXVI).each { |roman_digit|
"%-10s == %d\n".printf(roman_digit, roman2arabic(roman_digit))
}
|
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
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. REPEAT-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 HAHA PIC A(10).
PROCEDURE DIVISION.
MOVE ALL 'ha' TO HAHA.
DISPLAY HAHA.
STOP RUN.
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Go
|
Go
|
func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Groovy
|
Groovy
|
def addSub(x,y) {
[
sum: x+y,
difference: x-y
]
}
|
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).
|
#BBC_BASIC
|
BBC BASIC
|
DIM list$(15)
list$() = "Now", "is", "the", "time", "for", "all", "good", "men", \
\ "to", "come", "to", "the", "aid", "of", "the", "party."
num% = FNremoveduplicates(list$())
FOR i% = 0 TO num%-1
PRINT list$(i%) " " ;
NEXT
PRINT
END
DEF FNremoveduplicates(l$())
LOCAL i%, j%, n%, i$
n% = 1
FOR i% = 1 TO DIM(l$(), 1)
i$ = l$(i%)
FOR j% = 0 TO i%-1
IF i$ = l$(j%) EXIT FOR
NEXT
IF j%>=i% l$(n%) = i$ : n% += 1
NEXT
= n%
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
os << ", " << *i;
i = std::next(i);
}
return os << ']';
}
int main() {
using namespace std;
vector<int> a{ 0 };
set<int> used{ 0 };
set<int> used1000{ 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.find(next) != used.end()) {
next += 2 * n;
}
bool alreadyUsed = used.find(next) != used.end();
a.push_back(next);
if (!alreadyUsed) {
used.insert(next);
if (0 <= next && next <= 1000) {
used1000.insert(next);
}
}
if (n == 14) {
cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
}
if (!foundDup && alreadyUsed) {
cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
foundDup = true;
}
if (used1000.size() == 1001) {
cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
}
n++;
}
return 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
|
#Aime
|
Aime
|
rref(list l, integer rows, columns)
{
integer e, f, i, j, lead, r;
list u, v;
lead = r = 0;
while (r < rows && lead < columns) {
i = r;
while (!l.q_list(i)[lead]) {
i += 1;
if (i == rows) {
i = r;
lead += 1;
if (lead == columns) {
break;
}
}
}
if (lead == columns) {
break;
}
u = l[i];
l.spin(i, r);
e = u[lead];
if (e) {
for (j, f in u) {
u[j] = f / e;
}
}
for (i, v in l) {
if (i != r) {
e = v[lead];
for (j, f in v) {
v[j] = f - u[j] * e;
}
}
}
lead += 1;
r += 1;
}
}
display_2(list l)
{
for (, list u in l) {
u.ucall(o_winteger, -1, 4);
o_byte('\n');
}
}
main(void)
{
list l;
l = list(list(1, 2, -1, -4),
list(2, 3, -1, -11),
list(-2, 0, -3, 22));
rref(l, 3, 4);
display_2(l);
0;
}
|
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
|
#Aime
|
Aime
|
# e
exp(1);
# pi
2 * asin(1);
sqrt(x);
log(x);
exp(x);
fabs(x);
floor(x);
ceil(x);
pow(x, y);
|
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
|
#ALGOL_68
|
ALGOL 68
|
REAL x:=exp(1), y:=4*atan(1);
printf(($g(-8,5)"; "$,
exp(1), # e #
pi, # pi #
sqrt(x), # square root #
log(x), # logarithm base 10 #
ln(x), # natural logarithm #
exp(x), # exponential #
ABS x, # absolute value #
ENTIER x, # floor #
-ENTIER -x, # ceiling #
x ** y # power #
))
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defun remove-lines (filename start num)
(let ((tmp-filename (concatenate 'string filename ".tmp"))
(lines-omitted 0))
;; Open a temp file to write the result to
(with-open-file (out tmp-filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
;; Open the original file for reading
(with-open-file (in filename)
(loop
for line = (read-line in nil 'eof)
for i from 1
until (eql line 'eof)
;; Write the line to temp file if it is not in the omitted range
do (if (or (< i start)
(>= i (+ start num)))
(write-line line out)
(setf lines-omitted (1+ lines-omitted))))))
;; Swap in the temp file for the original
(delete-file filename)
(rename-file tmp-filename filename)
;; Warn if line removal went past the end of the file
(when (< lines-omitted num)
(warn "End of file reached with only ~d lines removed." lines-omitted))))
|
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.)
|
#Wren
|
Wren
|
/* record_sound.wren */
class C {
foreign static getInput(maxSize)
foreign static arecord(args)
foreign static aplay(name)
}
var name = ""
while (name == "") {
System.write("Enter output file name (without extension) : ")
name = C.getInput(80)
}
name = name + ".wav"
var rate = 0
while (!rate || !rate.isInteger || rate < 2000 || rate > 192000) {
System.write("Enter sampling rate in Hz (2000 to 192000) : ")
rate = Num.fromString(C.getInput(6))
}
var rateS = rate.toString
var dur = 0
while (!dur || dur < 5 || dur > 30) {
System.write("Enter duration in seconds (5 to 30) : ")
dur = Num.fromString(C.getInput(5))
}
var durS = dur.toString
System.print("\nOK, start speaking now...")
// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported.
var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name]
C.arecord(args.join(" "))
System.print("\n'%(name)' created on disk and will now be played back...")
C.aplay(name)
System.print("\nPlay-back completed.")
|
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.
|
#AWK
|
AWK
|
#!/usr/bin/awk -f
BEGIN {
## empty record separate,
RS="";
## read line (i.e. whole file) into $0
getline;
## print line number and content of line
print "=== line "NR,":",$0;
}
{
## no further line is read printed
print "=== line "NR,":",$0;
}
|
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.
|
#BaCon
|
BaCon
|
content$ = LOAD$(filename$)
|
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.
|
#Ring
|
Ring
|
# Project : Reflection/List methods
o1 = new test
aList = methods(o1)
for x in aList
cCode = "o1."+x+"()"
eval(cCode)
next
Class Test
func f1
see "hello from f1" + nl
func f2
see "hello from f2" + nl
func f3
see "hello from f3" + nl
func f4
see "hello from f4" + nl
|
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.
|
#Ruby
|
Ruby
|
# Sample classes for reflection
class Super
CLASSNAME = 'super'
def initialize(name)
@name = name
def self.superOwn
'super owned'
end
end
def to_s
"Super(#{@name})"
end
def doSup
'did super stuff'
end
def self.superClassStuff
'did super class stuff'
end
protected
def protSup
"Super's protected"
end
private
def privSup
"Super's private"
end
end
module Other
def otherStuff
'did other stuff'
end
end
class Sub < Super
CLASSNAME = 'sub'
attr_reader :dynamic
include Other
def initialize(name, *args)
super(name)
@rest = args;
@dynamic = {}
def self.subOwn
'sub owned'
end
end
def methods(regular=true)
super + @dynamic.keys
end
def method_missing(name, *args, &block)
return super unless @dynamic.member?(name)
method = @dynamic[name]
if method.arity > 0
if method.parameters[0][1] == :self
args.unshift(self)
end
if method.lambda?
# procs (hence methods) set missing arguments to `nil`, lambdas don't, so extend args explicitly
args += args + [nil] * [method.arity - args.length, 0].max
# procs (hence methods) discard extra arguments, lambdas don't, so discard arguments explicitly (unless lambda is variadic)
if method.parameters[-1][0] != :rest
args = args[0,method.arity]
end
end
method.call(*args)
else
method.call
end
end
def public_methods(all=true)
super + @dynamic.keys
end
def respond_to?(symbol, include_all=false)
@dynamic.member?(symbol) || super
end
def to_s
"Sub(#{@name})"
end
def doSub
'did sub stuff'
end
def self.subClassStuff
'did sub class stuff'
end
protected
def protSub
"Sub's protected"
end
private
def privSub
"Sub's private"
end
end
sup = Super.new('sup')
sub = Sub.new('sub', 0, 'I', 'two')
sub.dynamic[:incr] = proc {|i| i+1}
p sub.public_methods(false)
#=> [:superOwn, :subOwn, :respond_to?, :method_missing, :to_s, :methods, :public_methods, :dynamic, :doSub, :incr]
p sub.methods - Object.methods
#=> [:superOwn, :subOwn, :method_missing, :dynamic, :doSub, :protSub, :otherStuff, :doSup, :protSup, :incr]
p sub.public_methods - Object.public_methods
#=> [:superOwn, :subOwn, :method_missing, :dynamic, :doSub, :otherStuff, :doSup, :incr]
p sub.methods - sup.methods
#=> [:subOwn, :method_missing, :dynamic, :doSub, :protSub, :otherStuff, :incr]
# singleton/eigenclass methods
p sub.methods(false)
#=> [:superOwn, :subOwn, :incr]
p sub.singleton_methods
#=> [:superOwn, :subOwn]
|
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.
|
#Wren
|
Wren
|
#! instance_methods(m, n, o)
#! instance_properties(p, q, r)
class C {
construct new() {}
m() {}
n() {}
o() {}
p {}
q {}
r {}
}
var c = C.new() // create an object of type C
System.print("List of properties available for object 'c':")
for (property in c.type.attributes.self["instance_properties"]) System.print(property.key)
|
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.
|
#zkl
|
zkl
|
properties:=List.properties;
properties.println();
List(1,2,3).property(properties[0]).println(); // get value
List(1,2,3).Property(properties[0])().println(); // method that gets value
List(1,2,3).BaseClass(properties[0]).println(); // another way to get value
|
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
|
#Excel
|
Excel
|
REPCYCLES
=LAMBDA(s,
LET(
n, LEN(s),
xs, FILTERP(
LAMBDA(pfx,
s = TAKECYCLESTRING(n)(pfx)
)
)(
TAILCOLS(
INITS(
MID(s, 1, QUOTIENT(n, 2))
)
)
),
IF(ISERROR(xs), NA(), xs)
)
)
TAKECYCLESTRING
=LAMBDA(n,
LAMBDA(s,
LET(
lng, LEN(s),
MID(
IF(n < lng,
s,
REPT(s, CEILING.MATH(n / lng))
),
1, n
)
)
)
)
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Gambas
|
Gambas
|
Public Sub Main()
Dim sString As String = "Hello world!"
If sString Ends "!" Then Print sString & " ends with !"
If sString Begins "Hel" Then Print sString & " begins with 'Hel'"
sString = Replace(sString, "world", "moon")
Print sString
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
|
#GeneXus
|
GeneXus
|
&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim!
&string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups
|
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
|
#Babel
|
Babel
|
strrev: { str2ar ar2ls reverse ls2lf ar2str }
|
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.
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
1 П4
3 ^ 1 6 ПП 09 С/П
П7 <-> П0 КПП7 L0 12 В/О
ИП4 С/П КИП4 В/О
|
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.
|
#Modula-2
|
Modula-2
|
MODULE Repeat;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE F = PROCEDURE;
PROCEDURE Repeat(fun : F; c : INTEGER);
VAR i : INTEGER;
BEGIN
FOR i:=1 TO c DO
fun
END
END Repeat;
PROCEDURE Print;
BEGIN
WriteString("Hello");
WriteLn
END Print;
BEGIN
Repeat(Print, 3);
ReadChar
END Repeat.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.