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/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Picat | Picat | import util.
go =>
text(1,Text),
foreach(LineWidth in [60,80])
println(lineWidth=LineWidth),
println(wrap(Text,LineWidth)),
nl
end,
nl.
wrap(Text,LineWidth) = Wrapped =>
Words = Text.split(),
Wrapped = Words[1],
SpaceLeft = LineWidth - Wrapped.len,
foreach(Word in Words.tail)
WordLen = Word.length,
if (WordLen + 1) > SpaceLeft then
Wrapped := Wrapped ++ "\n" ++ Word,
SpaceLeft := LineWidth - WordLen
else
Wrapped := Wrapped ++ " " ++ Word,
SpaceLeft := SpaceLeft - WordLen - 1
end
end.
text(1,"Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum."). |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #PicoLisp | PicoLisp | : (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog")))
The quick
brown fox
jumps over
the lazy dog
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog" |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Tcl | Tcl | package require tdom
set tree [dom parse $xml]
set studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes]
foreach node $studentNodes {
puts [$node getAttribute Name]
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Piet | Piet | array onehundreddoors()
{
array doors = allocate(100);
foreach(doors; int i;)
for(int j=i; j<100; j+=i+1)
doors[j] = !doors[j];
return doors;
} |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #OCaml | OCaml | let () =
let _,_, page_content = make_request ~url:Sys.argv.(1) ~kind:GET () in
let lines = Str.split (Str.regexp "\n") page_content in
let str =
List.find
(fun line ->
try ignore(Str.search_forward (Str.regexp "UTC") line 0); true
with Not_found -> false)
lines
in
let str = Str.global_replace (Str.regexp "<BR>") "" str in
print_endline str;
;; |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Phix | Phix | without javascript_semantics
?"loading..."
constant subs = '\t'&"\r\n_.,\"\'!;:?][()|=<>#/*{}+@%&$",
reps = repeat(' ',length(subs)),
fn = open("135-0.txt","r")
string text = lower(substitute_all(get_text(fn),subs,reps))
close(fn)
sequence words = append(sort(split(text,no_empty:=true)),"")
constant wf = new_dict()
string last = words[1]
integer count = 1
for i=2 to length(words) do
if words[i]!=last then
setd({count,last},0,wf)
count = 0
last = words[i]
end if
count += 1
end for
count = 10
function visitor(object key, object /*data*/, object /*user_data*/)
?key
count -= 1
return count>0
end function
traverse_dict(routine_id("visitor"),0,wf,true)
|
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Raku | Raku | class Wireworld {
has @.line;
method height () { @!line.elems }
has int $.width;
multi method new(@line) { samewith :@line, :width(max @line».chars) }
multi method new($str ) { samewith $str.lines }
method gist { join "\n", @.line }
method !neighbors($i where ^$.height, $j where ^$.width)
{
my @i = grep ^$.height, $i «+« (-1, 0, 1);
my @j = grep ^$.width, $j «+« (-1, 0, 1);
gather for @i X @j -> (\i, \j) {
next if [ i, j ] ~~ [ $i, $j ];
take @!line[i].comb[j];
}
}
method succ {
my @succ;
for ^$.height X ^$.width -> ($i, $j) {
@succ[$i] ~=
do given @!line[$i].comb[$j] {
when 'H' { 't' }
when 't' { '.' }
when '.' {
grep('H', self!neighbors($i, $j)) == 1|2 ?? 'H' !! '.'
}
default { ' ' }
}
}
return self.new: @succ;
}
}
my %*SUB-MAIN-OPTS;
%*SUB-MAIN-OPTS<named-anywhere> = True;
multi sub MAIN (
IO() $filename,
Numeric:D :$interval = 1/4,
Bool :$stop-on-repeat,
) {
run-loop :$interval, :$stop-on-repeat, Wireworld.new: $filename.slurp;
}
#| run a built-in example
multi sub MAIN (
Numeric:D :$interval = 1/4,
Bool :$stop-on-repeat,
) {
run-loop :$interval, :$stop-on-repeat, Wireworld.new: Q:to/END/
tH.........
. .
...
. .
Ht.. ......
END
}
sub run-loop (
Wireworld:D $initial,
Real:D(Numeric) :$interval = 1/4,
Bool :$stop-on-repeat
){
my %seen is SetHash;
for $initial ...^ * eqv * { # generate a sequence (uses .succ)
print "\e[2J";
say '#' x $initial.width;
.say;
say '#' x $initial.width;
if $stop-on-repeat {
last if %seen{ .gist }++;
}
sleep $interval;
}
} |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #VBA | VBA | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Need to reference the following object library (From the Tools menu, choose References)
Microsoft Forms 2.0 Object Library
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
And :
Programmatic Access to Visual Basic Project must be trusted. See it in Macro's security! |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Vedit_macro_language | Vedit macro language | Win_Create(A, 2, 5, 20, 80) |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FI | PL/I | *process source attributes xref or(!);
ww: proc Options(main);
/*********************************************************************
* 21.08-2013 Walter Pachl derived from REXX version 2
*********************************************************************/
Dcl in record input;
Dcl out record output;
On Endfile(in) z=' ';
Dcl z char(32767) Var;
Dcl s char(32767) Var Init('');
dcl o Char(200) Var;
Dcl (i,w,p) Bin Fixed(31) Init(0);
w=72;
Read File(in) Into(z);
s=z;
Do Until(s='');
Do i=w+1 to 1 by -1;
If substr(s,i,1)='' Then Leave;
End;
If i=0 Then
p=index(s,' ');
Else
p=i;
o=left(s,p);
Write file(out) From(o);
s=substr(s,p+1);
If length(s)<200 Then Do;
Read File(in) Into(z);
s=s!!z;
End;
End;
End; |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
MODE DATA
$$ SET xmldata =*
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Emily" />
</Students>
$$ MODE TUSCRIPT
COMPILE
LOOP x = xmldata
SET name=GET_TAG_NAME (x)
IF (name!="student") CYCLE
studentname=GET_ATTRIBUTE (x,"Name")
IF (studentname!="") PRINT studentname
ENDLOOP
ENDCOMPILE
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #TXR | TXR | <Students>
@(collect :vars (NAME GENDER YEAR MONTH DAY (PET_TYPE "none") (PET_NAME "")))
@ (cases)
<Student Name="@NAME" Gender="@GENDER" DateOfBirth="@YEAR-@MONTH-@DAY"@(skip)
@ (or)
<Student DateOfBirth="@YEAR-@MONTH-@DAY" Gender="@GENDER" Name="@NAME"@(skip)
@ (end)
@ (maybe)
<Pet Type="@PET_TYPE" Name="@PET_NAME" />
@ (end)
@(until)
</Students>
@(end)
@(output :filter :from_html)
NAME G DOB PET
@ (repeat)
@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME
@ (end)
@(end) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Pike | Pike | array onehundreddoors()
{
array doors = allocate(100);
foreach(doors; int i;)
for(int j=i; j<100; j+=i+1)
doors[j] = !doors[j];
return doors;
} |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #ooRexx | ooRexx |
/* load the RexxcURL library */
Call RxFuncAdd 'CurlLoadFuncs', 'rexxcurl', 'CurlLoadFuncs'
Call CurlLoadFuncs
url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
/* get a curl session */
curl = CurlInit()
if curl \= ''
then do
call CurlSetopt curl, 'URL', Url
if curlerror.intcode \= 0 then exit
call curlSetopt curl, 'OUTSTEM', 'stem.'
if curlerror.intcode \= 0 then exit
call CurlPerform curl
/* content is in a stem - lets get it all in a string */
content = stem.~allItems~makestring('l')
/* now parse out utc time */
parse var content content 'Universal Time' .
utcTime = content~substr(content~lastpos('<BR>') + 4)
say utcTime
end |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Oz | Oz | declare
[Regex] = {Module.link ['x-oz://contrib/regex']}
fun {GetPage Url}
F = {New Open.file init(url:Url)}
Contents = {F read(list:$ size:all)}
in
{F close}
Contents
end
fun {GetDateString Doc}
case {Regex.search "<BR>([A-Za-z0-9:., ]+ UTC)" Doc}
of match(1:S#E ...) then {List.take {List.drop Doc S} E-S+1}
end
end
Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
in
{System.showInfo {GetDateString {GetPage Url}}} |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
"loading..." ?
"135-0.txt" "r" fopen var fn
" "
true
while
fn fgets number? if drop fn fclose false else lower " " chain chain true endif
endwhile
"process..." ?
len for
var i
i get dup 96 > swap 123 < and not if 32 i set endif
endfor
split sort
"count..." ?
( ) var words
"" var prev
1 var n
len for
var i
i get dup prev ==
if
drop n 1 + var n
else
words ( n prev ) 0 put var words var prev 1 var n
endif
endfor
drop
words sort
10 for
-1 * get ?
endfor
drop |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #PHP | PHP |
<?php
preg_match_all('/\w+/', file_get_contents($argv[1]), $words);
$frecuency = array_count_values($words[0]);
arsort($frecuency);
echo "Rank\tWord\tFrequency\n====\t====\t=========\n";
$i = 1;
foreach ($frecuency as $word => $count) {
echo $i . "\t" . $word . "\t" . $count . "\n";
if ($i >= 10) {
break;
}
$i++;
} |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #REXX | REXX | /*REXX program displays a wire world Cartesian grid of four─state cells. */
parse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps
if iFID=='' then iFID= "WIREWORLD.TXT" /*should default input file be used? */
bla = 'BLANK' /*the "name" for a blank. */
generations = p(generations 100 ) /*number generations that are allowed. */
rows = p(rows 3 ) /*the number of cell rows. */
cols = p(cols 3 ) /* " " " " columns. */
bare = pickChar(bare bla ) /*character used to show an empty cell.*/
clearScreen = p(clearScreen 0 ) /*1 means to clear the screen. */
head = pickChar(head 'H' ) /*pick the character for the head. */
tail = pickChar(tail 't' ) /* " " " " " tail. */
wire = pickChar(wire . ) /* " " " " " wire. */
reps = p(reps 2 ) /*stop program if there are 2 repeats.*/
fents= max(cols, linesize() - 1) /*the fence width used after displaying*/
#reps= 0; $.= bare; gens= abs(generations) /*at start, universe is new and barren.*/
/* [↓] read the input file. */
do r=1 while lines(iFID)\==0 /*keep reading until the End─Of─File. */
q= strip( linein(iFID), 'T') /*get a line from input file. */
L= length(q); cols= max(cols, L) /*calculate maximum number of columns. */
do c=1 for L; $.r.c= substr(q, c, 1) /*assign the cells for the R row. */
end /*c*/
end /*r*/
!.= 0; signal on halt /*initial state of cells; handle halt.*/
rows= r - 1; life= 0; call showCells /*display initial state of the cells. */
/*watch cells evolve, 4 possible states*/
do life=1 for gens; @.= bare /*perform for the number of generations*/
do r=1 for rows /*process each of the rows. */
do c=1 for cols; ?= $.r.c; ??= ? /* " " " " columns. */
select /*determine the type of cell. */
when ?==head then ??= tail
when ?==tail then ??= wire
when ?==wire then do; #= hood(); if #==1 | #==2 then ??= head; end
otherwise nop
end /*select*/
@.r.c= ?? /*possible assign a cell a new state.*/
end /*c*/
end /*r*/
call assign$ /*assign alternate cells ──► real world*/
if generations>0 | life==gens then call showCells
end /*life*/
/*stop watching the universe (or life).*/
halt: if life-1\==gens then say 'The ───Wireworld─── program was interrupted by user.'
done: exit 0 /*stick a fork in it, we are all done.*/
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$: parse arg _row,_col; return $._row._col==head
assign$: do r=1 for rows; do c=1 for cols; $.r.c= @.r.c; end; end; return
hood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1)
p: return word(arg(1), 1) /*pick the 1st word in list.*/
pickChar: parse arg _ .;arg U .;L=length(_);if U==bla then _=' '; if L==3 then _=d2c(_);if L==2 then _=x2c(_);return _
showRows: _=; do r=1 for rows; z=; do c=1 for cols; z= z||$.r.c; end; z= strip(z,'T'); say z; _= _||z; end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showCells: if clearScreen then 'CLS' /*◄──change CLS for the host*/
call showRows /*show rows in proper order.*/
say right( copies('═', fents)life, fents) /*display a title for cells.*/
if _=='' then signal done /*No life? Then stop run. */
if !._ then #reps= #reps + 1 /*detected repeated pattern.*/
!._= 1 /*it is now an extant state.*/
if reps\==0 & #reps<=reps then return /*so far, so good, no reps.*/
say '"Wireworld" repeated itself' reps "times, the program is stopping."
signal done /*jump to this pgm's "exit".*/ |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Visual_Basic_.NET | Visual Basic .NET | Dim newForm as new Form
newForm.Text = "It's a new window"
newForm.Show() |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Wren | Wren | import "dome" for Window
class EmptyWindow {
construct new(width, height) {
Window.title = "Empty window"
Window.resize(width, height)
}
init() {}
update() {}
draw(alpha) {}
}
var Game = EmptyWindow.new(600, 600) |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #X86_Assembly | X86 Assembly |
;GTK imports and defines etc.
%define GTK_WINDOW_TOPLEVEL 0
extern gtk_init
extern gtk_window_new
extern gtk_widget_show
extern gtk_signal_connect
extern gtk_main
extern g_print
extern gtk_main_quit
bits 32
section .text
global _main
;exit signal
sig_main_exit:
push exit_sig_msg
call g_print
add esp, 4
call gtk_main_quit
ret
_main:
mov ebp, esp
sub esp, 8
push argv
push argc
call gtk_init
add esp, 8 ;stack alignment.
push GTK_WINDOW_TOPLEVEL
call gtk_window_new
add esp, 4
mov [ebp-4], eax ;ebp-4 now holds our GTKWindow pointer.
push 0
push sig_main_exit
push gtk_delete_event
push dword [ebp-4]
call gtk_signal_connect
add esp, 16
push dword [ebp-4]
call gtk_widget_show
add esp, 4
call gtk_main
section .data
;sudo argv
argc dd 1
argv dd args
args dd title
dd 0
title db "GTK Window",0
gtk_delete_event db 'delete_event',0
exit_sig_msg db "-> Rage quitting..",10,0
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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 | function wrap{
$divide=$args[0] -split " "
$width=$args[1]
$spaceleft=$width
foreach($word in $divide){
if($word.length+1 -gt $spaceleft){
$output+="`n$word "
$spaceleft=$width-($word.length+1)
} else {
$output+="$word "
$spaceleft-=$word.length+1
}
}
return "$output`n"
}
### The Main Thing...
$paragraph="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."
"`nLine width:30`n"
wrap $paragraph 30
"========================================================="
"Line width:100`n"
wrap $paragraph 100
### End script |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #VBA | VBA | Option Explicit
Const strXml As String = "" & _
"<Students>" & _
"<Student Name=""April"" Gender=""F"" DateOfBirth=""1989-01-02"" />" & _
"<Student Name=""Bob"" Gender=""M"" DateOfBirth=""1990-03-04"" />" & _
"<Student Name=""Chad"" Gender=""M"" DateOfBirth=""1991-05-06"" />" & _
"<Student Name=""Dave"" Gender=""M"" DateOfBirth=""1992-07-08"">" & _
"<Pet Type=""dog"" Name=""Rover"" />" & _
"</Student>" & _
"<Student DateOfBirth=""1993-09-10"" Gender=""F"" Name=""Émily"" />" & _
"</Students>"
Sub Main_Xml()
Dim MyXml As Object
Dim myNodes, myNode
With CreateObject("MSXML2.DOMDocument")
.LoadXML strXml
Set myNodes = .getElementsByTagName("Student")
End With
If Not myNodes Is Nothing Then
For Each myNode In myNodes
Debug.Print myNode.getAttribute("Name")
Next
End If
Set myNodes = Nothing
End Sub |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #PL.2FI | PL/I |
declare door(100) bit (1) aligned;
declare closed bit (1) static initial ('0'b),
open bit (1) static initial ('1'b);
declare (i, inc) fixed binary;
door = closed;
inc = 1;
do until (inc >= 100);
do i = inc to 100 by inc;
door(i) = ^door(i); /* close door if open; open it if closed. */
end;
inc = inc+1;
end;
do i = 1 to 100;
put skip edit ('Door ', trim(i), ' is ') (a);
if door(i) then put edit (' open.') (a);
else put edit (' closed.') (a);
end;
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Peloton | Peloton | <@ DEFAREPRS>Rexx Parse</@>
<@ DEFPRSLIT>Rexx Parse|'<BR>' UTCtime 'UTC'</@>
<@ LETVARURL>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl</@>
<@ ACTRPNPRSVAR>Rexx Parse|timer</@>
<@ SAYVAR>UTCtime</@> |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Perl | Perl | use LWP::Simple;
my $url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl';
get($url) =~ /<BR>(.+? UTC)/
and print "$1\n"; |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Picat | Picat | main =>
NTop = 10,
File = "les_miserables.txt",
Chars = read_file_chars(File),
% Remove the Project Gutenberg header/footer
find(Chars,"*** START OF THE PROJECT GUTENBERG EBOOK LES MISÉRABLES ***",_,HeaderEnd),
find(Chars,"*** END OF THE PROJECT GUTENBERG EBOOK LES MISÉRABLES ***",FooterStart,_),
Book = [to_lowercase(C) : C in slice(Chars,HeaderEnd+1,FooterStart-1)],
% Split into words (different set of split characters)
member(SplitType,[all,space_punct,space]),
println(split_type=SplitType),
split_chars(SplitType,SplitChars),
Words = split(Book,SplitChars),
println(freq(Words).to_list.sort_down(2).take(NTop)),
nl,
fail.
freq(L) = Freq =>
Freq = new_map(),
foreach(E in L)
Freq.put(E,Freq.get(E,0)+1)
end.
% different set of split chars
split_chars(all,"\n\r \t,;!.?()[]”\"-“—-__‘’*").
split_chars(space_punct,"\n\r \t,;!.?").
split_chars(space,"\n\r \t"). |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #PicoLisp | PicoLisp | (setq *Delim " ^I^J^M-_.,\"'*[]?!&@#$%^\(\):;")
(setq *Skip (chop *Delim))
(de word+ NIL
(prog1
(lowc (till *Delim T))
(while (member (peek) *Skip) (char)) ) )
(off B)
(in "135-0.txt"
(until (eof)
(let W (word+)
(if (idx 'B W T) (inc (car @)) (set W 1)) ) ) )
(for L (head 10 (flip (by val sort (idx 'B))))
(println L (val L)) ) |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Ruby | Ruby | use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum State {
Empty,
Conductor,
ElectronTail,
ElectronHead,
}
impl State {
fn next(&self, e_nearby: usize) -> State {
match self {
State::Empty => State::Empty,
State::Conductor => {
if e_nearby == 1 || e_nearby == 2 {
State::ElectronHead
} else {
State::Conductor
}
}
State::ElectronTail => State::Conductor,
State::ElectronHead => State::ElectronTail,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WireWorld {
pub width: usize,
pub height: usize,
pub data: Vec<State>,
}
impl WireWorld {
pub fn new(width: usize, height: usize) -> Self {
WireWorld {
width,
height,
data: vec![State::Empty; width * height],
}
}
pub fn get(&self, x: usize, y: usize) -> Option<State> {
if x >= self.width || y >= self.height {
None
} else {
self.data.get(y * self.width + x).copied()
}
}
pub fn set(&mut self, x: usize, y: usize, state: State) {
self.data[y * self.width + x] = state;
}
fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize
where F: FnMut(State) -> bool
{
let (x, y) = (x as i32, y as i32);
let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];
neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()
}
pub fn next(&mut self) {
let mut next_state = vec![];
for y in 0..self.height {
for x in 0..self.width {
let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);
next_state.push(self.get(x, y).unwrap().next(e_count));
}
}
self.data = next_state;
}
}
impl FromStr for WireWorld {
type Err = ();
fn from_str(s: &str) -> Result<WireWorld, ()> {
let s = s.trim();
let height = s.lines().count();
let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);
let mut world = WireWorld::new(width, height);
for (y, line) in s.lines().enumerate() {
for (x, ch) in line.trim_end().chars().enumerate() {
let state = match ch {
'.' => State::Conductor,
't' => State::ElectronTail,
'H' => State::ElectronHead,
_ => State::Empty,
};
world.set(x, y, state);
}
}
Ok(world)
}
} |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Yabasic | Yabasic | open window 400,200 //minimum line required to accomplish the indicated task
clear screen
text 200,100,"I am a window - close me!","cc"
end |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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 | % See https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_number_of_lines
word_wrap(String, Length, Wrapped):-
re_split("\\S+", String, Words),
wrap(Words, Length, Length, Wrapped, '').
wrap([_], _, _, Result, Result):-!.
wrap([Space, Word|Words], Line_length, Space_left, Result, String):-
string_length(Word, Word_len),
string_length(Space, Space_len),
(Space_left < Word_len + Space_len ->
Space1 = '\n',
Space_left1 is Line_length - Word_len
;
Space1 = Space,
Space_left1 is Space_left - Word_len - Space_len
),
atomic_list_concat([String, Space1, Word], String1),
wrap(Words, Line_length, Space_left1, Result, String1).
sample_text("Lorem ipsum dolor sit amet, consectetur adipiscing \
elit, sed do eiusmod tempor incididunt ut labore et dolore magna \
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \
dolor in reprehenderit in voluptate velit esse cillum dolore eu \
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non \
proident, sunt in culpa qui officia deserunt mollit anim id est \
laborum.").
test_word_wrap(Line_length):-
sample_text(Text),
word_wrap(Text, Line_length, Wrapped),
writef('Wrapped at %w characters:\n%w\n',
[Line_length, Wrapped]).
main:-
test_word_wrap(60),
nl,
test_word_wrap(80). |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Vedit_macro_language | Vedit macro language | Repeat(ALL) {
Search("<Student|X", ERRBREAK)
#1 = Cur_Pos
Match_Paren()
if (Search_Block(/Name=|{",'}/, #1, Cur_Pos, BEGIN+ADVANCE+NOERR+NORESTORE)==0) { Continue }
#2 = Cur_Pos
Search(/|{",'}/)
Type_Block(#2, Cur_Pos)
Type_Newline
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #PL.2FM | PL/M | 100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */
/* BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG );
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
/* PRINTS A BYTE AS A CHARACTER */
PRINT$CHAR: PROCEDURE( CH );
DECLARE CH BYTE;
CALL BDOS( 2, CH );
END PRINT$CHAR;
/* PRINTS A BYTE AS A NUMBER */
PRINT$BYTE: PROCEDURE( N );
DECLARE N BYTE;
DECLARE ( V, D3, D2 ) BYTE;
V = N;
D3 = V MOD 10;
IF ( V := V / 10 ) <> 0 THEN DO;
D2 = V MOD 10;
IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );
CALL PRINT$CHAR( '0' + D2 );
END;
CALL PRINT$CHAR( '0' + D3 );
END PRINT$BYTE;
DECLARE DOOR$DCL LITERALLY '101';
DECLARE FALSE LITERALLY '0';
DECLARE CR LITERALLY '0DH';
DECLARE LF LITERALLY '0AH';
/* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */
DECLARE DOOR( DOOR$DCL ) BYTE;
DECLARE ( I, J ) BYTE;
/* SET ALL DOORS TO CLOSED */
DO I = 0 TO LAST( DOOR ); DOOR( I ) = FALSE; END;
/* REPEATEDLY FLIP THE DOORS */
DO I = 1 TO LAST( DOOR );
DO J = I TO LAST( DOOR ) BY I;
DOOR( J ) = NOT DOOR( J );
END;
END;
/* DISPLAY THE RESULTS */
DO I = 1 TO LAST( DOOR );
IF DOOR( I ) THEN DO;
CALL PRINT$CHAR( ' ' );
CALL PRINT$BYTE( I );
END;
END;
CALL PRINT$CHAR( CR );
CALL PRINT$CHAR( LF );
EOF
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Phix | Phix | --
-- demo\rosetta\web_scrape.exw
-- ===========================
--
without js -- (libcurl)
include builtins\libcurl.e
include builtins\timedate.e
object res = curl_easy_perform_ex("https://rosettacode.org/wiki/Talk:Web_scraping")
if string(res) then
res = split(res,'\n')
for i=1 to length(res) do
integer k = match("UTC",res[i])
if k then
string line = res[i] -- (debug aid)
res = line[1..k-3]
k = rmatch("</a>",res)
res = trim(res[k+5..$])
exit
end if
end for
?res
if string(res) then
timedate td = parse_date_string(res, {"hh:mm, d Mmmm yyyy"})
?format_timedate(td,"Dddd Mmmm ddth yyyy h:mpm")
end if
else
?{"some error",res,curl_easy_strerror(res)}
end if
|
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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 | print_top_words(File, N):-
read_file_to_string(File, String, [encoding(utf8)]),
re_split("\\w+", String, Words),
lower_case(Words, Lower),
sort(1, @=<, Lower, Sorted),
merge_words(Sorted, Counted),
sort(2, @>, Counted, Top_words),
writef("Top %w words:\nRank\tCount\tWord\n", [N]),
print_top_words(Top_words, N, 1).
lower_case([_], []):-!.
lower_case([_, Word|Words], [Lower - 1|Rest]):-
string_lower(Word, Lower),
lower_case(Words, Rest).
merge_words([], []):-!.
merge_words([Word - C1, Word - C2|Words], Result):-
!,
C is C1 + C2,
merge_words([Word - C|Words], Result).
merge_words([W|Words], [W|Rest]):-
merge_words(Words, Rest).
print_top_words([], _, _):-!.
print_top_words(_, 0, _):-!.
print_top_words([Word - Count|Rest], N, R):-
writef("%w\t%w\t%w\n", [R, Count, Word]),
N1 is N - 1,
R1 is R + 1,
print_top_words(Rest, N1, R1).
main:-
print_top_words("135-0.txt", 10). |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Rust | Rust | use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum State {
Empty,
Conductor,
ElectronTail,
ElectronHead,
}
impl State {
fn next(&self, e_nearby: usize) -> State {
match self {
State::Empty => State::Empty,
State::Conductor => {
if e_nearby == 1 || e_nearby == 2 {
State::ElectronHead
} else {
State::Conductor
}
}
State::ElectronTail => State::Conductor,
State::ElectronHead => State::ElectronTail,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WireWorld {
pub width: usize,
pub height: usize,
pub data: Vec<State>,
}
impl WireWorld {
pub fn new(width: usize, height: usize) -> Self {
WireWorld {
width,
height,
data: vec![State::Empty; width * height],
}
}
pub fn get(&self, x: usize, y: usize) -> Option<State> {
if x >= self.width || y >= self.height {
None
} else {
self.data.get(y * self.width + x).copied()
}
}
pub fn set(&mut self, x: usize, y: usize, state: State) {
self.data[y * self.width + x] = state;
}
fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize
where F: FnMut(State) -> bool
{
let (x, y) = (x as i32, y as i32);
let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];
neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()
}
pub fn next(&mut self) {
let mut next_state = vec![];
for y in 0..self.height {
for x in 0..self.width {
let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);
next_state.push(self.get(x, y).unwrap().next(e_count));
}
}
self.data = next_state;
}
}
impl FromStr for WireWorld {
type Err = ();
fn from_str(s: &str) -> Result<WireWorld, ()> {
let s = s.trim();
let height = s.lines().count();
let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);
let mut world = WireWorld::new(width, height);
for (y, line) in s.lines().enumerate() {
for (x, ch) in line.trim_end().chars().enumerate() {
let state = match ch {
'.' => State::Conductor,
't' => State::ElectronTail,
'H' => State::ElectronHead,
_ => State::Empty,
};
world.set(x, y, state);
}
}
Ok(world)
}
} |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Sidef | Sidef | var f = [[], DATA.lines.map {['', .chars..., '']}..., []];
10.times {
say f.map { .join(" ") + "\n" }.join;
var a = [[]];
for y in (1 .. f.end-1) {
var r = f[y];
var rr = [''];
for x in (1 .. r.end-1) {
var c = r[x];
rr << (
given(c) {
when('H') { 't' }
when('t') { '.' }
when('.') { <. H>[f.ft(y-1, y+1).map{.ft(x-1, x+1)...}.count('H') ~~ [1,2]] }
default { c }
}
)
}
rr << '';
a << rr;
}
f = [a..., []];
}
__DATA__
tH.........
. .
...
. .
Ht.. ...... |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic |
DataSection
Data.s "In olden times when wishing still helped one, there lived a king "+
"whose daughters were all beautiful, but the youngest was so beautiful "+
"that the sun itself, which has seen so much, was astonished whenever "+
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "+
"forest, and under an old lime-tree in the forest was a well, and when "+
"the day was very warm, the king's child went out into the forest and "+
"sat down by the side of the cool-fountain, and when she was bored she "+
"took a golden ball, and threw it up on high and caught it, and this "+
"ball was her favorite plaything."
EndDataSection
Procedure.i ww_pos(txt$,l.i)
While Mid(txt$,l,1)<>Chr(32) And l>0 And Len(txt$)>l : l-1 : Wend
If l>0 : ProcedureReturn l : Else : ProcedureReturn Len(Trim(txt$)) : EndIf
EndProcedure
Procedure WriteLine(txt$,ls.i)
Shared d$,lw
Select LCase(d$)
Case "l" : PrintN(Mid(txt$,1,ls))
Case "r" : PrintN(RSet(Trim(Mid(txt$,1,ls)),lw,Chr(32)))
EndSelect
EndProcedure
Procedure main(txt$,lw.i)
If Len(txt$)
p=ww_pos(txt$,lw) : WriteLine(txt$,p) : ProcedureReturn main(LTrim(Right(txt$,Len(txt$)-p)),lw)
EndIf
EndProcedure
Procedure.i MaxWordLen(txt$)
For i=1 To CountString(txt$,Chr(32))+1
wrd$=LTrim(StringField(txt$,i,Chr(32)))
wrdl=Len(wrd$)+1 : If wrdl>l : l=wrdl : EndIf
Next
ProcedureReturn l
EndProcedure
OpenConsole()
Read.s t$
Print("Input line width: ") : lw=Val(Input()) : minL=MaxWordLen(t$)
If lw<minL : lw=minL : PrintN("Min. line width "+Str(lw-1)) : EndIf
Print("Input direction l:left r:rigth ")
Repeat : d$=Inkey() : Delay(50) : Until FindString("lr",d$,1,#PB_String_NoCase) : PrintN(d$+#CRLF$)
main(t$,lw) : Input()
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Visual_Basic_.NET | Visual Basic .NET | Dim xml = <Students>
<Student Name="April"/>
<Student Name="Bob"/>
<Student Name="Chad"/>
<Student Name="Dave"/>
<Student Name="Emily"/>
</Students>
Dim names = (From node In xml...<Student> Select node.@Name).ToArray
For Each name In names
Console.WriteLine(name)
Next |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #PL.2FSQL | PL/SQL |
DECLARE
TYPE doorsarray IS VARRAY(100) OF BOOLEAN;
doors doorsarray := doorsarray();
BEGIN
doors.EXTEND(100); --ACCOMMODATE 100 DOORS
FOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE
LOOP
doors(i) := FALSE;
END LOOP;
FOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE
LOOP
FOR k IN 1 .. 100
LOOP
IF MOD(k,j)=0 THEN
doors(k) := NOT doors(k);
END IF;
END LOOP;
END LOOP;
FOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION
LOOP
DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE'
THEN 'OPEN'
ELSE 'CLOSED'
END);
END LOOP;
END;
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #PHP | PHP | <?
$contents = file('http://tycho.usno.navy.mil/cgi-bin/timer.pl');
foreach ($contents as $line){
if (($pos = strpos($line, ' UTC')) === false) continue;
echo subStr($line, 4, $pos - 4); //Prints something like "Dec. 06, 16:18:03"
break;
} |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic | EnableExplicit
Structure wordcount
wkey$
count.i
EndStructure
Define token.c, word$, idx.i, start.i, arg$
NewMap wordmap.i()
NewList wordlist.wordcount()
If OpenConsole("")
arg$ = ProgramParameter(0)
If arg$ = "" : End 1 : EndIf
start = ElapsedMilliseconds()
If ReadFile(0, arg$, #PB_Ascii)
While Not Eof(0)
token = ReadCharacter(0, #PB_Ascii)
Select token
Case 'A' To 'Z', 'a' To 'z'
word$ + LCase(Chr(token))
Default
If word$
wordmap(word$) + 1
word$ = ""
EndIf
EndSelect
Wend
CloseFile(0)
ForEach wordmap()
AddElement(wordlist())
wordlist()\wkey$ = MapKey(wordmap())
wordlist()\count = wordmap()
Next
SortStructuredList(wordlist(), #PB_Sort_Descending, OffsetOf(wordcount\count), TypeOf(wordcount\count))
PrintN("Elapsed milliseconds: " + Str(ElapsedMilliseconds() - start))
PrintN("File: " + GetFilePart(arg$))
PrintN(~"Rank\tCount\t\t Word")
If FirstElement(wordlist())
For idx = 1 To 10
Print(RSet(Str(idx), 2))
Print(~"\t")
Print(wordlist()\wkey$)
Print(~"\t\t")
PrintN(RSet(Str(wordlist()\count), 6))
If NextElement(wordlist()) = 0
Break
EndIf
Next
EndIf
EndIf
Input()
EndIf
End |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Smalltalk | Smalltalk | (* Maximilian Wuttke 12.04.2016 *)
type world = char vector vector
fun getstate (w:world, (x, y)) = (Vector.sub (Vector.sub (w, y), x)) handle Subscript => #" "
fun conductor (w:world, (x, y)) =
let
val s = [getstate (w, (x-1, y-1)) = #"H", getstate (w, (x-1, y)) = #"H", getstate (w, (x-1, y+1)) = #"H",
getstate (w, (x, y-1)) = #"H", getstate (w, (x, y+1)) = #"H",
getstate (w, (x+1, y-1)) = #"H", getstate (w, (x+1, y)) = #"H", getstate (w, (x+1, y+1)) = #"H"]
(* Count `true` in s *)
val count = List.length (List.filter (fn x => x=true) s)
in
if count = 1 orelse count = 2 then #"H" else #"."
end
fun translate (w:world, (x, y)) =
case getstate (w, (x, y)) of
#" " => #" "
| #"H" => #"t"
| #"t" => #"."
| #"." => conductor (w, (x, y))
| s => s
fun next_world (w : world) = Vector.mapi (fn (y, row) => Vector.mapi (fn (x, _) => translate (w, (x, y))) row) w
(* Test *)
(* makes a list of strings into a world *)
fun make_world (rows : string list) : world =
Vector.fromList (map (fn (row : string) => Vector.fromList (explode row)) rows)
(* word_str reverses make_world *)
fun vec_str (r:char vector) = implode (List.tabulate (Vector.length r, fn x => Vector.sub (r, x)))
fun world_str (w:world) = List.tabulate (Vector.length w, fn y => vec_str (Vector.sub (w, y)))
fun print_world (w:world) = (map (fn row_str => print (row_str ^ "\n")) (world_str w); ())
val test = make_world [
"tH.........",
". . ",
" ... ",
". . ",
"Ht.. ......"] |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | >>> import textwrap
>>> help(textwrap.fill)
Help on function fill in module textwrap:
fill(text, width=70, **kwargs)
Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.
>>> txt = '''\
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.'''
>>> print(textwrap.fill(txt, width=75))
Reformat the single paragraph in 'text' to fit in lines of no more than
'width' columns, and return a new string containing the entire wrapped
paragraph. As with wrap(), tabs are expanded and other whitespace
characters converted to space. See TextWrapper class for available keyword
args to customize wrapping behaviour.
>>> print(textwrap.fill(txt, width=45))
Reformat the single paragraph in 'text' to
fit in lines of no more than 'width' columns,
and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are
expanded and other whitespace characters
converted to space. See TextWrapper class
for available keyword args to customize
wrapping behaviour.
>>> print(textwrap.fill(txt, width=85))
Reformat the single paragraph in 'text' to fit in lines of no more than 'width'
columns, and return a new string containing the entire wrapped paragraph. As with
wrap(), tabs are expanded and other whitespace characters converted to space. See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Wren | Wren | import "/pattern" for Pattern
import "/fmt" for Conv
var xml =
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet Type=\"dog\" Name=\"Rover\" />
</Student>
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>"
var p = Pattern.new("<+1^>>")
var p2 = Pattern.new(" Name/=\"[+1^\"]\"")
var p3 = Pattern.new("/&/#x[+1/h];")
var matches = p.findAll(xml)
for (m in matches) {
var text = m.text
if (text.startsWith("<Student ")) {
var match = p2.find(m.text)
if (match) {
var name = match.captures[0].text
var escapes = p3.findAll(name)
for (esc in escapes) {
var hd = esc.captures[0].text
var char = String.fromCodePoint(Conv.atoi(hd, 16))
name = name.replace(esc.text, char)
}
System.print(name)
}
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Pointless | Pointless | output =
range(1, 100)
|> map(visit(100))
|> println
----------------------------------------------------------
toggle(state) =
if state == Closed then Open else Closed
----------------------------------------------------------
-- Door state on iteration i is recursively
-- defined in terms of previous door state
visit(i, index) = cond {
case (i == 0) Closed
case (index % i == 0) toggle(lastState)
else lastState
} where lastState = visit(i - 1, index) |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #PicoLisp | PicoLisp | (load "@lib/http.l")
(client "tycho.usno.navy.mil" 80 "cgi-bin/timer.pl"
(when (from "<BR>")
(pack (trim (till "U"))) ) ) |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #PowerShell | PowerShell | $wc = New-Object Net.WebClient
$html = $wc.DownloadString('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
$html -match ', (.*) UTC' | Out-Null
Write-Host $Matches[1] |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | import collections
import re
import string
import sys
def main():
counter = collections.Counter(re.findall(r"\w+",open(sys.argv[1]).read().lower()))
print counter.most_common(int(sys.argv[2]))
if __name__ == "__main__":
main() |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Standard_ML | Standard ML | (* Maximilian Wuttke 12.04.2016 *)
type world = char vector vector
fun getstate (w:world, (x, y)) = (Vector.sub (Vector.sub (w, y), x)) handle Subscript => #" "
fun conductor (w:world, (x, y)) =
let
val s = [getstate (w, (x-1, y-1)) = #"H", getstate (w, (x-1, y)) = #"H", getstate (w, (x-1, y+1)) = #"H",
getstate (w, (x, y-1)) = #"H", getstate (w, (x, y+1)) = #"H",
getstate (w, (x+1, y-1)) = #"H", getstate (w, (x+1, y)) = #"H", getstate (w, (x+1, y+1)) = #"H"]
(* Count `true` in s *)
val count = List.length (List.filter (fn x => x=true) s)
in
if count = 1 orelse count = 2 then #"H" else #"."
end
fun translate (w:world, (x, y)) =
case getstate (w, (x, y)) of
#" " => #" "
| #"H" => #"t"
| #"t" => #"."
| #"." => conductor (w, (x, y))
| s => s
fun next_world (w : world) = Vector.mapi (fn (y, row) => Vector.mapi (fn (x, _) => translate (w, (x, y))) row) w
(* Test *)
(* makes a list of strings into a world *)
fun make_world (rows : string list) : world =
Vector.fromList (map (fn (row : string) => Vector.fromList (explode row)) rows)
(* word_str reverses make_world *)
fun vec_str (r:char vector) = implode (List.tabulate (Vector.length r, fn x => Vector.sub (r, x)))
fun world_str (w:world) = List.tabulate (Vector.length w, fn y => vec_str (Vector.sub (w, y)))
fun print_world (w:world) = (map (fn row_str => print (row_str ^ "\n")) (world_str w); ())
val test = make_world [
"tH.........",
". . ",
" ... ",
". . ",
"Ht.. ......"] |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Tcl | Tcl | #import std
rule = case~&l\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?</`H! `.!}
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
evolve "n" = @iNC ~&x+ rep"n" ^C\~& rule**+ neighborhoods@h |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Quackery | Quackery | $ "Consider the inexorable logic of the Big Lie. If a man has
a consuming love for cats and dedicates himself to the
protection of cats, you have only to accuse him of killing
and mistreating cats. Your lie will have the unmistakable
ring of truth, whereas his outraged denials will reek of
falsehood and evasion. Those who have heard voices from the
nondominant brain hemisphere remark of the absolute
authority of the voice. They know they are hearing the
Truth. The fact that no evidence is adduced and that the
voice may be talking utter nonsense has nothing to do with
facts. Those who manipulate Truth to their advantage, the
people of the Big Lie, are careful to shun facts. In fact
nothing is more deeply offensive to such people than the
concept of fact. To adduce fact in your defense is to rule
yourself out of court."
nest$ dup
55 wrap$ cr
75 wrap$ cr
say "-- William S. Burroughs, Ghost Of Chance, 1981" cr |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #R | R | > x <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. "
> cat(paste(strwrap(x=c(x, "\n"), width=80), collapse="\n"))
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero
egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem
lacinia consectetur.
> cat(paste(strwrap(x=c(x, "\n"), width=60), collapse="\n"))
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas
congue ligula ac quam viverra nec consectetur ante
hendrerit. Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur. |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #XPL0 | XPL0 | code ChOut=8, CrLf=9; \intrinsic routines
string 0; \use zero-terminated strings
func StrLen(A); \Return number of characters in an ASCIIZ string
char A;
int I;
for I:= 0 to -1>>1-1 do
if A(I) = 0 then return I;
func StrFind(A, B); \Search for ASCIIZ string A in string B
\Returns address of first occurrence of string A in B, or zero if A is not found
char A, B; \strings to be compared
int LA, LB, I, J;
[LA:= StrLen(A);
LB:= StrLen(B);
for I:= 0 to LB-LA do
[for J:= 0 to LA-1 do
if A(J) # B(J+I) then J:= LA+1;
if J = LA then return B+I; \found
];
return 0;
];
char XML, P;
[XML:= "<Students>
<Student Name=^"April^" Gender=^"F^" DateOfBirth=^"1989-01-02^" />
<Student Name=^"Bob^" Gender=^"M^" DateOfBirth=^"1990-03-04^" />
<Student Name=^"Chad^" Gender=^"M^" DateOfBirth=^"1991-05-06^" />
<Student Name=^"Dave^" Gender=^"M^" DateOfBirth=^"1992-07-08^">
<Pet Type=^"dog^" Name=^"Rover^" />
</Student>
<Student DateOfBirth=^"1993-09-10^" Gender=^"F^" Name=^"Émily^" />
</Students>";
P:= XML;
loop [P:= StrFind("<Student ", P);
if P=0 then quit;
P:= StrFind("Name=", P);
if P=0 then quit;
P:= P + StrLen("Name=x");
repeat ChOut(0, P(0));
P:= P+1;
until P(0) = ^";
CrLf(0);
];
] |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Yabasic | Yabasic | // ========== routine for set code conversion ================
data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238
data 248, 241, 253, 252, 239, 230, 244, 250, 247, 251, 167, 175, 172, 171, 243, 168
data 183, 181, 182, 199, 142, 143, 146, 128, 212, 144, 210, 211, 222, 214, 215, 216
data 209, 165, 227, 224, 226, 229, 153, 158, 157, 235, 233, 234, 154, 237, 232, 225
data 133, 160, 131, 198, 132, 134, 145, 135, 138, 130, 136, 137, 141, 161, 140, 139
data 208, 164, 149, 162, 147, 228, 148, 246, 155, 151, 163, 150, 129, 236, 231, 152
initCode = 160 : TOASCII = 0 : TOUNICODE = 1 : numCodes = 255 - initCode + 1
dim codes(numCodes)
for i = 0 to numCodes - 1 : read codes(i) : next
sub codeConversion(charcode, tocode)
local i
if tocode then
for i = 0 to numCodes - 1
if codes(i) = charcode return i + initCode
next
else
return codes(charcode - initCode)
end if
end sub
// ========== end routine for set code conversion ============
xml$ = "<Students>\n"
xml$ = xml$ + " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
xml$ = xml$ + " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n"
xml$ = xml$ + " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n"
xml$ = xml$ + " <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n"
xml$ = xml$ + " <Pet Type=\"dog\" Name=\"Rover\" />\n"
xml$ = xml$ + " </Student>\n"
xml$ = xml$ + " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
xml$ = xml$ + "</Students>\n"
tag1$ = "<Student"
tag2$ = "Name=\""
ltag = len(tag2$)
sub convASCII$(name$, mark$)
local p, c, lm
lm = len(mark$)
do
p = instr(name$, mark$, p)
if not p break
c = dec(mid$(name$, p + lm, 4))
c = codeConversion(c)
name$ = left$(name$, p-1) + chr$(c) + right$(name$, len(name$) - (p + lm + 4))
p = p + 1
loop
return name$
end sub
do
p = instr(xml$, tag1$, p)
if not p break
p = instr(xml$, tag2$, p)
p = p + ltag
p2 = instr(xml$, "\"", p)
name$ = convASCII$(mid$(xml$, p, p2 - p), "&#x")
print name$
loop |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Polyglot:PL.2FI_and_PL.2FM | Polyglot:PL/I and PL/M | /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */
doors_100H: procedure options (main);
/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */
/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */
/* PL/I */
%replace dcldoors by 100;
/* PL/M */ /*
DECLARE DCLDOORS LITERALLY '101';
/* */
/* PL/I DEFINITIONS */
%include 'pg.inc';
/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*
DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';
DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';
DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';
DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';
BDOSF: PROCEDURE( FN, ARG )BYTE;
DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
PRNUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL BDOS( 9, .N$STR( W ) );
END PRNUMBER;
MODF: PROCEDURE( A, B )ADDRESS;
DECLARE ( A, B ) ADDRESS;
RETURN A MOD B;
END MODF;
/* END LANGUAGE DEFINITIONS */
/* TASK */
/* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */
DECLARE DOOR( DCLDOORS ) BIT;
DECLARE ( I, J, MAXDOOR ) FIXED BINARY;
MAXDOOR = HBOUND( DOOR ,1
);
/* SET ALL DOORS TO CLOSED */
DO I = 0 TO MAXDOOR; DOOR( I ) = FALSE; END;
/* REPEATEDLY FLIP THE DOORS */
DO I = 1 TO MAXDOOR;
DO J = I TO MAXDOOR BY I;
DOOR( J ) = NOT( DOOR( J ) );
END;
END;
/* DISPLAY THE RESULTS */
DO I = 1 TO MAXDOOR;
IF DOOR( I ) THEN DO;
CALL PRCHAR( ' ' );
CALL PRNUMBER( I );
END;
END;
CALL PRNL;
EOF: end doors_100H; |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #PureBasic | PureBasic | URLDownloadToFile_( #Null, "http://tycho.usno.navy.mil/cgi-bin/timer.pl", "timer.htm", 0, #Null)
ReadFile(0, "timer.htm")
While Not Eof(0) : Text$ + ReadString(0) : Wend
MessageRequester("Time", Mid(Text$, FindString(Text$, "UTC", 1) - 9 , 8)) |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Python | Python | import urllib
page = urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
for line in page:
if ' UTC' in line:
print line.strip()[4:]
break
page.close() |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #R | R |
wordcount<-function(file,n){
punctuation=c("`","~","!","@","#","$","%","^","&","*","(",")","_","+","=","{","[","}","]","|","\\",":",";","\"","<",",",">",".","?","/","'s")
wordlist=scan(file,what=character())
wordlist=tolower(wordlist)
for(i in 1:length(punctuation)){
wordlist=gsub(punctuation[i],"",wordlist,fixed=T)
}
df=data.frame("Word"=sort(unique(wordlist)),"Count"=rep(0,length(unique(wordlist))))
for(i in 1:length(unique(wordlist))){
df[i,2]=length(which(wordlist==df[i,1]))
}
df=df[order(df[,2],decreasing = T),]
row.names(df)=1:nrow(df)
return(df[1:n,])
}
|
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket | #lang racket
(define (all-words f (case-fold string-downcase))
(map case-fold (regexp-match* #px"\\w+" (file->string f))))
(define (l.|l| l) (cons (car l) (length l)))
(define (counts l (>? >)) (sort (map l.|l| (group-by values l)) >? #:key cdr))
(module+ main
(take (counts (all-words "data/les-mis.txt")) 10)) |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Ursala | Ursala | #import std
rule = case~&l\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?</`H! `.!}
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
evolve "n" = @iNC ~&x+ rep"n" ^C\~& rule**+ neighborhoods@h |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Wren | Wren | import "/fmt" for Fmt
import "/ioutil" for FileUtil, Stdin
var rows = 0 // extent of input configuration
var cols = 0 // """
var rx = 0 // grid extent (includes border)
var cx = 0 // """
var mn = [] // offsets of Moore neighborhood
var print = Fn.new { |grid|
System.print("__" * cols)
System.print()
for (r in 1..rows) {
for (c in 1..cols) Fmt.write(" $s", grid[r*cx+c])
System.print()
}
}
var step = Fn.new { |dst, src|
for (r in 1..rows) {
for (c in 1..cols) {
var x = r*cx + c
dst[x] = src[x]
if (dst[x] == "H") {
dst[x] = "t"
} else if (dst[x] == "t") {
dst[x] = "."
} else if (dst[x] == ".") {
var nn = 0
for (n in mn) {
if (src[x+n] == "H") nn = nn + 1
}
if (nn == 1 || nn == 2) dst[x] = "H"
}
}
}
}
var srcRows = FileUtil.readLines("ww.config")
rows = srcRows.count
for (r in srcRows) {
if (r.count > cols) cols = r.count
}
rx = rows + 2
cx = cols + 2
mn = [-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1]
// allocate two grids and copy input into first grid
var odd = List.filled(rx*cx, " ")
var even = List.filled(rx*cx, " ")
var ri = 0
for (r in srcRows) {
for (i in 0...r.count) {
odd[(ri+1)*cx+1+i] = r[i]
}
ri = ri + 1
}
// run
while (true) {
print.call(odd)
step.call(even, odd)
Stdin.readLine() // wait for enter to be pressed
print.call(even)
step.call(odd, even)
Stdin.readLine() // ditto
} |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket |
#lang at-exp racket
(require scribble/text/wrap)
(define text
@(λ xs (regexp-replace* #rx" *\n *" (string-append* xs) " ")){
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in her
face. Close by the king's castle lay a great dark forest, and under an old
lime-tree in the forest was a well, and when the day was very warm, the
king's child went out into the forest and sat down by the side of the cool
fountain, and when she was bored she took a golden ball, and threw it up on
high and caught it, and this ball was her favorite plaything.})
(for-each displayln (wrap-line text 60))
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Raku | Raku | my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close-by-the-king's-castle-lay-a-great-dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.";
$s ~~ s:g/»\s+/ /;
$s ~~ s/\s*$/\n\n/;
say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g);
say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g); |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #zkl | zkl | student:=RegExp(0'|.*<Student\s*.+Name\s*=\s*"([^"]+)"|);
unicode:=RegExp(0'|.*(&#x[0-9a-fA-F]+;)|);
xml:=File("foo.xml").read();
students:=xml.pump(List,'wrap(line){
if(student.search(line)){
s:=student.matched[1]; // ( (match start,len),group text )
while(unicode.search(s)){ // convert "É" to 0xc9 to UTF-8
c:=unicode.matched[1];
uc:=c[3,-1].toInt(16).toString(-8);
s=s.replace(c,uc);
}
s
}
else Void.Skip; // line doesn't contain <Student ... Name ...
});
students.println(); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Pony | Pony |
actor Toggler
let doors:Array[Bool]
let env: Env
new create(count:USize,_env:Env) =>
var i:USize=0
doors=Array[Bool](count)
env=_env
while doors.size() < count do
doors.push(false)
end
be togglin(interval : USize)=>
var i:USize=0
try
while i < doors.size() do
doors.update(i,not doors(i)?)?
i=i+interval
end
else
env.out.print("Errored while togglin'!")
end
be printn(onlyOpen:Bool)=>
try
for i in doors.keys() do
if onlyOpen and not doors(i)? then
continue
end
env.out.print("Door " + i.string() + " is " +
if doors(i)? then
"Open"
else
"closed"
end)
end
else
env.out.print("Error!")
end
true
actor OptimizedToggler
let doors:Array[Bool]
let env:Env
new create(count:USize,_env:Env)=>
env=_env
doors=Array[Bool](count)
while doors.size()<count do
doors.push(false)
end
be togglin()=>
var i:USize=0
if alreadydone then
return
end
try
doors.update(0,true)?
doors.update(1,true)?
while i < doors.size() do
i=i+1
let z=i*i
let x=z*z
if z > doors.size() then
break
else
doors.update(z,true)?
end
if x < doors.size() then
doors.update(x,true)?
end
end
end
be printn(onlyOpen:Bool)=>
try
for i in doors.keys() do
if onlyOpen and not doors(i)? then
continue
end
env.out.print("Door " + i.string() + " is " +
if doors(i)? then
"Open"
else
"closed"
end)
end
else
env.out.print("Error!")
end
true
actor Main
new create(env:Env)=>
var count: USize =100
try
let index=env.args.find("-n",0,0,{(l,r)=>l==r})?
try
match env.args(index+1)?.read_int[USize]()?
| (let x:USize, _)=>count=x
end
else
env.out.print("You either neglected to provide an argument after -n or that argument was not an integer greater than zero.")
return
end
end
if env.args.contains("optimized",{(l,r)=>r==l}) then
let toggler=OptimizedToggler(count,env)
var i:USize = 1
toggler.togglin()
toggler.printn(env.args.contains("onlyopen", {(l,r)=>l==r}))
else
let toggler=Toggler(count,env)
var i:USize = 1
while i < count do
toggler.togglin(i)
i=i+1
end
toggler.printn(env.args.contains("onlyopen", {(l,r)=>l==r}))
end
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #R | R |
all_lines <- readLines("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
utc_line <- grep("UTC", all_lines, value = TRUE)
matched <- regexpr("(\\w{3}.*UTC)", utc_line)
utc_time_str <- substring(line, matched, matched + attr(matched, "match.length") - 1L)
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Racket | Racket |
#lang racket
(require net/url)
((compose1 car (curry regexp-match #rx"[^ <>][^<>]+ UTC")
port->string get-pure-port string->url)
"https://tycho.usno.navy.mil/cgi-bin/timer.pl")
|
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Raku | Raku | sub MAIN ($filename, $top = 10) {
my $file = $filename.IO.slurp.lc.subst(/ (<[\w]-[_]>'-')\n(<[\w]-[_]>) /, {$0 ~ $1}, :g );
my @matcher = (
rx/ <[a..z]>+ /, # simple 7-bit ASCII
rx/ \w+ /, # word characters with underscore
rx/ <[\w]-[_]>+ /, # word characters without underscore
rx/ <[\w]-[_]>+[["'"|'-'|"'-"]<[\w]-[_]>+]* / # word characters without underscore but with hyphens and contractions
);
for @matcher -> $reg {
say "\nTop $top using regex: ", $reg.raku;
.put for $file.comb( $reg ).Bag.sort(-*.value)[^$top];
}
} |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
char New(53,40), Old(53,40);
proc Block(X0, Y0, C); \Display a colored block
int X0, Y0, C; \big (6x5) coordinates, char
int X, Y;
[case C of \convert char to color
^H: C:= $9; \blue
^t: C:= $C; \red
^.: C:= $E \yellow
other C:= 0; \black
for Y:= Y0*5 to Y0*5+4 do \make square blocks by correcting aspect ratio
for X:= X0*6 to X0*6+5 do \ (6x5 = square)
Point(X,Y,C);
];
int X, Y, C;
[SetVid($13); \set 320x200 graphics display
for Y:= 0 to 40-1 do \initialize New with space (empty) characters
for X:= 0 to 53-1 do
New(X, Y):= ^ ;
X:= 1; Y:= 1; \read file from command line, skipping borders
loop [C:= ChIn(1);
case C of
$0D: X:= 1; \carriage return
$0A: Y:= Y+1; \line feed
$1A: quit \end of file
other [New(X,Y):= C; X:= X+1];
];
repeat C:= Old; Old:= New; New:= C; \swap arrays, by swapping their pointers
for Y:= 1 to 39-1 do \generate New array from Old
for X:= 1 to 52-1 do \ (skipping borders)
[case Old(X,Y) of
^ : New(X,Y):= ^ ; \copy empty to empty
^H: New(X,Y):= ^t; \convert head to tail
^t: New(X,Y):= ^. \convert tail to conductor
other [C:= (Old(X-1,Y-1)=^H) + (Old(X+0,Y-1)=^H) + \head count
(Old(X+1,Y-1)=^H) + (Old(X-1,Y+0)=^H) + \ in neigh-
(Old(X+1,Y+0)=^H) + (Old(X-1,Y+1)=^H) + \ boring
(Old(X+0,Y+1)=^H) + (Old(X+1,Y+1)=^H); \ cells
New(X,Y):= if C=-1 or C=-2 then ^H else ^.; \ (true=-1)
];
Block(X, Y, New(X,Y)); \display result
];
Sound(0, 6, 1); \delay about 1/3 second
until KeyHit; \keystroke terminates program
SetVid(3); \restore normal text mode
] |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
The cell transition rules are this:
Input State
Output State
Condition
empty
empty
electron head
electron tail
electron tail
conductor
conductor
electron head
if 1 or 2 cells in the neighborhood of the cell are in the state “electron head”
conductor
conductor
otherwise
Task
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
tH.........
. .
...
. .
Ht.. ......
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
| #Yabasic | Yabasic | open window 230,130
backcolor 0,0,0
clear window
label circuit
DATA " "
DATA " tH......... "
DATA " . . "
DATA " ... "
DATA " . . "
DATA " Ht.. ...... "
DATA " "
DATA ""
do
read a$
if a$ = "" break
n = n + 1
redim t$(n)
t$(n) = a$+a$
loop
size = len(t$(1))/2
E2 = size
first = true
Orig = 0
Dest = E2
do
for y = 2 to n-1
for x = 2 to E2-1
switch mid$(t$(y),x+Orig,1)
case " ": color 32,32,32 : mid$(t$(y),x+Dest,1) = " " : break
case "H": color 0,0,255 : mid$(t$(y),x+Dest,1) = "t" : break
case "t": color 255,0,0 : mid$(t$(y),x+Dest,1) = "." : break
case ".":
color 255,200,0
t = 0
for y1 = y-1 to y+1
for x1 = x-1 to x+1
t = t + ("H" = mid$(t$(y1),x1+Orig,1))
next x1
next y1
if t=1 or t=2 then
mid$(t$(y),x+Dest,1) = "H"
else
mid$(t$(y),x+Dest,1) = "."
end if
end switch
fill circle x*16, y*16, 8
next x
print t$(y),"="
next y
first = not first
if first then
Orig = 0 : Dest = E2
else
Orig = E2 : Dest = 0
end if
wait .5
loop
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #REXX | REXX | /*REXX program reads a file and displays it to the screen (with word wrap). */
parse arg iFID width . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID='LAWS.TXT' /*Not specified? Then use the default.*/
if width=='' | width=="," then width=linesize() /* " " " " " " */
@= /*number of words in the file (so far).*/
do while lines(iFID)\==0 /*read from the file until End-Of-File.*/
@=@ linein(iFID) /*get a record (line of text). */
end /*while*/
$=word(@,1) /*initialize $ with the first word. */
do k=2 for words(@)-1; x=word(@,k) /*parse until text (@) exhausted. */
_=$ x /*append it to the $ list and test. */
if length(_)>=width then do; say $ /*this word a bridge too far? > w. */
_=x /*assign this word to the next line. */
end
$=_ /*new words (on a line) are OK so far.*/
end /*m*/
if $\=='' then say $ /*handle any residual words (overflow).*/
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Pop11 | Pop11 | lvars i;
lvars doors = {% for i from 1 to 100 do false endfor %};
for i from 1 to 100 do
for j from i by i to 100 do
not(doors(j)) -> doors(j);
endfor;
endfor;
;;; Print state
for i from 1 to 100 do
printf('Door ' >< i >< ' is ' ><
if doors(i) then 'open' else 'closed' endif, '%s\n');
endfor; |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Raku | Raku | # 20210301 Updated Raku programming solution
use HTTP::Client; # https://github.com/supernovus/perl6-http-client/
#`[ Site inaccessible since 2019 ?
my $site = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
HTTP::Client.new.get($site).content.match(/'<BR>'( .+? <ws> UTC )/)[0].say
# ]
my $site = "https://www.utctime.net/";
my $matched = HTTP::Client.new.get($site).content.match(
/'<td>UTC</td><td>'( .*Z )'</td>'/
)[0];
say $matched;
#$matched = '12321321:412312312 123';
with DateTime.new($matched.Str) {
say 'The fetch result seems to be of a valid time format.'
} else {
CATCH { put .^name, ': ', .Str }
} |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #REXX | REXX | /*REXX pgm displays top 10 words in a file (includes foreign letters), case is ignored.*/
parse arg fID top . /*obtain optional arguments from the CL*/
if fID=='' | fID=="," then fID= 'les_mes.txt' /*None specified? Then use the default.*/
if top=='' | top=="," then top= 10 /* " " " " " " */
call init /*initialize varied bunch of variables.*/
call rdr
say right('word', 40) " " center(' rank ', 6) " count " /*display title for output*/
say right('════', 40) " " center('══════', 6) " ═══════" /* " title separator.*/
do until otops==tops | tops>top /*process enough words to satisfy TOP.*/
WL=; mk= 0; otops= tops /*initialize the word list (to a NULL).*/
do n=1 for c; z= !.n; k= @.z /*process the list of words in the file*/
if k==mk then WL= WL z /*handle cases of tied number of words.*/
if k> mk then do; mk=k; WL=z; end /*this word count is the current max. */
end /*n*/
wr= max( length(' rank '), length(top) ) /*find the maximum length of the rank #*/
do d=1 for words(WL); y= word(WL, d) /*process all words in the word list. */
if d==1 then w= max(10, length(@.y) ) /*use length of the first number used. */
say right(y, 40) right( commas(tops), wr) right(commas(@.y), w)
@.y= . /*nullify word count for next go 'round*/
end /*d*/ /* [↑] this allows a non-sorted list. */
tops= tops + words(WL) /*correctly handle any tied rankings.*/
end /*until*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
16bit: do k=1 for xs; _=word(x,k); $=changestr('├'left(_,1),$,right(_,1)); end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
init: x= 'Çà åÅ çÇ êÉ ëÉ áà óâ ªæ ºç ¿è ⌐é ¬ê ½ë «î »ï ▒ñ ┤ô ╣ù ╗û ╝ü'; xs= words(x)
abcL="abcdefghijklmnopqrstuvwxyz'" /*lowercase letters of Latin alphabet. */
abcU= abcL; upper abcU /*uppercase version of Latin alphabet. */
accL= 'üéâÄàÅÇêëèïîìéæôÖòûùÿáíóúÑ' /*some lowercase accented characters. */
accU= 'ÜéâäàåçêëèïîìÉÆôöòûùÿáíóúñ' /* " uppercase " " */
accG= 'αßΓπΣσµτΦΘΩδφε' /* " upper/lowercase Greek letters. */
ll= abcL || abcL ||accL ||accL || accG /*chars of after letters. */
uu= abcL || abcU ||accL ||accU || accG || xrange() /* " " before " */
@.= 0; q= "'"; totW= 0; !.= @.; c= 0; tops= 1; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
rdr: do #=0 while lines(fID)\==0; $=linein(fID) /*loop whilst there're lines in file.*/
if pos('├', $) \== 0 then call 16bit /*are there any 16-bit characters ?*/
$= translate( $, ll, uu) /*trans. uppercase letters to lower. */
do while $ \= ''; parse var $ z $ /*process each word in the $ line. */
parse var z z1 2 zr '' -1 zL /*obtain: first, middle, & last char.*/
if z1==q then do; z=zr; if z=='' then iterate; end /*starts with apostrophe?*/
if zL==q then z= strip(left(z, length(z) - 1)) /*ends " " ?*/
if z=='' then iterate /*if Z is now null, skip.*/
if @.z==0 then do; c=c+1; !.c=z; end /*bump word cnt; assign word to array*/
totW= totW + 1; @.z= @.z + 1 /*bump total words; bump a word count*/
end /*while*/
end /*#*/
say commas(totW) ' words found ('commas(c) "unique) in " commas(#),
' records read from file: ' fID; say; return |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Ring | Ring |
# Project : Word wrap
load "stdlib.ring"
doc = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything."
wordwrap(doc,72)
wordwrap(doc,80)
func wordwrap(doc, maxline)
words = split(doc, " ")
line = words[1]
for i=2 to len(words)
word = words[i]
if len(line)+len(word)+1 > maxline
see line + nl
line = word
else
line = line + " " + word
ok
next
see line + nl + nl
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Ruby | Ruby | class String
def wrap(width)
txt = gsub("\n", " ")
para = []
i = 0
while i < length
j = i + width
j -= 1 while j != txt.length && j > i + 1 && !(txt[j] =~ /\s/)
para << txt[i ... j]
i = j + 1
end
para
end
end
text = <<END
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.
END
[72,80].each do |w|
puts "." * w
puts text.wrap(w)
end |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #PostScript | PostScript | /doors [ 100 { false } repeat ] def
1 1 100 { dup 1 sub exch 99 {
dup doors exch get not doors 3 1 roll put
} for } for
doors pstack |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #REBOL | REBOL | rebol [
Title: "Web Scraping"
URL: http://rosettacode.org/wiki/Web_Scraping
]
; Notice that REBOL understands unquoted URL's:
service: http://tycho.usno.navy.mil/cgi-bin/timer.pl
; The 'read' function can read from any data scheme that REBOL knows
; about, which includes web URLs. NOTE: Depending on your security
; settings, REBOL may ask you for permission to contact the service.
html: read service
; I parse the HTML to find the first <br> (note the unquoted HTML tag
; -- REBOL understands those too), then copy the current time from
; there to the "UTC" terminator.
; I have the "to end" in the parse rule so the parse will succeed.
; Not strictly necessary once I've got the time, but good practice.
parse html [thru <br> copy current thru "UTC" to end]
print ["Current UTC time:" current] |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Ruby | Ruby | require "open-uri"
open('http://tycho.usno.navy.mil/cgi-bin/timer.pl') do |p|
p.each_line do |line|
if line =~ /UTC/
puts line.match(/ (\d{1,2}:\d{1,2}:\d{1,2}) /)
break
end
end
end
|
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Ring | Ring |
# project : Word count
fp = fopen("Miserables.txt","r")
str = fread(fp, getFileSize(fp))
fclose(fp)
mis =substr(str, " ", nl)
mis = lower(mis)
mis = str2list(mis)
count = list(len(mis))
ready = []
for n = 1 to len(mis)
flag = 0
for m = 1 to len(mis)
if mis[n] = mis[m] and n != m
for p = 1 to len(ready)
if m = ready[p]
flag = 1
ok
next
if flag = 0
count[n] = count[n] + 1
ok
ok
next
if flag = 0
add(ready, n)
ok
next
for n = 1 to len(count)
for m = n + 1 to len(count)
if count[m] > count[n]
temp = count[n]
count[n] = count[m]
count[m] = temp
temp = mis[n]
mis[n] = mis[m]
mis[m] = temp
ok
next
next
for n = 1 to 10
see mis[n] + " " + (count[n] + 1) + nl
next
func getFileSize fp
c_filestart = 0
c_fileend = 2
fseek(fp,0,c_fileend)
nfilesize = ftell(fp)
fseek(fp,0,c_filestart)
return nfilesize
func swap(a, b)
temp = a
a = b
b = temp
return [a, b]
|
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Ruby | Ruby |
class String
def wc
n = Hash.new(0)
downcase.scan(/[A-Za-zÀ-ÿ]+/) { |g| n[g] += 1 }
n.sort{|n,g| n[1]<=>g[1]}
end
end
open('135-0.txt') { |n| n.read.wc[-10,10].each{|n| puts n[0].to_s+"->"+n[1].to_s} }
|
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Run_BASIC | Run BASIC | doc$ = "In olden times when wishing still helped one, there lived a king ";_
"whose daughters were all beautiful, but the youngest was so beautiful ";_
"that the sun itself, which has seen so much, was astonished whenever ";_
"it shone in her face."
wrap$ = " style='white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;";_
"white-space: -o-pre-wrap;word-wrap: break-word'"
html "<table border=1 cellpadding=2 cellspacing=0><tr" + wrap$ +" valign=top>"
html "<td width=60%>" + doc$ + "</td><td width=40%>" + doc$ + "</td></tr></table>" |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Rust | Rust | #[derive(Clone, Debug)]
pub struct LineComposer<I> {
words: I,
width: usize,
current: Option<String>,
}
impl<I> LineComposer<I> {
pub(crate) fn new<S>(words: I, width: usize) -> Self
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
LineComposer {
words,
width,
current: None,
}
}
}
impl<I, S> Iterator for LineComposer<I>
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let mut next = match self.words.next() {
None => return self.current.take(),
Some(value) => value,
};
let mut current = self.current.take().unwrap_or_else(String::new);
loop {
let word = next.as_ref();
if self.width <= current.len() + word.len() {
self.current = Some(String::from(word));
// If the first word itself is too long, avoid producing an
// empty line. Continue instead with the next word.
if !current.is_empty() {
return Some(current);
}
}
if !current.is_empty() {
current.push_str(" ")
}
current.push_str(word);
match self.words.next() {
None => return Some(current), // Last line, current remains None
Some(word) => next = word,
}
}
}
}
// This part is just to extend all suitable iterators with LineComposer
pub trait ComposeLines: Iterator {
fn compose_lines(self, width: usize) -> LineComposer<Self>
where
Self: Sized,
Self::Item: AsRef<str>,
{
LineComposer::new(self, width)
}
}
impl<T, S> ComposeLines for T
where
T: Iterator<Item = S>,
S: AsRef<str>,
{
}
fn main() {
let text = r"
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.";
text.split_whitespace()
.compose_lines(80)
.for_each(|line| println!("{}", line));
}
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Potion | Potion | square=1, i=3
1 to 100(door):
if (door == square):
("door", door, "is open") say
square += i
i += 2.
. |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Run_BASIC | Run BASIC | print word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"<BR>") |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Rust | Rust | // 202100302 Rust programming solution
use std::io::Read;
use regex::Regex;
fn main() {
let client = reqwest::blocking::Client::new();
let site = "https://www.utctime.net/";
let mut res = client.get(site).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
let re = Regex::new(r#"<td>UTC</td><td>(.*Z)</td>"#).unwrap();
let caps = re.captures(&body).unwrap();
println!("Result : {:?}", caps.get(1).unwrap().as_str());
} |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Rust | Rust | use std::cmp::Reverse;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
extern crate regex;
use regex::Regex;
fn word_count(file: File, n: usize) {
let word_regex = Regex::new("(?i)[a-z']+").unwrap();
let mut words = HashMap::new();
for line in BufReader::new(file).lines() {
word_regex
.find_iter(&line.expect("Read error"))
.map(|m| m.as_str())
.for_each(|word| {
*words.entry(word.to_lowercase()).or_insert(0) += 1;
});
}
let mut words: Vec<_> = words.iter().collect();
words.sort_unstable_by_key(|&(word, count)| (Reverse(count), word));
for (word, count) in words.iter().take(n) {
println!("{:8} {:>8}", word, count);
}
}
fn main() {
word_count(File::open("135-0.txt").expect("File open error"), 10)
} |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Scala | Scala | import scala.io.Source
object WordCount extends App {
val url = "http://www.gutenberg.org/files/135/135-0.txt"
val header = "Rank Word Frequency\n==== ======== ======"
def wordCnt =
Source.fromURL(url).getLines()
.filter(_.nonEmpty)
.flatMap(_.split("""\W+""")).toSeq
.groupBy(_.toLowerCase())
.mapValues(_.size).toSeq
.sortWith { case ((_, v0), (_, v1)) => v0 > v1 }
.take(10).zipWithIndex
println(header)
wordCnt.foreach {
case ((word, count), rank) => println(f"${rank + 1}%4d $word%-8s $count%6d")
}
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
} |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Scala | Scala | import java.util.StringTokenizer
object WordWrap extends App {
final val defaultLineWidth = 80
final val spaceWidth = 1
def letsWrap(text: String, lineWidth: Int = defaultLineWidth) = {
println(s"\n\nWrapped at: $lineWidth")
println("." * lineWidth)
minNumLinesWrap(ewd, lineWidth)
}
final def ewd = "Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme. Daarom een kleine ode" +
" aan de in 2002 overleden Dijkstra, iemand waar we als Nederlanders best wat trotser op mogen zijn. Dijkstra was" +
" een van de eerste programmeurs van Nederland. Toen hij in 1957 trouwde, werd het beroep computerprogrammeur door" +
" de burgerlijke stand nog niet erkend en uiteindelijk gaf hij maar `theoretische natuurkundige’ op.\nZijn" +
" beroemdste resultaat is het kortstepadalgoritme, dat de kortste verbinding vindt tussen twee knopen in een graaf" +
" (een verzameling punten waarvan sommigen verbonden zijn). Denk bijvoorbeeld aan het vinden van de kortste route" +
" tussen twee steden. Het slimme van Dijkstra’s algoritme is dat het niet alle mogelijke routes met elkaar" +
" vergelijkt, maar dat het stap voor stap de kortst mogelijke afstanden tot elk punt opbouwt. In de eerste stap" +
" kijk je naar alle punten die vanaf het beginpunt te bereiken zijn en markeer je al die punten met de afstand tot" +
" het beginpunt. Daarna kijk je steeds vanaf het punt dat op dat moment de kortste afstand heeft tot het beginpunt" +
" naar alle punten die je vanaf daar kunt bereiken. Als je een buurpunt via een nieuwe verbinding op een snellere" +
" manier kunt bereiken, schrijf je de nieuwe, kortere afstand tot het beginpunt bij zo’n punt. Zo ga je steeds een" +
" stukje verder tot je alle punten hebt gehad en je de kortste route tot het eindpunt hebt gevonden."
def minNumLinesWrap(text: String, LineWidth: Int) {
val tokenizer = new StringTokenizer(text)
var SpaceLeft = LineWidth
while (tokenizer.hasMoreTokens) {
val word: String = tokenizer.nextToken
if ((word.length + spaceWidth) > SpaceLeft) {
print("\n" + word + " ")
SpaceLeft = LineWidth - word.length
} else {
print(word + " ")
SpaceLeft -= (word.length + spaceWidth)
}
}
}
letsWrap(ewd)
letsWrap(ewd, 120)
} // 44 lines |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #PowerShell | PowerShell | $doors = @(0..99)
for($i=0; $i -lt 100; $i++) {
$doors[$i] = 0 # start with all doors closed
}
for($i=0; $i -lt 100; $i++) {
$step = $i + 1
for($j=$i; $j -lt 100; $j = $j + $step) {
$doors[$j] = $doors[$j] -bxor 1
}
}
foreach($doornum in 1..100) {
if($doors[($doornum-1)] -eq $true) {"$doornum open"}
else {"$doornum closed"}
} |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Scala | Scala |
import scala.io.Source
object WebTime extends Application {
val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
val utc = text.getLines.find(_.contains("UTC"))
utc match {
case Some(s) => println(s.substring(4))
case _ => println("error")
}
}
|
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Scheme | Scheme | ; Use the regular expression module to parse the url
(use-modules (ice-9 regex) (ice-9 rdelim))
; Variable to store result
(define time "")
; Set the url and parse the hostname, port, and path into variables
(define url "http://tycho.usno.navy.mil/cgi-bin/timer.pl")
(define r (make-regexp "^(http://)?([^:/]+)(:)?(([0-9])+)?(/.*)?" regexp/icase))
(define host (match:substring (regexp-exec r url) 2))
(define port (match:substring (regexp-exec r url) 4))
(define path (match:substring (regexp-exec r url) 6))
; Set port to 80 if it wasn't set above and convert from a string to a number
(if (eq? port #f) (define port "80"))
(define port (string->number port))
; Connect to remote host on specified port
(let ((s (socket PF_INET SOCK_STREAM 0)))
(connect s AF_INET (car (hostent:addr-list (gethostbyname host))) port)
; Send a HTTP request for the specified path
(display "GET " s)
(display path s)
(display " HTTP/1.0\r\n\r\n" s)
(set! r (make-regexp "<BR>(.+? UTC)"))
(do ((line (read-line s) (read-line s))) ((eof-object? line))
(if (regexp-match? (regexp-exec r line))
(set! time (match:substring (regexp-exec r line) 1)))))
; Display result
(display time)
(newline) |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "gethttp.s7i";
include "strifile.s7i";
include "scanfile.s7i";
include "chartype.s7i";
include "console.s7i";
const type: wordHash is hash [string] integer;
const type: countHash is hash [integer] array string;
const proc: main is func
local
var file: inFile is STD_NULL;
var string: aWord is "";
var wordHash: numberOfWords is wordHash.EMPTY_HASH;
var countHash: countWords is countHash.EMPTY_HASH;
var array integer: countKeys is 0 times 0;
var integer: index is 0;
var integer: number is 0;
begin
OUT := STD_CONSOLE;
inFile := openStrifile(getHttp("www.gutenberg.org/files/135/135-0.txt"));
while hasNext(inFile) do
aWord := lower(getSimpleSymbol(inFile));
if aWord <> "" and aWord[1] in letter_char then
if aWord in numberOfWords then
incr(numberOfWords[aWord]);
else
numberOfWords @:= [aWord] 1;
end if;
end if;
end while;
countWords := flip(numberOfWords);
countKeys := sort(keys(countWords));
writeln("Word Frequency");
for index range length(countKeys) downto length(countKeys) - 9 do
number := countKeys[index];
for aWord range sort(countWords[number]) do
writeln(aWord rpad 8 <& number);
end for;
end for;
end func; |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Sidef | Sidef | var count = Hash()
var file = File(ARGV[0] \\ '135-0.txt')
file.open_r.each { |line|
line.lc.scan(/[\pL]+/).each { |word|
count{word} := 0 ++
}
}
var top = count.sort_by {|_,v| v }.last(10).flip
top.each { |pair|
say "#{pair.key}\t-> #{pair.value}"
} |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
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
| #Scheme | Scheme |
(import (scheme base)
(scheme write)
(only (srfi 13) string-join string-tokenize))
;; word wrap, using greedy algorithm with minimum lines
(define (simple-word-wrap str width)
(let loop ((words (string-tokenize str))
(line-length 0)
(line '())
(lines '()))
(cond ((null? words)
(reverse (cons (reverse line) lines)))
((> (+ line-length (string-length (car words)))
width)
(if (null? line)
(loop (cdr words) ; case where word exceeds line length
0
'()
(cons (list (car words)) lines))
(loop words ; word must go to next line, so finish current line
0
'()
(cons (reverse line) lines))))
(else
(loop (cdr words) ; else, add word to current line
(+ 1 line-length (string-length (car words)))
(cons (car words) line)
lines)))))
;; run examples - text from RnRS report
(define *text* "Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible enough to support most of the major programming paradigms in use today.")
(define (show-para algorithm width)
(display (make-string width #\-)) (newline)
(for-each (lambda (line) (display (string-join line " ")) (newline))
(algorithm *text* width)))
(show-para simple-word-wrap 50)
(show-para simple-word-wrap 60)
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Processing | Processing | boolean[] doors = new boolean[100];
void setup() {
for (int i = 0; i < 100; i++) {
doors[i] = false;
}
for (int i = 1; i < 100; i++) {
for (int j = 0; j < 100; j += i) {
doors[j] = !doors[j];
}
}
println("Open:");
for (int i = 1; i < 100; i++) {
if (doors[i]) {
println(i);
}
}
exit();
} |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "gethttp.s7i";
const proc: main is func
local
var string: pageWithTime is "";
var integer: posOfUTC is 0;
var integer: posOfBR is 0;
var string: timeStri is "";
begin
pageWithTime := getHttp("tycho.usno.navy.mil/cgi-bin/timer.pl");
posOfUTC := pos(pageWithTime, "UTC");
if posOfUTC <> 0 then
posOfBR := rpos(pageWithTime, "<BR>", posOfUTC);
if posOfBR <> 0 then
timeStri := pageWithTime[posOfBR + 4 .. pred(posOfUTC)];
writeln(timeStri);
end if;
end if;
end func; |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
| #Sidef | Sidef | var ua = frequire('LWP::Simple');
var url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl';
var match = /<BR>(.+? UTC)/.match(ua.get(url));
say match[0] if match; |
http://rosettacode.org/wiki/Word_frequency | Word frequency | Task
Given a text file and an integer n, print/display the n most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
A word is a sequence of one or more contiguous letters.
You are free to define what a letter is.
Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
You may treat a compound word like well-dressed as either one word or two.
The word it's could also be one or two words as you see fit.
You may also choose not to support non US-ASCII characters.
Assume words will not span multiple lines.
Don't worry about normalization of word spelling differences.
Treat color and colour as two distinct words.
Uppercase letters are considered equivalent to their lowercase counterparts.
Words of equal frequency can be listed in any order.
Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Misérables from Project Gutenberg as the text file input and display the top 10 most used words.
History
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
References
McIlroy's program
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
| #Simula | Simula | COMMENT COMPILE WITH
$ cim -m64 word-count.sim
;
BEGIN
COMMENT ----- CLASSES FOR GENERAL USE ;
! ABSTRACT HASH KEY TYPE ;
CLASS HASHKEY;
VIRTUAL:
PROCEDURE HASH IS
INTEGER PROCEDURE HASH;;
PROCEDURE EQUALTO IS
BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;;
BEGIN
END HASHKEY;
! ABSTRACT HASH VALUE TYPE ;
CLASS HASHVAL;
BEGIN
! THERE IS NOTHING REQUIRED FOR THE VALUE TYPE ;
END HASHVAL;
CLASS HASHMAP;
BEGIN
CLASS INNERHASHMAP(N); INTEGER N;
BEGIN
INTEGER PROCEDURE INDEX(K); REF(HASHKEY) K;
BEGIN
INTEGER I;
IF K == NONE THEN
ERROR("HASHMAP.INDEX: NONE IS NOT A VALID KEY");
I := MOD(K.HASH,N);
LOOP:
IF KEYTABLE(I) == NONE OR ELSE KEYTABLE(I).EQUALTO(K) THEN
INDEX := I
ELSE BEGIN
I := IF I+1 = N THEN 0 ELSE I+1;
GO TO LOOP;
END;
END INDEX;
! PUT SOMETHING IN ;
PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
BEGIN
INTEGER I;
IF V == NONE THEN
ERROR("HASHMAP.PUT: NONE IS NOT A VALID VALUE");
I := INDEX(K);
IF KEYTABLE(I) == NONE THEN BEGIN
IF SIZE = N THEN
ERROR("HASHMAP.PUT: TABLE FILLED COMPLETELY");
KEYTABLE(I) :- K;
VALTABLE(I) :- V;
SIZE := SIZE+1;
END ELSE
VALTABLE(I) :- V;
END PUT;
! GET SOMETHING OUT ;
REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
BEGIN
INTEGER I;
IF K == NONE THEN
ERROR("HASHMAP.GET: NONE IS NOT A VALID KEY");
I := INDEX(K);
IF KEYTABLE(I) == NONE THEN
GET :- NONE ! ERROR("HASHMAP.GET: KEY NOT FOUND");
ELSE
GET :- VALTABLE(I);
END GET;
PROCEDURE CLEAR;
BEGIN
INTEGER I;
FOR I := 0 STEP 1 UNTIL N-1 DO BEGIN
KEYTABLE(I) :- NONE;
VALTABLE(I) :- NONE;
END;
SIZE := 0;
END CLEAR;
! DATA MEMBERS OF CLASS HASHMAP ;
REF(HASHKEY) ARRAY KEYTABLE(0:N-1);
REF(HASHVAL) ARRAY VALTABLE(0:N-1);
INTEGER SIZE;
END INNERHASHMAP;
PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
BEGIN
IF IMAP.SIZE >= 0.75 * IMAP.N THEN
BEGIN
COMMENT RESIZE HASHMAP ;
REF(INNERHASHMAP) NEWIMAP;
REF(ITERATOR) IT;
NEWIMAP :- NEW INNERHASHMAP(2 * IMAP.N);
IT :- NEW ITERATOR(THIS HASHMAP);
WHILE IT.MORE DO
BEGIN
REF(HASHKEY) KEY;
KEY :- IT.NEXT;
NEWIMAP.PUT(KEY, IMAP.GET(KEY));
END;
IMAP.CLEAR;
IMAP :- NEWIMAP;
END;
IMAP.PUT(K, V);
END;
REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
GET :- IMAP.GET(K);
PROCEDURE CLEAR;
IMAP.CLEAR;
INTEGER PROCEDURE SIZE;
SIZE := IMAP.SIZE;
REF(INNERHASHMAP) IMAP;
IMAP :- NEW INNERHASHMAP(16);
END HASHMAP;
CLASS ITERATOR(H); REF(HASHMAP) H;
BEGIN
INTEGER POS,KEYCOUNT;
BOOLEAN PROCEDURE MORE;
MORE := KEYCOUNT < H.SIZE;
REF(HASHKEY) PROCEDURE NEXT;
BEGIN
INSPECT H DO
INSPECT IMAP DO
BEGIN
WHILE KEYTABLE(POS) == NONE DO
POS := POS+1;
NEXT :- KEYTABLE(POS);
KEYCOUNT := KEYCOUNT+1;
POS := POS+1;
END;
END NEXT;
END ITERATOR;
COMMENT ----- PROBLEM SPECIFIC CLASSES ;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
BEGIN
INTEGER PROCEDURE HASH;
BEGIN
INTEGER I;
T.SETPOS(1);
WHILE T.MORE DO
I := 31*I+RANK(T.GETCHAR);
HASH := I;
END HASH;
BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;
EQUALTO := T = K QUA TEXTHASHKEY.T;
END TEXTHASHKEY;
HASHVAL CLASS COUNTER;
BEGIN
INTEGER COUNT;
END COUNTER;
REF(INFILE) INF;
REF(HASHMAP) MAP;
REF(TEXTHASHKEY) KEY;
REF(COUNTER) VAL;
REF(ITERATOR) IT;
TEXT LINE, WORD;
INTEGER I, J, MAXCOUNT, LINENO;
INTEGER ARRAY MAXCOUNTS(1:10);
REF(TEXTHASHKEY) ARRAY MAXWORDS(1:10);
WORD :- BLANKS(1000);
MAP :- NEW HASHMAP;
COMMENT MAP WORDS TO COUNTERS ;
INF :- NEW INFILE("135-0.txt");
INF.OPEN(BLANKS(4096));
WHILE NOT INF.LASTITEM DO
BEGIN
BOOLEAN INWORD;
PROCEDURE SAVE;
BEGIN
IF WORD.POS > 1 THEN
BEGIN
KEY :- NEW TEXTHASHKEY(WORD.SUB(1, WORD.POS - 1));
VAL :- MAP.GET(KEY);
IF VAL == NONE THEN
BEGIN
VAL :- NEW COUNTER;
MAP.PUT(KEY, VAL);
END;
VAL.COUNT := VAL.COUNT + 1;
WORD := " ";
WORD.SETPOS(1);
END;
END SAVE;
LINENO := LINENO + 1;
LINE :- COPY(INF.IMAGE).STRIP; INF.INIMAGE;
COMMENT SEARCH WORDS IN LINE ;
COMMENT A WORD IS ANY SEQUENCE OF LETTERS ;
INWORD := FALSE;
LINE.SETPOS(1);
WHILE LINE.MORE DO
BEGIN
CHARACTER CH;
CH := LINE.GETCHAR;
IF CH >= 'a' AND CH <= 'z' THEN
CH := CHAR(RANK(CH) - RANK('a') + RANK('A'));
IF CH >= 'A' AND CH <= 'Z' THEN
BEGIN
IF NOT INWORD THEN
BEGIN
SAVE;
INWORD := TRUE;
END;
WORD.PUTCHAR(CH);
END ELSE
BEGIN
IF INWORD THEN
BEGIN
SAVE;
INWORD := FALSE;
END;
END;
END;
SAVE; COMMENT LAST WORD ;
END;
INF.CLOSE;
COMMENT FIND 10 MOST COMMON WORDS ;
IT :- NEW ITERATOR(MAP);
WHILE IT.MORE DO
BEGIN
KEY :- IT.NEXT;
VAL :- MAP.GET(KEY);
FOR I := 1 STEP 1 UNTIL 10 DO
BEGIN
IF VAL.COUNT >= MAXCOUNTS(I) THEN
BEGIN
FOR J := 10 STEP -1 UNTIL I + 1 DO
BEGIN
MAXCOUNTS(J) := MAXCOUNTS(J - 1);
MAXWORDS(J) :- MAXWORDS(J - 1);
END;
MAXCOUNTS(I) := VAL.COUNT;
MAXWORDS(I) :- KEY;
GO TO BREAK;
END;
END;
BREAK:
END;
COMMENT OUTPUT 10 MOST COMMON WORDS ;
FOR I := 1 STEP 1 UNTIL 10 DO
BEGIN
IF MAXWORDS(I) =/= NONE THEN
BEGIN
OUTINT(MAXCOUNTS(I), 10);
OUTTEXT(" ");
OUTTEXT(MAXWORDS(I) QUA TEXTHASHKEY.T);
OUTIMAGE;
END;
END;
END
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.