task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#Raku
|
Raku
|
my $*TOLERANCE = 1e-12;
sub set-boundary(@mesh,@p1,@p2) {
@mesh[ @p1[0] ; @p1[1] ] = 1;
@mesh[ @p2[0] ; @p2[1] ] = -1;
}
sub solve(@p1, @p2, Int \w, Int \h) {
my @d = [0 xx w] xx h;
my @V = [0 xx w] xx h;
my @fixed = [0 xx w] xx h;
set-boundary(@fixed,@p1,@p2);
loop {
set-boundary(@V,@p1,@p2);
my $diff = 0;
for (flat ^h X ^w) -> \i, \j {
my @neighbors = (@V[i-1;j], @V[i;j-1], @V[i+1;j], @V[i;j+1]).grep: *.defined;
@d[i;j] = my \v = @V[i;j] - @neighbors.sum / @neighbors;
$diff += v × v unless @fixed[i;j];
}
last if $diff =~= 0;
for (flat ^h X ^w) -> \i, \j {
@V[i;j] -= @d[i;j];
}
}
my @current;
for (flat ^h X ^w) -> \i, \j {
@current[ @fixed[i;j]+1 ] += @d[i;j] × (?i + ?j + (i < h-1) + (j < w-1) );
}
(@current[2] - @current[0]) / 2
}
say 2 / solve (1,1), (6,7), 10, 10;
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#Elm
|
Elm
|
reversedPoem =
String.trim """
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
"""
reverseWords string =
string |> String.words |> List.reverse |> String.join " "
reverseLinesWords string =
string |> String.lines |> List.map reverseWords |> String.join "\n"
poem =
reverseLinesWords reversedPoem
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun reverse-words (line)
(insert
(format "%s\n"
(mapconcat 'identity (reverse (split-string line)) " "))))
(defun reverse-lines (lines)
(mapcar 'reverse-words lines))
(reverse-lines
'("---------- Ice and Fire ------------"
""
"fire, in end will world the say Some"
"ice. in say Some"
"desire of tasted I've what From"
"fire. favor who those with hold I"
""
"... elided paragraph last ..."
""
"Frost Robert ----------------------- "))
|
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
|
#Pop11
|
Pop11
|
define rot13(s);
lvars j, c;
for j from 1 to length(s) do
s(j) -> c;
if `A` <= c and c <= `M` or `a` <= c and c <= `m` then
c + 13 -> s(j);
elseif `N` <= c and c <= `Z` or `n` <= c and c <= `z` then
c - 13 -> s(j);
endif;
endfor;
s;
enddefine;
rot13('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') =>
|
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
|
#Phixmonti
|
Phixmonti
|
include ..\Utilitys.pmt
def romanEnc /# n -- s #/
var number
"" var res
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
( 50 "L" ) ( 40 "XL" ) ( 10 "X" ) ( 9 "IX" ) ( 5 "V" ) ( 4 "IV" ) ( 1 "I" ) )
len for
get 1 get
number over / int
number rot mod var number
swap 2 get rot dup if
for drop res over chain var res endfor
else
drop
endif
drop drop
endfor
drop
res
enddef
1968 romanEnc print
|
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.
|
#Red
|
Red
|
Red [
Purpose: "Arabic <-> Roman numbers converter"
Author: "Didier Cadieu"
Date: "07-Oct-2016"
]
table-r2a: reverse [1000 "M" 900 "CM" 500 "D" 400 "CD" 100 "C" 90 "XC" 50 "L" 40 "XL" 10 "X" 9 "IX" 5 "V" 4 "IV" 1 "I"]
roman-to-arabic: func [r [string!] /local a b e] [
a: 0
parse r [any [b: ["I" ["V" | "X" | none] | "X" ["L" | "C" | none] | "C" ["D" | "M" | none] | "V" | "L" | "D" | "M"] e: (a: a + select table-r2a copy/part b e)]]
a
]
; Example usage:
print roman-to-arabic "XXXIII"
print roman-to-arabic "MDCCCLXXXVIII"
print roman-to-arabic "MMXVI"
|
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
|
#BBC_BASIC
|
BBC BASIC
|
PRINT STRING$(5, "ha")
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#beeswax
|
beeswax
|
p <
p0~1<}~< d@<
_VT@1~>yg~9PKd@M'd;
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Eiffel
|
Eiffel
|
some_feature: TUPLE
do
Result := [1, 'j', "r"]
end
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Aime
|
Aime
|
index x;
list(1, 2, 3, 1, 2, 3, 4, 1).ucall(i_add, 1, x, 0);
x.i_vcall(o_, 1, " ");
o_newline();
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#Ada
|
Ada
|
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions;
use Ada.Text_IO;
procedure Remove_Lines_From_File is
Temporary: constant String := ".tmp";
begin
if Ada.Command_Line.Argument_Count /= 3 then
raise Constraint_Error;
end if;
declare
Filename: String := Ada.Command_Line.Argument(1);
First: Positive := Integer'Value(Ada.Command_Line.Argument(2));
Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1;
Input, Output: File_Type;
Line_Number: Positive := 1;
begin
Open(Input, In_File, Filename); -- open original file for reading
Create(Output, Out_File, Filename & Temporary); -- write to temp. file
while not End_Of_File(Input) loop
declare
Line: String := Get_Line(Input);
begin
if Line_Number < First or else Line_Number > Last then
Put_Line(Output, Line);
end if;
end;
Line_Number := Line_Number + 1;
end loop;
Close(Input);
Close(Output);
Ada.Directories.Rename(Old_Name => Filename & Temporary,
New_Name => Filename);
end;
exception
when Constraint_Error | Ada.IO_Exceptions.Name_Error =>
Put_Line("usage: " & Ada.Command_Line.Command_Name &
" <filename> <first> <length>");
Put_Line(" opens <filename> for reading and " &
"<filename>" & Temporary & " for temporary writing");
Put_Line(" requires first > 0, length >= 0");
end Remove_Lines_From_File;
|
http://rosettacode.org/wiki/Record_sound
|
Record sound
|
Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs might not record sound in the same format.)
|
#BBC_BASIC
|
BBC BASIC
|
wavfile$ = @dir$ + "capture.wav"
bitspersample% = 16
channels% = 2
samplespersec% = 44100
alignment% = bitspersample% * channels% / 8
bytespersec% = alignment% * samplespersec%
params$ = " bitspersample " + STR$(bitspersample%) + \
\ " channels " + STR$(channels%) + \
\ " alignment " + STR$(alignment%) + \
\ " samplespersec " + STR$(samplespersec%) + \
\ " bytespersec " + STR$(bytespersec%)
SYS "mciSendString", "close all", 0, 0, 0
SYS "mciSendString", "open new type waveaudio alias capture", 0, 0, 0
SYS "mciSendString", "set capture" + params$, 0, 0, 0 TO res%
IF res% ERROR 100, "Couldn't set capture parameters: " + STR$(res% AND &FFFF)
PRINT "Press SPACE to start recording..."
REPEAT UNTIL INKEY(1) = 32
SYS "mciSendString", "record capture", 0, 0, 0 TO res%
IF res% ERROR 100, "Couldn't start audio capture: " + STR$(res% AND &FFFF)
PRINT "Recording, press SPACE to stop..."
REPEAT UNTIL INKEY(1) = 32
SYS "mciSendString", "stop capture", 0, 0, 0
SYS "mciSendString", "save capture " + wavfile$, 0, 0, 0 TO res%
IF res% ERROR 100, "Couldn't save to WAV file: " + STR$(res% AND &FFFF)
SYS "mciSendString", "delete capture", 0, 0, 0
SYS "mciSendString", "close capture", 0, 0, 0
PRINT "Captured audio is stored in " wavfile$
|
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.)
|
#C
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void * record(size_t bytes)
{
int fd;
if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
void *a = malloc(bytes);
read(fd, a, bytes);
close(fd);
return a;
}
int play(void *buf, size_t len)
{
int fd;
if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0;
write(fd, buf, len);
close(fd);
return 1;
}
int main()
{
void *p = record(65536);
play(p, 65536);
return 0;
}
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Go
|
Go
|
package main
import (
"fmt"
"image"
"reflect"
)
type t int // A type definition
// Some methods on the type
func (r t) Twice() t { return r * 2 }
func (r t) Half() t { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}
func main() {
report(t(0))
report(image.Point{})
}
func report(x interface{}) {
v := reflect.ValueOf(x)
t := reflect.TypeOf(x) // or v.Type()
n := t.NumMethod()
fmt.Printf("Type %v has %d exported methods:\n", t, n)
const format = "%-6s %-46s %s\n"
fmt.Printf(format, "Name", "Method expression", "Method value")
for i := 0; i < n; i++ {
fmt.Printf(format,
t.Method(i).Name,
t.Method(i).Func.Type(),
v.Method(i).Type(),
)
}
fmt.Println()
}
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Julia
|
Julia
|
for obj in (Int, 1, 1:10, collect(1:10), now())
println("\nObject: $obj\nDescription:")
dump(obj)
end
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Kotlin
|
Kotlin
|
// version 1.1
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
open class BaseExample(val baseProp: String) {
protected val protectedProp: String = "inherited protected value"
}
class Example(val prop1: String, val prop2: Int, baseProp: String) : BaseExample(baseProp) {
private val privateProp: String = "private value"
val prop3: String
get() = "property without backing field"
val prop4 by lazy { "delegated value" }
}
fun main(args: Array<String>) {
val example = Example(prop1 = "abc", prop2 = 1, baseProp = "inherited public value")
val props = Example::class.memberProperties
for (prop in props) {
prop.isAccessible = true // makes non-public properties accessible
println("${prop.name.padEnd(13)} -> ${prop.get(example)}")
}
}
|
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
|
#C
|
C
|
#include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
http://rosettacode.org/wiki/Reflection/Get_source
|
Reflection/Get source
|
Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
|
#Wren
|
Wren
|
import "os" for Platform, Process
import "io" for File
import "/pattern" for Pattern
var getSourceLines = Fn.new {
var fileName = Process.allArguments[1]
var text = File.read(fileName)
var sep = Platform.isWindows ? "\r\n" : "\n"
return [fileName, text.split(sep)]
}
var res = getSourceLines.call()
var fileName = res[0]
var lines = res[1]
// look for getSourceLines function
var funcName = "getSourceLines"
var p = Pattern.new("+1/s")
var i = 1
var found = 0
for (line in lines) {
var t = p.splitAll(line.trim())
if (t[0] == "var" && t[1] == funcName && t[2] == "=" && t[3] == "Fn.new") {
found = i
break
}
i = i + 1
}
System.print("File name : %(fileName)")
System.print("Function name : %(funcName)")
System.print("Line number : %(found > 0 ? found : "Function not found")")
|
http://rosettacode.org/wiki/Reflection/Get_source
|
Reflection/Get source
|
Task
The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
|
#zkl
|
zkl
|
src:=File(__FILE__).read();
println("Src file is \"%s\" and has %d lines".fmt(__FILE__,src.len(1)));
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#C.23
|
C#
|
using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
Console.WriteLine(str);
}
}
|
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
|
#Amazing_Hopper
|
Amazing Hopper
|
#include <hopper.h>
main:
s="mañana será otro día"
reverse(s),strtoutf8, println
{0}return
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#Wren
|
Wren
|
class Printer {
construct new(id, ink) {
_id = id
_ink = ink
}
ink { _ink }
ink=(v) { _ink = v }
print(text) {
System.write("%(_id): ")
for (c in text) System.write(c)
System.print()
_ink = _ink - 1
}
}
var ptrMain = Printer.new("Main ", 5)
var ptrReserve = Printer.new("Reserve", 5)
var hd = [
"Humpty Dumpty sat on a wall.",
"Humpty Dumpty had a great fall.",
"All the king's horses and all the king's men",
"Couldn't put Humpty together again."
]
var mg = [
"Old Mother Goose",
"When she wanted to wander,",
"Would ride through the air",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon."
]
var task = Fn.new { |name|
var lines = (name == "Humpty Dumpty") ? hd : mg
for (line in lines) {
if (ptrMain.ink > 0) {
ptrMain.print(line)
Fiber.yield()
} else if (ptrReserve.ink > 0) {
ptrReserve.print(line)
Fiber.yield()
} else {
Fiber.abort("ERROR : Reserve printer ran out of ink in %(name) task.")
}
}
}
var rhymes = ["Humpty Dumpty", "Mother Goose"]
var tasks = List.filled(2, null)
for (i in 0..1) {
tasks[i] = Fiber.new(task)
tasks[i].call(rhymes[i])
}
while (true) {
for (i in 0..1) {
if (!tasks[i].isDone) {
var error = tasks[i].try()
if (error) {
System.print(error)
return
}
}
}
if (tasks.all { |task| task.isDone }) return
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Factor
|
Factor
|
3 [ "Hello!" print ] times
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Forth
|
Forth
|
: times ( xt n -- )
0 ?do dup execute loop drop ;
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#DCL
|
DCL
|
rename input.txt output.txt
rename docs.dir mydocs.dir
rename [000000]input.txt [000000]output.txt
rename [000000]docs.dir [000000]mydocs.dir
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Delphi
|
Delphi
|
program RenameFile;
{$APPTYPE CONSOLE}
uses SysUtils;
begin
SysUtils.RenameFile('input.txt', 'output.txt');
SysUtils.RenameFile('\input.txt', '\output.txt');
// RenameFile works for both files and folders
SysUtils.RenameFile('docs', 'MyDocs');
SysUtils.RenameFile('\docs', '\MyDocs');
end.
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#REXX
|
REXX
|
/*REXX program calculates the resistance between any two points on a resistor grid.*/
if 2=='f2'x then ohms = "ohms" /*EBCDIC machine? Then use 'ohms'. */
else ohms = "Ω" /* ASCII " " " Greek Ω.*/
parse arg high wide Arow Acol Brow Bcol digs . /*obtain optional arguments from the CL*/
if high=='' | high=="," then high= 10 /*Not specified? Then use the default.*/
if wide=='' | wide=="," then wide= 10 /* " " " " " " */
if Arow=='' | Arow=="," then Arow= 2 /* " " " " " " */
if Acol=='' | Acol=="," then Acol= 2 /* " " " " " " */
if Brow=='' | Brow=="," then Brow= 7 /* " " " " " " */
if Bcol=='' | Bcol=="," then Bcol= 8 /* " " " " " " */
if digs=='' | digs=="," then digs= 20 /* " " " " " " */
numeric digits digs /*use moderate decimal digs (precision)*/
minVal = 1'e-' || (digs*2) /*calculate the threshold minimal value*/
say ' minimum value is ' format(minVal,,,,0) " using " digs ' decimal digits'; say
say ' resistor mesh size is: ' wide "wide, " high 'high' ; say
say ' point A is at (row,col): ' Arow"," Acol
say ' point B is at (row,col): ' Brow"," Bcol
@.=0; cell.= 1
do until $<=minVal; v= 0
@.Arow.Acol= 1 ; cell.Arow.Acol= 0
@.Brow.Bcol= '-1' ; cell.Brow.Bcol= 0
$=0
do i=1 for high; im= i-1; ip= i+1
do j=1 for wide; n= 0; v= 0
if i\==1 then do; v= v + @.im.j; n= n+1; end
if j\==1 then do; jm= j-1; v= v + @.i.jm; n= n+1; end
if i<high then do; v= v + @.ip.j; n= n+1; end
if j<wide then do; jp= j+1; v= v + @.i.jp; n= n+1; end
v= @.i.j - v / n; #.i.j= v; if cell.i.j then $= $ + v*v
end /*j*/
end /*i*/
do r=1 for High
do c=1 for Wide; @.r.c= @.r.c - #.r.c
end /*c*/
end /*r*/
end /*until*/
say
Acur= #.Arow.Acol * sides(Arow, Acol)
Bcur= #.Brow.Bcol * sides(Brow, Bcol)
say ' resistance between point A and point B is: ' 4 / (Acur - Bcur) ohms
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sides: parse arg row,col; z=0; if row\==1 & row\==high then z= z+2; else z= z+1
if col\==1 & col\==wide then z= z+2; else z= z+1
return z
|
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
|
#F.23
|
F#
|
//Reverse words in a string. Nigel Galloway: July 14th., 2021
[" ---------- Ice and Fire ------------ ";
" ";
" fire, in end will world the say Some ";
" ice. in say Some ";
" desire of tasted I've what From ";
" fire. favour who those with hold I ";
" ";
" ... elided paragraph last ... ";
" ";
" Frost Robert ----------------------- "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
|
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
|
#PostScript
|
PostScript
|
/r13 {
4 dict begin
/rotc {
{
{{{64 gt} {91 lt}} all?} {65 - 13 + 26 mod 65 +} is?
{{{95 gt} {123 lt}} all?} {97 - 13 + 26 mod 97 +} is?
} cond
}.
{rotc} map cvstr
end}.
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#PHP
|
PHP
|
/**
* int2roman
* Convert any positive value of a 32-bit signed integer to its modern roman
* numeral representation. Numerals within parentheses are multiplied by
* 1000. ie. M == 1 000, (M) == 1 000 000, ((M)) == 1 000 000 000
*
* @param number - an integer between 1 and 2147483647
* @return roman numeral representation of number
*/
function int2roman($number)
{
if (!is_int($number) || $number < 1) return false; // ignore negative numbers and zero
$integers = array(900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);
$numerals = array('CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I');
$major = intval($number / 1000) * 1000;
$minor = $number - $major;
$numeral = $leastSig = '';
for ($i = 0; $i < sizeof($integers); $i++) {
while ($minor >= $integers[$i]) {
$leastSig .= $numerals[$i];
$minor -= $integers[$i];
}
}
if ($number >= 1000 && $number < 40000) {
if ($major >= 10000) {
$numeral .= '(';
while ($major >= 10000) {
$numeral .= 'X';
$major -= 10000;
}
$numeral .= ')';
}
if ($major == 9000) {
$numeral .= 'M(X)';
return $numeral . $leastSig;
}
if ($major == 4000) {
$numeral .= 'M(V)';
return $numeral . $leastSig;
}
if ($major >= 5000) {
$numeral .= '(V)';
$major -= 5000;
}
while ($major >= 1000) {
$numeral .= 'M';
$major -= 1000;
}
}
if ($number >= 40000) {
$major = $major/1000;
$numeral .= '(' . int2roman($major) . ')';
}
return $numeral . $leastSig;
}
|
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.
|
#REXX
|
REXX
|
/* Rexx */
Do
/* 1990 2008 1666 */
years = 'MCMXC MMVIII MDCLXVI'
Do y_ = 1 to words(years)
Say right(word(years, y_), 10) || ':' decode(word(years, y_))
End y_
Return
End
Exit
decode:
Procedure
Do
Parse upper arg roman .
If verify(roman, 'MDCLXVI') = 0 then Do
/* always insert the value of the least significant numeral */
decnum = rchar(substr(roman, length(roman), 1))
Do d_ = 1 to length(roman) - 1
If rchar(substr(roman, d_, 1)) < rchar(substr(roman, d_ + 1, 1)) then Do
/* Handle cases where numerals are not in descending order */
/* subtract the value of the numeral */
decnum = decnum - rchar(substr(roman, d_, 1))
End
else Do
/* Normal case */
/* add the value of the numeral */
decnum = decnum + rchar(substr(roman, d_, 1))
End
End d_
End
else Do
decnum = roman 'contains invalid roman numerals'
End
Return decnum
End
Exit
rchar:
Procedure
Do
Parse upper arg ch +1 .
select
when ch = 'M' then digit = 1000
when ch = 'D' then digit = 500
when ch = 'C' then digit = 100
when ch = 'L' then digit = 50
when ch = 'X' then digit = 10
when ch = 'V' then digit = 5
when ch = 'I' then digit = 1
otherwise digit = 0
end
Return digit
End
Exit
|
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
|
#Befunge
|
Befunge
|
v> ">:#,_v
>29*+00p>~:"0"- #v_v $
v ^p0p00:-1g00< $ >
v p00&p0-1g00+4*65< >00g1-:00p#^_@
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Elena
|
Elena
|
import system'routines;
import extensions;
extension op
{
MinMax(ref int minVal, ref int maxVal)
{
var ordered := self.ascendant();
minVal := ordered.FirstMember;
maxVal := ordered.LastMember
}
}
public program()
{
var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4};
values.MinMax(ref int min, ref int max);
console.printLine("Min: ",min," Max: ",max)
}
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Elixir
|
Elixir
|
defmodule RC do
def addsub(a, b) do
{a+b, a-b}
end
end
{add, sub} = RC.addsub(7, 4)
IO.puts "Add: #{add},\tSub: #{sub}"
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#ALGOL_68
|
ALGOL 68
|
# use the associative array in the Associate array/iteration task #
# this example uses strings - for other types, the associative #
# array modes AAELEMENT and AAKEY should be modified as required #
PR read "aArray.a68" PR
# returns the unique elements of list #
PROC remove duplicates = ( []STRING list )[]STRING:
BEGIN
REF AARRAY elements := INIT LOC AARRAY;
INT count := 0;
FOR pos FROM LWB list TO UPB list DO
IF NOT ( elements CONTAINSKEY list[ pos ] ) THEN
# first occurance of this element #
elements // list[ pos ] := "";
count +:= 1
FI
OD;
# construct an array of the unique elements from the #
# associative array - the new list will not necessarily be #
# in the original order #
[ count ]STRING result;
REF AAELEMENT e := FIRST elements;
FOR pos WHILE e ISNT nil element DO
result[ pos ] := key OF e;
e := NEXT elements
OD;
result
END; # remove duplicates #
# test the duplicate removal #
print( ( remove duplicates( ( "A", "B", "D", "A", "C", "F", "F", "A" ) ), newline ) )
|
http://rosettacode.org/wiki/Remove_lines_from_a_file
|
Remove lines from a file
|
Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from 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.
|
#ALGOL_68
|
ALGOL 68
|
# removes the specified number of lines from a file, starting at start line (numbered from 1) #
# returns TRUE if successful, FALSE otherwise #
PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOOL:
IF number of lines < 0 OR start line < 1
THEN
# invalid parameters #
print( ( "number of lines must be >= 0 and start line must be >= 1", newline ) );
FALSE
ELIF FILE temp file;
create( temp file, stand back channel ) /= 0
THEN
# unable to create a temporary output file #
print( ( "Unable to create temporary file", newline ) );
FALSE
ELIF NOT reset possible( temp file )
THEN
# rewinding the temporary file is not possible #
# we would have to get its name ( with "idf( temp file )", close it and re-open it #
print( ( "Temp file is not rewindable", newline ) );
FALSE
ELIF FILE input file;
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) );
FALSE
ELSE
# files opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the original file #
on logical file end( input file
, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
# copy the input file to the temp file #
WHILE STRING line;
get( input file, ( line, newline ) );
NOT at eof
DO
put( temp file, ( line, newline ) )
OD;
# copy the temp file back to the input, removing the specified lines #
close( input file );
IF open( input file, file name, stand out channel ) /= 0
THEN
# failed to open the original file for output #
print( ( "Unable to open ", file name, " for output", newline ) );
FALSE
ELSE
# opened OK - copy the temporary file #
reset( temp file ); # rewinds the input file #
at eof := FALSE;
on logical file end( temp file
, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
INT end line = ( start line - 1 ) + number of lines;
INT line number := 0;
WHILE STRING line;
get( temp file, ( line, newline ) );
NOT at eof
DO
# have another line #
line number +:= 1;
IF line number < start line OR line number > end line
THEN
put( input file, ( line, newline ) )
FI
OD;
# close the files #
close( input file );
scratch( temp file );
IF line number < start line
THEN
# didn't find the start line #
print( ( "Specified start line (", whole( start line, 0 ), ") not in ", file name, newline ) );
FALSE
ELIF line number < end line
THEN
# the ending line was not in the file #
print( ( "Final omitted line not in the file ", file name, newline ) );
FALSE
ELSE
# successful operation #
TRUE
FI
FI
FI # remove lines # ;
# test the line removal #
BEGIN
FILE t;
open( t, "test.txt", stand out channel );
print( ( "Before...", newline ) );
FOR i TO 10 DO
STRING line = whole( i, - ( ( i MOD 5 ) + 3 ) );
put( t, ( line, newline ) );
print( ( line, newline ) )
OD;
close( t );
remove lines( "test.txt", 2, 3 );
print( ( "After...", newline ) );
open( t, "test.txt", stand in channel );
FOR i TO 7 DO
STRING line;
get( t, ( line, newline ) );
print( ( line, newline ) )
OD;
close( t );
print( ( "----", newline ) )
END
|
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.)
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
using namespace std;
class recorder
{
public:
void start()
{
paused = rec = false; action = "IDLE";
while( true )
{
cout << endl << "==" << action << "==" << endl << endl;
cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl;
char c; cin >> c;
if( c > '0' && c < '6' )
{
switch( c )
{
case '1': record(); break;
case '2': play(); break;
case '3': pause(); break;
case '4': stop(); break;
case '5': stop(); return;
}
}
}
}
private:
void record()
{
if( mciExecute( "open new type waveaudio alias my_sound") )
{
mciExecute( "record my_sound" );
action = "RECORDING"; rec = true;
}
}
void play()
{
if( paused )
mciExecute( "play my_sound" );
else
if( mciExecute( "open tmp.wav alias my_sound" ) )
mciExecute( "play my_sound" );
action = "PLAYING";
paused = false;
}
void pause()
{
if( rec ) return;
mciExecute( "pause my_sound" );
paused = true; action = "PAUSED";
}
void stop()
{
if( rec )
{
mciExecute( "stop my_sound" );
mciExecute( "save my_sound tmp.wav" );
mciExecute( "close my_sound" );
action = "IDLE"; rec = false;
}
else
{
mciExecute( "stop my_sound" );
mciExecute( "close my_sound" );
action = "IDLE";
}
}
bool mciExecute( string cmd )
{
if( mciSendString( cmd.c_str(), NULL, 0, NULL ) )
{
cout << "Can't do this: " << cmd << endl;
return false;
}
return true;
}
bool paused, rec;
string action;
};
int main( int argc, char* argv[] )
{
recorder r; r.start();
return 0;
}
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#J
|
J
|
NB. define a stack class
coclass 'Stack'
create =: 3 : 'items =: i. 0'
push =: 3 : '# items =: items , < y'
top =: 3 : '> {: items'
pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;')
destroy =: codestroy
cocurrent 'base'
names_Stack_'' NB. all names
create destroy pop push top
'p' names_Stack_ 3 NB. verbs that start with p
pop push
NB. make an object. The dyadic definition of cownew invokes the create verb
S =: conew~ 'Stack'
names__S'' NB. object specific names
COCREATOR items
pop__S NB. introspection: get the verbs definition
3 : 0
a =. top 0
items =: }: items
a
)
NB. get the search path of object S
copath S
┌─────┬─┐
│Stack│z│
└─────┴─┘
names__S 0 NB. get the object specific data
COCREATOR items
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Java
|
Java
|
import java.lang.reflect.Method;
public class ListMethods {
public int examplePublicInstanceMethod(char c, double d) {
return 42;
}
private boolean examplePrivateInstanceMethod(String s) {
return true;
}
public static void main(String[] args) {
Class clazz = ListMethods.class;
System.out.println("All public methods (including inherited):");
for (Method m : clazz.getMethods()) {
System.out.println(m);
}
System.out.println();
System.out.println("All declared methods (excluding inherited):");
for (Method m : clazz.getDeclaredMethods()) {
System.out.println(m);
}
}
}
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Lingo
|
Lingo
|
obj = script("MyClass").new()
obj.foo = 23
obj.bar = 42
-- ...
-- show obj's property names and values
cnt = obj.count
repeat with i = 1 to cnt
put obj.getPropAt(i)&" = "&obj[i]
end repeat
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Lua
|
Lua
|
a = 1
b = 2.0
c = "hello world"
function listProperties(t)
if type(t) == "table" then
for k,v in pairs(t) do
if type(v) ~= "function" then
print(string.format("%7s: %s", type(v), k))
end
end
end
end
print("Global properties")
listProperties(_G)
print("Package properties")
listProperties(package)
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Nanoquery
|
Nanoquery
|
// declare a class that has fields to be listed
class Fields
declare static field1 = "this is a static field. it will not be listed"
declare field2
declare field3
declare field4
end
// list all the fields in the class
for fieldname in Fields.getFieldNames()
println fieldname
end
|
http://rosettacode.org/wiki/Rep-string
|
Rep-string
|
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For 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
|
#C.2B.2B
|
C++
|
#include <string>
#include <vector>
#include <boost/regex.hpp>
bool is_repstring( const std::string & teststring , std::string & repunit ) {
std::string regex( "^(.+)\\1+(.*)$" ) ;
boost::regex e ( regex ) ;
boost::smatch what ;
if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
std::string firstbracket( what[1 ] ) ;
std::string secondbracket( what[ 2 ] ) ;
if ( firstbracket.length( ) >= secondbracket.length( ) &&
firstbracket.find( secondbracket ) != std::string::npos ) {
repunit = firstbracket ;
}
}
return !repunit.empty( ) ;
}
int main( ) {
std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" ,
"1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ;
std::string theRep ;
for ( std::string myString : teststrings ) {
if ( is_repstring( myString , theRep ) ) {
std::cout << myString << " is a rep string! Here is a repeating string:\n" ;
std::cout << theRep << " " ;
}
else {
std::cout << myString << " is no rep string!" ;
}
theRep.clear( ) ;
std::cout << std::endl ;
}
return 0 ;
}
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
// match the complete string
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
// match a substring
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
// replace a substring
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}
|
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
|
#Apex
|
Apex
|
String str = 'Hello World!';
str = str.reverse();
system.debug(str);
|
http://rosettacode.org/wiki/Rendezvous
|
Rendezvous
|
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
|
#zkl
|
zkl
|
class OutOfInk(Exception.IOError){
const TEXT="Out of ink";
text=TEXT; // rename IOError to OutOfInk for this first/mother class
fcn init{ IOError.init(TEXT) } // this renames instances
}
class Printer{
var id, ink;
fcn init(_id,_ink){ id,ink=vm.arglist }
fcn print(line){
if(not ink) throw(OutOfInk);
println("%s: %s".fmt(id,line));
Atomic.sleep((0.0).random(0.01)); // don't let one thread dominate
ink-=1;
}
}
class RendezvousPrinter{ // the choke point between printers and tasks
var printers=Thread.List(); // a thread safe list
fcn init(_printers){ printers.extend(vm.arglist) }
fcn print(line){ // caller waits for print job to finish
var lines=Thread.List(); // fcn local [static] variable, the print queue
lines.write(line); // thread safe, stalls when full
// lines is racy - other threads are modifing it, length is suspect here
while(True){ // this thread can print that threads job
critical{ // creates a [global] mutex, automatically unlocks on exception
if(not printers) throw(OutOfInk); // No more printers to try
if(not lines) break; // only remove jobs in this serialized section
try{
printers[0].print(lines[0]); // can throw
lines.del(0); // successful print, remove job from queue
}catch(OutOfInk){ printers.del(0) } // Switch to the next printer
}
}
}
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Sub proc()
Print " proc called"
End Sub
Sub repeat(s As Sub, n As UInteger)
For i As Integer = 1 To n
Print Using "##"; i;
s()
Next
End Sub
repeat(@proc, 5)
Print
Print "Press any key to quit"
Sleep
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#E
|
E
|
for where in [<file:.>, <file:///>] {
where["input.txt"].renameTo(where["output.txt"], null)
where["docs"].renameTo(where["mydocs"], null)
}
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Elixir
|
Elixir
|
File.rename "input.txt","output.txt"
File.rename "docs", "mydocs"
File.rename "/input.txt", "/output.txt"
File.rename "/docs", "/mydocs"
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#Sidef
|
Sidef
|
var (w, h) = (10, 10)
var v = h.of { w.of(0) } # voltage
var f = h.of { w.of(0) } # fixed condition
var d = h.of { w.of(0) } # diff
var n = [] # neighbors
for i in ^h {
for j in (1 ..^ w ) { n[i][j] := [] << [i, j-1] }
for j in (0 ..^ w-1) { n[i][j] := [] << [i, j+1] }
}
for j in ^w {
for i in (1 ..^ h ) { n[i][j] := [] << [i-1, j] }
for i in (0 ..^ h-1) { n[i][j] := [] << [i+1, j] }
}
func set_boundary {
f[1][1] = 1; f[6][7] = -1;
v[1][1] = 1; v[6][7] = -1;
}
func calc_diff {
var total_diff = 0
for i,j in (^h ~X ^w) {
var w = n[i][j].map { |a| v.dig(a...) }.sum
d[i][j] = (w = (v[i][j] - w/n[i][j].len))
f[i][j] || (total_diff += w*w)
}
total_diff
}
func iter {
var diff = 1
while (diff > 1e-24) {
set_boundary()
diff = calc_diff()
for i,j in (^h ~X ^w) {
v[i][j] -= d[i][j]
}
}
var current = 3.of(0)
for i,j in (^h ~X ^w) {
current[ f[i][j] ] += (d[i][j] * n[i][j].len)
}
(current[1] - current[-1]) / 2
}
say "R = #{2 / iter()}"
|
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
|
#Factor
|
Factor
|
USING: io sequences splitting ;
IN: rosetta-code.reverse-words
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------"
"\n" split [ " " split reverse " " join ] map [ print ] each
|
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
|
#PowerBASIC
|
PowerBASIC
|
#COMPILE EXE
#COMPILER PBWIN 9.05
#DIM ALL
FUNCTION ROT13(BYVAL a AS STRING) AS STRING
LOCAL p AS BYTE PTR
LOCAL n AS BYTE, e AS BYTE
LOCAL res AS STRING
res = a
p = STRPTR(res)
n = @p
DO WHILE n
SELECT CASE n
CASE 65 TO 90
e = 90
n += 13
CASE 97 TO 122
e = 122
n += 13
CASE ELSE
e = 255
END SELECT
IF n > e THEN
n -= 26
END IF
@p = n
INCR p
n = @p
LOOP
FUNCTION = res
END FUNCTION
'testing:
FUNCTION PBMAIN () AS LONG
#DEBUG PRINT ROT13("abc")
#DEBUG PRINT ROT13("nop")
END FUNCTION
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Picat
|
Picat
|
go =>
List = [455,999,1990,1999,2000,2001,2008,2009,2010,2011,2012,1666,3456,3888,4000],
foreach(Val in List)
printf("%4d: %w\n", Val, roman_encode(Val))
end,
nl.
roman_encode(Val) = Res =>
if Val <= 0 then
Res := -1
else
Arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
Roman = ["M", "CM", "D", "CD", "C", "XC","L","XL","X","IX","V","IV","I"],
Res = "",
foreach(I in 1..Arabic.length)
while(Val >= Arabic[I])
Res := Res ++ Roman[I],
Val := Val - Arabic[I]
end
end
end.
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Ring
|
Ring
|
symbols = "MDCLXVI"
weights = [1000,500,100,50,10,5,1]
see "MCMXCIX = " + romanDec("MCMXCIX") + nl
see "MDCLXVI =" + romanDec("MDCLXVI") + nl
see "XXV = " + romanDec("XXV") + nl
see "CMLIV = " + romanDec("CMLIV") + nl
see "MMXI = " + romanDec("MMXI") + nl
func romanDec roman
n = 0
lastval = 0
arabic = 0
for i = len(roman) to 1 step -1
n = substr(symbols,roman[i])
if n > 0 n = weights[n] ok
if n < lastval arabic = arabic - n
else arabic = arabic + n ok
lastval = n
next
return arabic
|
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
|
#BQN
|
BQN
|
Repeat ← ×⟜≠ ⥊ ⊢
•Show 5 Repeat "Hello"
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Erlang
|
Erlang
|
% Put this code in return_multi.erl and run it as "escript return_multi.erl"
-module(return_multi).
main(_) ->
{C, D, E} = multiply(3, 4),
io:format("~p ~p ~p~n", [C, D, E]).
multiply(A, B) ->
{A * B, A + B, A - B}.
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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).
|
#Amazing_Hopper
|
Amazing Hopper
|
#include <hopper.h>
main:
x=-1
{30} rand array (x), mulby(10), ceil, mov(x)
{"Original Array:\n",x}, println
{x}array(SORT),
{x}sets(UNIQUE), mov(x)
{"Final array:\n",x}, println
y={}
{"C","Go","Go","C","Cobol","java","Ada"} pushall(y)
{"java","algol-68","C","java","fortran"} pushall(y)
{"\nOriginal Array:\n",y}, println
{y}array(SORT),
{y}sets(UNIQUE), mov(y)
{"Final array:\n",y}, println
exit(0)
|
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.
|
#Amazing_Hopper
|
Amazing Hopper
|
#include <hopper.h>
main:
.ctrlc
fd=0,fw=0
fopen(OPEN_READ,"archivo.txt")(fd)
if file error?
{"no pude abrir el archivo de lectura: "}
jsub(show error)
else
fcreate(CREATE_NORMAL,"archivoTmp.txt")(fw)
if file error?
{"no pude crear el archivo para escritura: "}
jsub(show error)
else
get arg number(2,desde), // from line
get arg number(3,hasta), // to line
line read=0
while( not(feof(fd)))
fread line(1000)(fd), ++line read
if(not( {line read} between(desde, hasta)))
{"\n"}cat,writeline(fw)
endif
wend
endif
endif
fclose(fw)
fclose(fd)
system("mv archivoTmp.txt archivo.txt")
exit(0)
.locals
show error:
file error, println
back
|
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.)
|
#ChucK
|
ChucK
|
// chuck this with other shreds to record to file
// example> chuck foo.ck bar.ck rec
// arguments: rec:<filename>
// get name
me.arg(0) => string filename;
if( filename.length() == 0 ) "foo.wav" => filename;
// pull samples from the dac
dac => Gain g => WvOut w => blackhole;
// this is the output file name
filename => w.wavFilename;
<<<"writing to file:", "'" + w.filename() + "'">>>;
// any gain you want for the output
.5 => g.gain;
// temporary workaround to automatically close file on remove-shred
null @=> w;
// infinite time loop...
// ctrl-c will stop it, or modify to desired duration
while( true ) 1::second => now;
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#JavaScript
|
JavaScript
|
// Sample classes for reflection
function Super(name) {
this.name = name;
this.superOwn = function() { return 'super owned'; };
}
Super.prototype = {
constructor: Super
className: 'super',
toString: function() { return "Super(" + this.name + ")"; },
doSup: function() { return 'did super stuff'; }
}
function Sub() {
Object.getPrototypeOf(this).constructor.apply(this, arguments);
this.rest = [].slice.call(arguments, 1);
this.subOwn = function() { return 'sub owned'; };
}
Sub.prototype = Object.assign(
new Super('prototype'),
{
constructor: Sub
className: 'sub',
toString: function() { return "Sub(" + this.name + ")"; },
doSub: function() { return 'did sub stuff'; }
});
Object.defineProperty(Sub.prototype, 'shush', {
value: function() { return ' non-enumerable'; },
enumerable: false // the default
});
var sup = new Super('sup'),
sub = new Sub('sub', 0, 'I', 'two');
Object.defineProperty(sub, 'quiet', {
value: function() { return 'sub owned non-enumerable'; },
enumerable: false
});
// get enumerable methods on an object and its ancestors
function get_method_names(obj) {
var methods = [];
for (var p in obj) {
if (typeof obj[p] == 'function') {
methods.push(p);
}
}
return methods;
}
get_method_names(sub);
//["subOwn", "superOwn", "toString", "doSub", "doSup"]
// get enumerable properties on an object and its ancestors
function get_property_names(obj) {
var properties = [];
for (var p in obj) {
properties.push(p);
}
return properties;
}
// alternate way to get enumerable method names on an object and its ancestors
function get_method_names(obj) {
return get_property_names(obj)
.filter(function(p) {return typeof obj[p] == 'function';});
}
get_method_names(sub);
//["subOwn", "superOwn", "toString", "doSub", "doSup"]
// get enumerable & non-enumerable method names set directly on an object
Object.getOwnPropertyNames(sub)
.filter(function(p) {return typeof sub[p] == 'function';})
//["subOwn", "shhh"]
// get enumerable method names set directly on an object
Object.keys(sub)
.filter(function(p) {return typeof sub[p] == 'function';})
//["subOwn"]
// get enumerable method names & values set directly on an object
Object.entries(sub)
.filter(function(p) {return typeof p[1] == 'function';})
//[["subOwn", function () {...}]]
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Nim
|
Nim
|
type
Foo = object
a: float
b: string
c: seq[int]
let f = Foo(a: 0.9, b: "hi", c: @[1,2,3])
for n, v in f.fieldPairs:
echo n, ": ", v
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo : NSObject {
int exampleIvar;
}
@property (nonatomic) double exampleProperty;
@end
@implementation Foo
- (instancetype)init {
self = [super init];
if (self) {
exampleIvar = 42;
_exampleProperty = 3.14;
}
return self;
}
@end
int main() {
id obj = [[Foo alloc] init];
Class clazz = [obj class];
NSLog(@"\Instance variables:");
unsigned int ivarCount;
Ivar *ivars = class_copyIvarList(clazz, &ivarCount);
for (unsigned int i = 0; i < ivarCount; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
const char *typeEncoding = ivar_getTypeEncoding(ivar);
// for simple types we can use Key-Value Coding to access it
// but in general we will have to use object_getIvar and cast it to the right type of function
// corresponding to the type of the instance variable
id value = [obj valueForKey:@(name)];
NSLog(@"%s\t%s\t%@", name, typeEncoding, value);
}
free(ivars);
NSLog(@"");
NSLog(@"Properties:");
unsigned int propCount;
objc_property_t *properties = class_copyPropertyList([Foo class], &propCount);
for (unsigned int i = 0; i < propCount; i++) {
objc_property_t p = properties[i];
const char *name = property_getName(p);
const char *attributes = property_getAttributes(p);
// for simple types we can use Key-Value Coding to access it
// but in general we will have to use objc_msgSend to call the getter,
// casting objc_msgSend to the right type of function corresponding to the type of the getter
id value = [obj valueForKey:@(name)];
NSLog(@"%s\t%s\t%@", name, attributes, value);
}
free(properties);
return 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
|
#Clojure
|
Clojure
|
(defn rep-string [s]
(let [len (count s)
first-half (subs s 0 (/ len 2))
test-group (take-while seq (iterate butlast first-half))
test-reptd (map (comp #(take len %) cycle) test-group)]
(some #(= (seq s) %) test-reptd)))
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Clojure
|
Clojure
|
(let [s "I am a string"]
;; match
(when (re-find #"string$" s)
(println "Ends with 'string'."))
(when-not (re-find #"^You" s)
(println "Does not start with 'You'."))
;; substitute
(println (clojure.string/replace s " a " " another "))
)
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Common_Lisp
|
Common Lisp
|
(let ((string "I am a string"))
(when (cl-ppcre:scan "string$" string)
(write-line "Ends with string"))
(unless (cl-ppcre:scan "^You" string )
(write-line "Does not start with 'You'")))
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#APL
|
APL
|
⌽'asdf'
fdsa
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Gambas
|
Gambas
|
Public Sub Main()
RepeatIt("RepeatableOne", 2)
RepeatIt("RepeatableTwo", 3)
End
'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call()
Public Sub RepeatIt(sDelegateName As String, iCount As Integer)
For iCounter As Integer = 1 To iCount
Object.Call(Me, sDelegateName, [])
Next
End
Public Sub RepeatableOne()
Print "RepeatableOne"
End
Public Sub RepeatableTwo()
Print "RepeatableTwo"
End
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Emacs_Lisp
|
Emacs Lisp
|
(rename-file "input.txt" "output.txt")
(rename-file "/input.txt" "/output.txt")
(rename-file "docs" "mydocs")
(rename-file "/docs" "/mydocs")
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#Erlang
|
Erlang
|
file:rename("input.txt","output.txt"),
file:rename( "docs", "mydocs" ),
file:rename( "/input.txt", "/output.txt" ),
file:rename( "/docs", "/mydocs" ).
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#Tcl
|
Tcl
|
package require Tcl 8.6; # Or 8.5 with the TclOO package
# This code is structured as a class with a little trivial DSL parser
# so it is easy to change what problem is being worked on.
oo::class create ResistorMesh {
variable forcePoints V fixed w h
constructor {boundaryConditions} {
foreach {op condition} $boundaryConditions {
switch $op {
size {
lassign $condition w h
set fixed [lrepeat $h [lrepeat $w 0]]
set V [lrepeat $h [lrepeat $w 0.0]]
}
fixed {
lassign $condition j i v
lset fixed $i $j [incr ctr]
lappend forcePoints $j $i $v
}
}
}
}
method CalculateDifferences {*dV} {
upvar 1 ${*dV} dV
set error 0.0
for {set i 0} {$i < $h} {incr i} {
for {set j 0} {$j < $w} {incr j} {
set v 0.0
set n 0
if {$i} {
set v [expr {$v + [lindex $V [expr {$i-1}] $j]}]
incr n
}
if {$j} {
set v [expr {$v + [lindex $V $i [expr {$j-1}]]}]
incr n
}
if {$i+1 < $h} {
set v [expr {$v + [lindex $V [expr {$i+1}] $j]}]
incr n
}
if {$j+1 < $w} {
set v [expr {$v + [lindex $V $i [expr {$j+1}]]}]
incr n
}
lset dV $i $j [set v [expr {[lindex $V $i $j] - $v/$n}]]
if {![lindex $fixed $i $j]} {
set error [expr {$error + $v**2}]
}
}
}
return $error
}
method FindCurrentFixpoint {epsilon} {
set dV [lrepeat $h [lrepeat $w 0.0]]
set current {0.0 0.0 0.0}
while true {
# Enforce the boundary conditions
foreach {j i v} $forcePoints {
lset V $i $j $v
}
# Compute the differences and the error
set error [my CalculateDifferences dV]
# Apply the differences
for {set i 0} {$i < $h} {incr i} {
for {set j 0} {$j < $w} {incr j} {
lset V $i $j [expr {
[lindex $V $i $j] - [lindex $dV $i $j]}]
}
}
# Done if the error is small enough
if {$error < $epsilon} break
}
# Compute the currents from the error
for {set i 0} {$i < $h} {incr i} {
for {set j 0} {$j < $w} {incr j} {
lset current [lindex $fixed $i $j] [expr {
[lindex $current [lindex $fixed $i $j]] +
[lindex $dV $i $j] * (!!$i+!!$j+($i<$h-1)+($j<$w-1))}]
}
}
# Compute the actual current flowing between source and sink
return [expr {([lindex $current 1] - [lindex $current 2]) / 2.0}]
}
# Public entry point
method solveForResistance {{epsilon 1e-24}} {
set voltageDifference [expr {
[lindex $forcePoints 2] - [lindex $forcePoints 5]}]
expr {$voltageDifference / [my FindCurrentFixpoint $epsilon]}
}
}
|
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
|
#Forth
|
Forth
|
: not-empty? dup 0 > ;
: (reverse) parse-name not-empty? IF recurse THEN type space ;
: reverse (reverse) cr ;
reverse ---------- Ice and Fire ------------
reverse
reverse fire, in end will world the say Some
reverse ice. in say Some
reverse desire of tasted I've what From
reverse fire. favor who those with hold I
reverse
reverse ... elided paragraph last ...
reverse
reverse Frost Robert -----------------------
|
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
|
#Fortran
|
Fortran
|
character*40 words
character*40 reversed
logical inblank
ierr=0
read (5,fmt="(a)",iostat=ierr)words
do while (ierr.eq.0)
inblank=.true.
ipos=1
do i=40,1,-1
if(words(i:i).ne.' '.and.inblank) then
last=i
inblank=.false.
end if
if(.not.inblank.and.words(i:i).eq.' ') then
reversed(ipos:ipos+last-i)=words(i+1:last)
ipos=ipos+last-i+1
inblank=.true.
end if
if(.not.inblank.and.i.eq.1) then
reversed(ipos:ipos+last-1)=words(1:last)
ipos=ipos+last
end if
end do
print *,words,'=> ',reversed(1:ipos-1)
read (5,fmt="(a)",iostat=ierr)words
end do
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
|
#PowerShell
|
PowerShell
|
$e = "This is a test Guvf vf n grfg"
[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join ""
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#PicoLisp
|
PicoLisp
|
(de roman (N)
(pack
(make
(mapc
'((C D)
(while (>= N D)
(dec 'N D)
(link C) ) )
'(M CM D CD C XC L XL X IX V IV I)
(1000 900 500 400 100 90 50 40 10 9 5 4 1) ) ) ) )
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost 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.
|
#Ruby
|
Ruby
|
def fromRoman(roman)
r = roman.upcase
n = 0
until r.empty? do
case
when r.start_with?('M') then v = 1000; len = 1
when r.start_with?('CM') then v = 900; len = 2
when r.start_with?('D') then v = 500; len = 1
when r.start_with?('CD') then v = 400; len = 2
when r.start_with?('C') then v = 100; len = 1
when r.start_with?('XC') then v = 90; len = 2
when r.start_with?('L') then v = 50; len = 1
when r.start_with?('XL') then v = 40; len = 2
when r.start_with?('X') then v = 10; len = 1
when r.start_with?('IX') then v = 9; len = 2
when r.start_with?('V') then v = 5; len = 1
when r.start_with?('IV') then v = 4; len = 2
when r.start_with?('I') then v = 1; len = 1
else
raise ArgumentError.new("invalid roman numerals: " + roman)
end
n += v
r.slice!(0,len)
end
n
end
[ "MCMXC", "MMVIII", "MDCLXVI" ].each {|r| p r => fromRoman(r)}
|
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
|
#Bracmat
|
Bracmat
|
(repeat=
string N rep
. !arg:(?string.?N)
& !string:?rep
& whl
' (!N+-1:>0:?N&!string !rep:?rep)
& str$!rep
);
|
http://rosettacode.org/wiki/Repeat_a_string
|
Repeat a string
|
Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks 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
|
#Brainf.2A.2A.2A
|
Brainf***
|
+++++ +++++ init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround
Now we want to loop 5 times to follow std
+++++
[-> ++++ . ----- -- . +++<] print h and a each loop
and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- .
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#ERRE
|
ERRE
|
PROGRAM RETURN_VALUES
PROCEDURE SUM_DIFF(A,B->C,D)
C=A+B
D=A-B
END PROCEDURE
BEGIN
SUM_DIFF(5,3->SUM,DIFF)
PRINT("Sum is";SUM)
PRINT("Difference is";DIFF)
END PROGRAM
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#Euphoria
|
Euphoria
|
include std\console.e --only for any_key, to help make running this program easy on windows GUI
integer aWholeNumber = 1
atom aFloat = 1.999999
sequence aSequence = {3, 4}
sequence result = {} --empty initialized sequence
function addmultret(integer first, atom second, sequence third)--takes three kinds of input, adds them all into one element of the..
return (first + second + third[1]) + third[2] & (first * second * third[1]) * third[2] --..output sequence and multiplies them into..
end function --..the second element
result = addmultret(aWholeNumber, aFloat, aSequence) --call function, assign what it gets into result - {9.999999, 23.999988}
? result
any_key()
|
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).
|
#APL
|
APL
|
∪ 1 2 3 1 2 3 4 1
1 2 3 4
|
http://rosettacode.org/wiki/Recaman%27s_sequence
|
Recaman's sequence
|
The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the 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.
|
#11l
|
11l
|
F recamanSucc(seen, n, r)
‘The successor for a given Recaman term,
given the set of Recaman terms seen so far.’
V back = r - n
R I 0 > back | (back C seen) {n + r} E back
F recamanUntil(p)
‘All terms of the Recaman series before the
first term for which the predicate p holds.’
V n = 1
V r = 0
V rs = [r]
V seen = Set(rs)
V blnNew = 1B
L !p(seen, n, r, blnNew)
r = recamanSucc(seen, n, r)
blnNew = r !C seen
seen.add(r)
rs.append(r)
n = 1 + n
R rs
F enumFromTo(m)
‘Integer enumeration from m to n.’
R n -> @m .< 1 + n
print("First 15 Recaman:\n "recamanUntil((seen, n, r, _) -> n == 15))
print("First duplicated Recaman:\n "recamanUntil((seen, n, r, blnNew) -> !blnNew).last)
V setK = Set(enumFromTo(0)(1000))
print("Number of Recaman terms needed to generate all integers from [0..1000]:\n "(recamanUntil((seen, n, r, blnNew) -> (blnNew & r < 1001 & :setK.is_subset(seen))).len - 1))
|
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.
|
#AutoHotkey
|
AutoHotkey
|
RemoveLines(filename, startingLine, numOfLines){
Loop, Read, %filename%
if ( A_Index < StartingLine )
|| ( A_Index >= StartingLine + numOfLines )
ret .= "`r`n" . A_LoopReadLine
FileDelete, % FileName
FileAppend, % SubStr(ret, 3), % FileName
}
SetWorkingDir, % A_ScriptDir
RemoveLines("test.txt", 4, 3)
|
http://rosettacode.org/wiki/Record_sound
|
Record sound
|
Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs might not record sound in the same format.)
|
#Common_Lisp
|
Common Lisp
|
(defun record (n)
(with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8))
(loop repeat n collect (read-byte in))
)
)
(defun play (byte-list)
(with-open-file (out "/dev/dsp" :direction :output :element-type '(unsigned-byte 8) :if-exists :append)
(mapcar (lambda (b) (write-byte b out)) byte-list)
)
)
(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.)
|
#Go
|
Go
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
name := ""
for name == "" {
fmt.Print("Enter output file name (without extension) : ")
scanner.Scan()
name = scanner.Text()
check(scanner.Err())
}
name += ".wav"
rate := 0
for rate < 2000 || rate > 192000 {
fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
rate, _ = strconv.Atoi(input)
}
rateS := strconv.Itoa(rate)
dur := 0.0
for dur < 5 || dur > 30 {
fmt.Print("Enter duration in seconds (5 to 30) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
fmt.Println("OK, start speaking now...")
// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported.
args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name}
cmd := exec.Command("arecord", args...)
err := cmd.Run()
check(err)
fmt.Printf("'%s' created on disk and will now be played back...\n", name)
cmd = exec.Command("aplay", name)
err = cmd.Run()
check(err)
fmt.Println("Play-back completed.")
}
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Julia
|
Julia
|
methods(methods)
methods(println)
|
http://rosettacode.org/wiki/Reflection/List_methods
|
Reflection/List methods
|
Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Kotlin
|
Kotlin
|
// Version 1.2.31
import kotlin.reflect.full.functions
open class MySuperClass {
fun mySuperClassMethod(){}
}
open class MyClass : MySuperClass() {
fun myPublicMethod(){}
internal fun myInternalMethod(){}
protected fun myProtectedMethod(){}
private fun myPrivateMethod(){}
}
fun main(args: Array<String>) {
val c = MyClass::class
println("List of methods declared in ${c.simpleName} and its superclasses:\n")
val fs = c.functions
for (f in fs) println("${f.name}, ${f.visibility}")
}
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#ooRexx
|
ooRexx
|
/* REXX demonstrate uses of datatype() */
/* test values */
d.1=''
d.2='a23'
d.3='101'
d.4='123'
d.5='12345678901234567890'
d.6='abc'
d.7='aBc'
d.8='1'
d.9='0'
d.10='Walter'
d.11='ABC'
d.12='f23'
d.13='123'
/* supported options */
t.1='A' /* Alphanumeric */
t.2='B' /* Binary */
t.3='I' /* Internal whole number */
t.4='L' /* Lowercase */
t.5='M' /* Mixed case */
t.6='N' /* Number */
t.7='O' /* lOgical */
t.8='S' /* Symbol */
t.9='U' /* Uppercase */
t.10='V' /* Variable */
t.11='W' /* Whole number */
t.12='X' /* heXadecimal */
t.13='9' /* 9 digits */
hdr=left('',20)
Do j=1 To 13
hdr=hdr t.j
End
hdr=hdr 'datatype(v)'
Say hdr
Do i=1 To 13
ol=left(d.i,20)
Do j=1 To 13
ol=ol datatype(d.i,t.j)
End
ol=ol datatype(d.i)
Say ol
End
Say hdr
|
http://rosettacode.org/wiki/Reflection/List_properties
|
Reflection/List properties
|
Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
|
#Perl
|
Perl
|
{
package Point;
use Class::Spiffy -base;
field 'x';
field 'y';
}
{
package Circle;
use base qw(Point);
field 'r';
}
my $p1 = Point->new(x => 8, y => -5);
my $c1 = Circle->new(r => 4);
my $c2 = Circle->new(x => 1, y => 2, r => 3);
use Data::Dumper;
say Dumper $p1;
say Dumper $c1;
say Dumper $c2;
|
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
|
#CLU
|
CLU
|
rep_strings = iter (s: string) yields (string)
for len: int in int$from_to_by(string$size(s)/2, 1, -1) do
repstr: string := string$substr(s, 1, len)
attempt: string := ""
while string$size(attempt) < string$size(s) do
attempt := attempt || repstr
end
if s = string$substr(attempt, 1, string$size(s)) then
yield(repstr)
end
end
end rep_strings
start_up = proc ()
as = array[string]
po: stream := stream$primary_output()
tests: as := as$["1001110011","1110111011","0010010010","1010101010",
"1111111111","0100101101","0100100","101","11","00",
"1"]
for test: string in as$elements(tests) do
stream$puts(po, test || ": ")
for rep_str: string in rep_strings(test) do
stream$puts(po, "<" || rep_str || "> ")
end
stream$putc(po, '\n')
end
end start_up
|
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
|
#Common_Lisp
|
Common Lisp
|
(ql:quickload :alexandria)
(defun rep-stringv (a-str &optional (max-rotation (floor (/ (length a-str) 2))))
;; Exit condition if no repetition found.
(cond ((< max-rotation 1) "Not a repeating string")
;; Two checks:
;; 1. Truncated string must be equal to rotation by repetion size.
;; 2. Remaining chars (rest-str) are identical to starting chars (beg-str)
((let* ((trunc (* max-rotation (truncate (length a-str) max-rotation)))
(truncated-str (subseq a-str 0 trunc))
(rest-str (subseq a-str trunc))
(beg-str (subseq a-str 0 (rem (length a-str) max-rotation))))
(and (string= beg-str rest-str)
(string= (alexandria:rotate (copy-seq truncated-str) max-rotation)
truncated-str)))
;; If both checks pass, return the repeting string.
(subseq a-str 0 max-rotation))
;; Recurse function reducing length of rotation.
(t (rep-stringv a-str (1- max-rotation)))))
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#D
|
D
|
void main() {
import std.stdio, std.regex;
immutable s = "I am a string";
// Test.
if (s.match("string$"))
"Ends with 'string'.".writeln;
// Substitute.
s.replace(" a ".regex, " another ").writeln;
}
|
http://rosettacode.org/wiki/Regular_expressions
|
Regular expressions
|
Task
match a string against a regular expression
substitute part of a string using a regular expression
|
#Dart
|
Dart
|
RegExp regexp = new RegExp(r'\w+\!');
String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';
void main(){
String hello = 'hello hello! world world!';
String hellomodified = hello.replaceAllMapped(regexp, capitalize);
print(hello);
print(hellomodified);
}
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
|
#AppleScript
|
AppleScript
|
reverseString("Hello World!")
on reverseString(str)
reverse of characters of str as string
end reverseString
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Go
|
Go
|
package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
|
http://rosettacode.org/wiki/Repeat
|
Repeat
|
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
|
#Haskell
|
Haskell
|
import Control.Monad (replicateM_)
sampleFunction :: IO ()
sampleFunction = putStrLn "a"
main = replicateM_ 5 sampleFunction
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#ERRE
|
ERRE
|
CMD$="REN "+OLDFILENAME$+" "+NEWFILENAME$
SHELL CMD$
|
http://rosettacode.org/wiki/Rename_a_file
|
Rename a file
|
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)
|
#F.23
|
F#
|
open System.IO
[<EntryPoint>]
let main args =
File.Move("input.txt","output.txt")
File.Move(@"\input.txt",@"\output.txt")
Directory.Move("docs","mydocs")
Directory.Move(@"\docs",@"\mydocs")
0
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#Wren
|
Wren
|
class Node {
construct new(v, fixed) {
_v = v
_fixed = fixed
}
v { _v }
v=(value) { _v = value }
fixed { _fixed }
fixed=(value) { _fixed = value }
}
var setBoundary = Fn.new { |m|
m[1][1].v = 1
m[1][1].fixed = 1
m[6][7].v = -1
m[6][7].fixed = -1
}
var calcDiff = Fn.new { |m, d, w, h|
var total = 0
for (i in 0...h) {
for (j in 0...w) {
var v = 0
var n = 0
if (i > 0) {
v = v + m[i-1][j].v
n = n + 1
}
if (j > 0) {
v = v + m[i][j-1].v
n = n + 1
}
if (i + 1 < h) {
v = v + m[i+1][j].v
n = n + 1
}
if (j + 1 < w) {
v = v + m[i][j+1].v
n = n + 1
}
v = m[i][j].v - v/n
d[i][j].v = v
if (m[i][j].fixed == 0) total = total + v*v
}
}
return total
}
var iter = Fn.new { |m, w, h|
var d = List.filled(h, null)
for (i in 0...h) {
d[i] = List.filled(w, null)
for (j in 0...w) d[i][j] = Node.new(0, 0)
}
var cur = [0] * 3
var diff = 1e10
while (diff > 1e-24) {
setBoundary.call(m)
diff = calcDiff.call(m, d, w, h)
for (i in 0...h) {
for (j in 0...w) m[i][j].v = m[i][j].v - d[i][j].v
}
}
for (i in 0...h) {
for (j in 0...w) {
var k = 0
if (i != 0) k = k + 1
if (j != 0) k = k + 1
if (i < h - 1) k = k + 1
if (j < w - 1) k = k + 1
cur[m[i][j].fixed + 1] = cur[m[i][j].fixed + 1] + d[i][j].v * k
}
}
return (cur[2] - cur[0]) / 2
}
var S = 10
var mesh = List.filled(S, null)
for (i in 0...S) {
mesh[i] = List.filled(S, null)
for (j in 0...S) mesh[i][j] = Node.new(0, 0)
}
var r = 2 / iter.call(mesh, S, S)
System.print("R = %(r)")
|
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
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1 - empty) = Mid(s, position(i - 1) + 1, length)
If removeEmpty Andalso CBool(length = 0) Then empty += 1
Next
If empty > 0 Then Redim Preserve result(count - empty)
End Sub
Dim s As String = "Hey you, Bub!"
Dim a() As String
split(s, " ", a(), true)
Dim reversed As String = ""
For i As Integer = UBound(a) To LBound(a) Step -1
reversed += a(i)
If i > LBound(a) Then reversed += " "
Next
Print "Original String = "; s
Print "Reversed String = "; reversed
Print
Print "Press any key to quit"
Sleep
|
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
|
#Prolog
|
Prolog
|
:- use_module(library(ctypes)).
runtime_entry(start) :-
prompt(_, ''),
rot13.
rot13 :-
get0(Ch),
( is_endfile(Ch) ->
true
; rot13_char(Ch, Rot),
put(Rot),
rot13
).
rot13_char(Ch, Rot) :-
( is_alpha(Ch) ->
to_upper(Ch, Up),
Letter is Up - 0'A,
Rot is Ch + ((Letter + 13) mod 26) - Letter
; Rot = Ch
).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.