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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | string="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[textWidth_,spaceWidth_,string_]:=Module[{start,spaceLeft,masterString},
spaceLeft=textWidth;
start=1;
masterString={};
Do[
If[i+1>Length@StringSplit@string
,
p=StringSplit[string][[start;;i]];
AppendTo[masterString,{StringJoin@@Riffle[p,StringJoin@ConstantArray[" ",spaceWidth]]}]
,
If[StringLength[StringSplit@string][[i+1]]+spaceWidth>spaceLeft
,
spaceLeft=textWidth-StringLength[StringSplit@string][[i]];
start=i;
AppendTo[masterString,{StringJoin@@Riffle[p,StringJoin@ConstantArray[" ",spaceWidth]]}]
,
spaceLeft-=StringLength[StringSplit@string][[i]];
spaceLeft-=spaceWidth;
p=StringSplit[string][[start;;i]]
]
]
,
{i,1,Length@StringSplit@string}
];
StringJoin@@Riffle[masterString,"\n"]
]; |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Wren | Wren | var escapes = [
["&" , "&"], // must do this one first
["\"", """],
["'" , "'"],
["<" , "<"],
[">" , ">"]
]
var xmlEscape = Fn.new { |s|
for (esc in escapes) s = s.replace(esc[0], esc[1])
return s
}
var xmlDoc = Fn.new { |names, remarks|
var xml = "<CharacterRemarks>\n"
for (i in 0...names.count) {
var name = xmlEscape.call(names[i])
var remark = xmlEscape.call(remarks[i])
xml = xml + " <Character name=\"%(name)\">%(remark)</Character>\n"
}
xml = xml + "</CharacterRemarks>"
System.print(xml)
}
var names = ["April", "Tam O'Shanter", "Emily"]
var remarks = [
"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"
]
xmlDoc.call(names, remarks) |
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
| #Raku | Raku | use XML;
my $xml = from-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>';
say .<Name> for $xml.nodes.grep(/Student/) |
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.
| #Perl | Perl | my @doors;
for my $pass (1 .. 100) {
for (1 .. 100) {
if (0 == $_ % $pass) {
$doors[$_] = not $doors[$_];
};
};
};
print "Door $_ is ", $doors[$_] ? "open" : "closed", "\n" for 1 .. 100; |
http://rosettacode.org/wiki/Weird_numbers | Weird numbers | In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect).
For example:
12 is not a weird number.
It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12),
but it is semiperfect, e.g.: 6 + 4 + 2 == 12.
70 is a weird number.
It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70),
and there is no subset of proper divisors that sum to 70.
Task
Find and display, here on this page, the first 25 weird numbers.
Related tasks
Abundant, deficient and perfect number classifications
Proper divisors
See also
OEIS: A006037 weird numbers
Wikipedia: weird number
MathWorld: weird number
| #Vlang | Vlang | fn divisors(n int) []int {
mut divs := [1]
mut divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs << i
if i != j {
divs2 << j
}
}
}
for i := divs.len - 1; i >= 0; i-- {
divs2 << divs[i]
}
return divs2
}
fn abundant(n int, divs []int) bool {
mut sum := 0
for div in divs {
sum += div
}
return sum > n
}
fn semiperfect(n int, divs []int) bool {
le := divs.len
if le > 0 {
h := divs[0]
t := divs[1..]
if n < h {
return semiperfect(n, t)
} else {
return n == h || semiperfect(n-h, t) || semiperfect(n, t)
}
} else {
return false
}
}
fn sieve(limit int) []bool {
// false denotes abundant and not semi-perfect.
// Only interested in even numbers >= 2
mut w := []bool{len: limit}
for i := 2; i < limit; i += 2 {
if w[i] {
continue
}
divs := divisors(i)
if !abundant(i, divs) {
w[i] = true
} else if semiperfect(i, divs) {
for j := i; j < limit; j += i {
w[j] = true
}
}
}
return w
}
fn main() {
w := sieve(17000)
mut count := 0
max := 25
println("The first 25 weird numbers are:")
for n := 2; count < max; n += 2 {
if !w[n] {
print("$n ")
count++
}
}
println('')
} |
http://rosettacode.org/wiki/Weird_numbers | Weird numbers | In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect).
For example:
12 is not a weird number.
It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12),
but it is semiperfect, e.g.: 6 + 4 + 2 == 12.
70 is a weird number.
It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70),
and there is no subset of proper divisors that sum to 70.
Task
Find and display, here on this page, the first 25 weird numbers.
Related tasks
Abundant, deficient and perfect number classifications
Proper divisors
See also
OEIS: A006037 weird numbers
Wikipedia: weird number
MathWorld: weird number
| #Wren | Wren | import "/math" for Int, Nums
import "/trait" for Stepped
var semiperfect // recursive
semiperfect = Fn.new { |n, divs|
var le = divs.count
if (le == 0) return false
var h = divs[0]
if (n == h) return true
if (le == 1) return false
var t = divs[1..-1]
if (n < h) return semiperfect.call(n, t)
return semiperfect.call(n-h, t) || semiperfect.call(n, t)
}
var sieve = Fn.new { |limit|
// 'false' denotes abundant and not semi-perfect.
// Only interested in even numbers >= 2
var w = List.filled(limit, false)
for (j in Stepped.new(6...limit, 6)) w[j] = true // eliminate multiples of 3
for (i in Stepped.new(2...limit, 2)) {
if (!w[i]) {
var divs = Int.properDivisors(i)
var sum = Nums.sum(divs)
if (sum <= i) {
w[i] = true
} else if (semiperfect.call(sum-i, divs)) {
for (j in Stepped.new(i...limit, i)) w[j] = true
}
}
}
return w
}
var start = System.clock
var limit = 16313
var w = sieve.call(limit)
var count = 0
var max = 25
System.print("The first 25 weird numbers are:")
var n = 2
while (count < max) {
if (!w[n]) {
System.write("%(n) ")
count = count + 1
}
n = n + 2
}
System.print()
System.print("\nTook %(((System.clock-start)*1000).round) milliseconds") |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
mapfile -t name <<EOF
Aimhacks
EOF
main() {
banner3d_1 "${name[@]}"
echo
banner3d_2 "${name[@]}"
echo
banner3d_3 "${name[@]}"
}
space() {
local -i n i
(( n=$1 )) || n=1
if (( n < 1 )); then n=1; fi
for ((i=0; i<n; ++i)); do
printf ' '
done
printf '\n'
}
banner3d_1() {
local txt i
mapfile -t txt < <(printf '%s\n' "$@" | sed -e 's,#,__/,g' -e 's/ / /g')
for i in "${!txt[@]}"; do
printf '%s%s\n' "$(space $(( ${#txt[@]} - i )))" "${txt[i]}"
done
}
banner3d_2() {
local txt i line line2
mapfile -t txt < <(printf '%s \n' "$@")
for i in "${!txt[@]}"; do
line=${txt[i]}
line2=$(printf '%s%s' "$(space $(( 2 * (${#txt[@]} - i) )))" "$(sed -e 's, , ,g' -e 's,#,///,g' -e 's,/ ,/\\,g' <<<"$line")")
printf '%s\n%s\n' "$line2" "$(tr '/\\' '\\/' <<<"$line2")"
done
}
banner3d_3() {
# hard-coded fancy one
cat <<'EOF'
______________ ___________ ___________ ____ ____␣
/ /\ / |\ /| \ |\ \ |\ \
/_____________/ /| /___________|| ||___________\| \___\ | \___\␣
| \ / |/ \ / | | | | | |
| ________ | | ________ | | _________| | | | | |
| | |___| | | | |____| | | |_______ | | |____| | |
| | / | | /| | / | | | | \ | | | \ | |
| |/_____| |/ | |/_____| | | |________\| | |______\| |
| / /| | | \ | |
| ______ \ / | _______ | \_________ | | ________ |
| | |___| | | | | | | _________/| | | | | | |
| | / | | | | | | | | || | | | | | |
| |/_____| | /| | | | | |_________|/ | | | \ | |
| |/ | | | | | | | | | \| |
|_____________/ |___|/ |___| |_____________/ \|___| |___|
EOF
}
main "$@"
|
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++.
| #Julia | Julia | using Requests, Printf
function getusnotime()
const url = "http://tycho.usno.navy.mil/timer.pl"
s = try
get(url)
catch err
@sprintf "get(%s)\n => %s" url err
end
isa(s, Requests.Response) || return (s, false)
t = match(r"(?<=<BR>)(.*?UTC)", readstring(s))
isa(t, RegexMatch) || return (@sprintf("raw html:\n %s", readstring(s)), false)
return (t.match, true)
end
(t, issuccess) = getusnotime();
if issuccess
println("The USNO time is ", t)
else
println("Failed to fetch UNSO time:\n", t)
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++.
| #Kotlin | Kotlin | // version 1.1.3
import java.net.URL
import java.io.InputStreamReader
import java.util.Scanner
fun main(args: Array<String>) {
val url = URL("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
val isr = InputStreamReader(url.openStream())
val sc = Scanner(isr)
while (sc.hasNextLine()) {
val line = sc.nextLine()
if ("UTC" in line) {
println(line.drop(4).take(17))
break
}
}
sc.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
| #KAP | KAP | ∇ stats (file) {
content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file
sorted ← (⍋⊇⊢) content
selection ← 1,2≢/sorted
words ← selection / sorted
{⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection
} |
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
| #Kotlin | Kotlin | // version 1.1.3
import java.io.File
fun main(args: Array<String>) {
val text = File("135-0.txt").readText().toLowerCase()
val r = Regex("""\p{javaLowerCase}+""")
val matches = r.findAll(text)
val wordGroups = matches.map { it.value }
.groupBy { it }
.map { Pair(it.key, it.value.size) }
.sortedByDescending { it.second }
.take(10)
println("Rank Word Frequency")
println("==== ==== =========")
var rank = 1
for ((word, freq) in wordGroups)
System.out.printf("%2d %-4s %5d\n", rank++, word, freq)
} |
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.
| #Oz | Oz | declare
Rules =
[rule(& & )
rule(&H &t)
rule(&t &.)
rule(&. &H when:fun {$ Neighbours}
fun {IsHead X} X == &H end
Hs = {Filter Neighbours IsHead}
Len = {Length Hs}
in
Len == 1 orelse Len == 2
end)
rule(&. &.)]
Init = ["tH........."
". . "
" ... "
". . "
"Ht.. ......"]
MaxGen = 100
%% G(i) -> G(i+1)
fun {Evolve Gi}
fun {Get X#Y}
Row = {CondSelect Gi Y unit}
in
{CondSelect Row X & } %% cells beyond boundaries are empty
end
fun {GetNeighbors X Y}
{Map [X-1#Y-1 X#Y-1 X+1#Y-1
X-1#Y X+1#Y
X-1#Y+1 X#Y+1 X+1#Y+1]
Get}
end
in
{Record.mapInd Gi
fun {$ Y Row}
{Record.mapInd Row
fun {$ X C}
for Rule in Rules return:Return do
if C == Rule.1 then
When = {CondSelect Rule when {Const true}}
in
if {When {GetNeighbors X Y}} then
{Return Rule.2}
end
end
end
end}
end}
end
%% Create an arena from a list of strings.
fun {ReadArena LinesList}
{List.toTuple '#'
{Map LinesList
fun {$ Line}
{List.toTuple row Line}
end}}
end
%% Converts an arena to a virtual string
fun {ShowArena G}
{Record.map G
fun {$ L} {Record.toList L}#"\n" end}
end
%% helpers
fun lazy {Iterate F V} V|{Iterate F {F V}} end
fun {Const X} fun {$ _} X end end
%% prepare GUI
[QTk]={Module.link ["x-oz://system/wp/QTk.ozf"]}
GenDisplay
Field
GUI = td(label(handle:GenDisplay)
label(handle:Field font:{QTk.newFont font(family:'Courier')})
)
{{QTk.build GUI} show}
G0 = {ReadArena Init}
Gn = {Iterate Evolve G0}
in
for
Gi in Gn
I in 0..MaxGen
do
{GenDisplay set(text:"Gen. "#I)}
{Field set(text:{ShowArena Gi})}
{Delay 500}
end |
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.
| #Prolog | Prolog | ?- new(D, window('Prolog Window')), send(D, open). |
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.
| #PureBasic | PureBasic | Define MyWin.i, Event.i
MyWin = OpenWindow(#PB_Any, 412, 172, 402, 94, "PureBasic")
; Event loop
Repeat
Event = WaitWindowEvent()
Select Event
Case #PB_Event_Gadget
; Handle any gadget events here
Case #PB_Event_CloseWindow
Break
EndSelect
ForEver |
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.
| #Python | Python | import Tkinter
w = Tkinter.Tk()
w.mainloop() |
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
| #MiniScript | MiniScript | str = "one two three four five six seven eight nine ten eleven!"
width = 15
words = str.split
pos = 0
line = ""
for word in words
pos = pos + word.len + 1
if pos <= width then
line = line + word + " "
else
print line[:-1]
line = word + " "
pos = word.len
end if
end for
print line[:-1] |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
@see http://en.wikipedia.org/wiki/Word_wrap#Minimum_length
SpaceLeft := LineWidth
for each Word in Text
if (Width(Word) + SpaceWidth) > SpaceLeft
insert line break before Word in Text
SpaceLeft := LineWidth - Width(Word)
else
SpaceLeft := SpaceLeft - (Width(Word) + SpaceWidth)
*/
method wordWrap(text, lineWidth = 80) public static
if lineWidth > 0 then do
NL = '\n'
SP = ' '
wrapped = ''
spaceWidth = SP.length()
spaceLeft = lineWidth
loop w_ = 1 to text.words()
nextWord = text.word(w_)
if (nextWord.length() + spaceWidth) > spaceLeft then do
wrapped = wrapped || NL || nextWord
spaceLeft = lineWidth - nextWord.length()
end
else do
wrapped = wrapped || SP || nextWord
spaceLeft = spaceLeft - (nextWord.length() + spaceWidth)
end
end w_
end
else do
wrapped = text
end
return wrapped.strip() -- clean w/s from front & back
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
parse arg lineLen .
if lineLen = '' then lineLen = 80
text = getText()
wrappedLines = wordWrap(text, lineLen)
say 'Wrapping text at' lineLen 'characters'
say ('....+....|'.copies((lineLen + 9) % 10)).left(lineLen)
say wrappedLines
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getText() public static
-- ....+....|....+....|....+....|....+....|....+....|....+....|
speech01 = -
'She should have died hereafter;' -
'There would have been a time for such a word.' -
'Tomorrow, and tomorrow, and tomorrow,' -
'Creeps in this petty pace from day to day,' -
'To the last syllable of recorded time;' -
'And all our yesterdays have lighted fools' -
'The way to dusty death. Out, out, brief candle!' -
'Life''s but a walking shadow, a poor player' -
'That struts and frets his hour upon the stage' -
'And then is heard no more. It is a tale' -
'Told by an idiot, full of sound and fury' -
'Signifying nothing.' -
'' -
'—-Macbeth (Act 5, Scene 5, lines 17-28)' -
''
return speech01
|
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #XPL0 | XPL0 | code ChOut=8, CrLf=9, Text=12;
string 0; \use zero-terminated strings
proc XmlOut(S); \Output string in XML format
char S;
repeat case S(0) of \character entity substitutions
^<: Text(0, "<");
^>: Text(0, ">");
^&: Text(0, "&");
^": Text(0, """);
^': Text(0, "'")
other ChOut(0, S(0));
S:= S+1;
until S(0) = 0;
int Name, Remark, I;
[Name:= ["April", "Tam O'Shanter", "Emily"];
Remark:= ["Bubbly: I'm > Tam and <= Emily",
"Burns: ^"When chapman billies leave the street ...^"",
"Short & shrift"];
Text(0, "<CharacterRemarks>"); CrLf(0);
for I:= 0 to 3-1 do
[Text(0, " <Character name=^"");
XmlOut(Name(I));
Text(0, "^">");
XmlOut(Remark(I));
Text(0, "</Character>"); CrLf(0);
];
Text(0, "</CharacterRemarks>"); CrLf(0);
] |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #XQuery | XQuery |
let $names := ("April","Tam O'Shanter","Emily")
let $remarks := ("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."',"Short & shrift")
return element CharacterRemarks {
for $name at $count in $names
return element Character {
attribute name { $name }
,text { $remarks[$count] }
}
}
|
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
| #Rascal | Rascal | import lang::xml::DOM;
public void getNames(loc a){
D = parseXMLDOM(readFile(a));
visit(D){
case element(_,"Student",[_*,attribute(_,"Name", x),_*]): println(x);
};
} |
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
| #REBOL | REBOL | rebol [
Title: "XML Reading"
URL: http://rosettacode.org/wiki/XML_Reading
]
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>
}
; REBOL has a simple built-in XML parser. It's not terribly fancy, but
; it's easy to use. It converts the XML into a nested list of blocks
; which can be accessed using standard REBOL path operators. The only
; annoying part (in this case) is that it does try to preserve
; whitespace, so some of the parsed elements are just things like line
; endings and whatnot, which I need to ignore.
; Once I have drilled down to the individual student records, I can
; just use the standard REBOL 'select' to locate the requested
; property.
data: parse-xml xml
students: data/3/1/3 ; Drill down to student records.
foreach student students [
if block! = type? student [ ; Ignore whitespace elements.
print select student/2 "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.
| #Perl5i | Perl5i |
use perl5i::2;
package doors {
use perl5i::2;
use Const::Fast;
const my $OPEN => 1;
const my $CLOSED => 0;
# ----------------------------------------
# Constructor: door->new( @args );
# input: N - how many doors?
# returns: door object
#
method new($class: @args ) {
my $self = bless {}, $class;
$self->_init( @args );
return $self;
}
# ----------------------------------------
# class initializer.
# input: how many doors?
# sets N, creates N+1 doors ( door zero is not used ).
#
method _init( $N ) {
$self->{N} = $N;
$self->{doors} = [ ($CLOSED) x ($N+1) ];
}
# ----------------------------------------
# $self->toggle( $door_number );
# input: number of door to toggle.
# OPEN a CLOSED door; CLOSE an OPEN door.
#
method toggle( $which ) {
$self->{doors}[$which] = ( $self->{doors}[$which] == $OPEN
? $CLOSED
: $OPEN
);
}
# ----------------------------------------
# $self->toggle_n( $cycle );
# input: number.
# Toggle doors 0, $cycle, 2 * $cycle, 3 * $cycle, .. $self->{N}
#
method toggle_n( $n ) {
$self->toggle($_)
for map { $n * $_ }
( 1 .. int( $self->{N} / $n) );
}
# ----------------------------------------
# $self->toggle_all();
# Toggle every door, then every other door, every third door, ...
#
method toggle_all() {
$self->toggle_n( $_ ) for ( 1 .. $self->{N} );
}
# ----------------------------------------
# $self->print_open();
# Print list of which doors are open.
#
method print_open() {
say join ', ', grep { $self->{doors}[$_] == $OPEN } ( 1 ... $self->{N} );
}
}
# ----------------------------------------------------------------------
# Main Thread
#
my $doors = doors->new(100);
$doors->toggle_all();
$doors->print_open();
|
http://rosettacode.org/wiki/Weird_numbers | Weird numbers | In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect).
For example:
12 is not a weird number.
It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12),
but it is semiperfect, e.g.: 6 + 4 + 2 == 12.
70 is a weird number.
It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70),
and there is no subset of proper divisors that sum to 70.
Task
Find and display, here on this page, the first 25 weird numbers.
Related tasks
Abundant, deficient and perfect number classifications
Proper divisors
See also
OEIS: A006037 weird numbers
Wikipedia: weird number
MathWorld: weird number
| #zkl | zkl | fcn properDivs(n){
if(n==1) return(T);
( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
.pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })
}
fcn abundant(n,divs){ divs.sum(0) > n }
fcn semiperfect(n,divs){
if(divs){
h,t := divs[0], divs[1,*];
if(n<h) return(semiperfect(n,t));
return((n==h) or semiperfect(n - h, t) or semiperfect(n, t));
}
False
}
fcn sieve(limit){
// False denotes abundant and not semi-perfect.
// Only interested in even numbers >= 2
w:=List.createLong(limit,False);
foreach i in ([2..limit - 1, 2]){
if(w[i]) continue;
divs:=properDivs(i);
if(not abundant(i,divs)) w[i]=True;
else if(semiperfect(i,divs))
{ foreach j in ([i..limit - 1, i]){ w[j]=True; } }
}
w
} |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Console.WriteLine(" ___ ___ ___ ________ ___ ___ ________ ___ ________ ________ ________ ___ ________ ________ _______ _________
|\ \ / /|\ \|\ ____\|\ \|\ \|\ __ \|\ \ |\ __ \|\ __ \|\ ____\|\ \|\ ____\ |\ ___ \|\ ___ \|\___ ___\
\ \ \ / / | \ \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \ \|\ /\ \ \|\ \ \ \___|\ \ \ \ \___| \ \ \\ \ \ \ __/\|___ \ \_|
\ \ \/ / / \ \ \ \_____ \ \ \\\ \ \ __ \ \ \ \ \ __ \ \ __ \ \_____ \ \ \ \ \ \ \ \\ \ \ \ \_|/__ \ \ \
\ \ / / \ \ \|____|\ \ \ \\\ \ \ \ \ \ \ \____ \ \ \|\ \ \ \ \ \|____|\ \ \ \ \ \____ __\ \ \\ \ \ \ \_|\ \ \ \ \
\ \__/ / \ \__\____\_\ \ \_______\ \__\ \__\ \_______\ \ \_______\ \__\ \__\____\_\ \ \__\ \_______\ |\__\ \__\\ \__\ \_______\ \ \__\
\|__|/ \|__|\_________\|_______|\|__|\|__|\|_______| \|_______|\|__|\|__|\_________\|__|\|_______| \|__|\|__| \|__|\|_______| \|__|
\|_________| \|_________|
")
End Sub
End Module |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Wren | Wren | var w = """
____ ____ ____
|\ \ |\ \ |\ \
| \ \ | \ \ | \ \
\ \ \\ / \\ / /|
\ \ \V \V / |
\ \ /\ / /
\ \____/ \____/ /
\ | | /| | /
\|____|/ |____|/
""".split("\n")
var r = """
_______ ____
|\__ \ / \
|| |\ \/ ___\
\|_| \ /|__|
\ \ //
\ \ \
\ \____\
\ | |
\|____|
""".split("\n")
var e = """
___________
/ _____ \
/ /_____\ \
|\ _____/|
| \ /|____|/
\ \ \/_______/\
\ \_____________/|
\ | | |
\|____________|/
""".split("\n")
var n = """
_____ _______
|\__ \/ \
|| |\ __ \
\|_| \ /| \ \
\ \ \/\ \ \
\ \ \ \ \ \
\ \___\ \ \___\
\ | | \| |
\|___| |___|
""".split("\n")
for (i in 0..8) {
System.print("%(w[i]) %(r[i]) %(e[i]) %(n[i])")
} |
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++.
| #Lasso | Lasso | /* have to be used
local(raw_htmlstring = '<TITLE>What time is it?</TITLE>
<H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
<BR>Jul. 27, 22:57:22 UTC Universal Time
<BR>Jul. 27, 06:57:22 PM EDT Eastern Time
<BR>Jul. 27, 05:57:22 PM CDT Central Time
<BR>Jul. 27, 04:57:22 PM MDT Mountain Time
<BR>Jul. 27, 03:57:22 PM PDT Pacific Time
<BR>Jul. 27, 02:57:22 PM AKDT Alaska Time
<BR>Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time
</PRE></H3>
')
*/
// should be used
local(raw_htmlstring = string(include_url('http://tycho.usno.navy.mil/cgi-bin/timer.pl')))
local(
reg_exp = regexp(-find = `<br>(.*?) UTC`, -input = #raw_htmlstring, -ignorecase),
datepart_txt = #reg_exp -> find ? #reg_exp -> matchstring(1) | string
)
#datepart_txt
'<br />'
// added bonus showing how parsed string can be converted to date object
local(mydate = date(#datepart_txt, -format = `MMM'.' dd',' HH:mm:ss`))
#mydate -> format(`YYYY-MM-dd HH:mm:ss`) |
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++.
| #Liberty_BASIC | Liberty BASIC | if DownloadToFile("http://tycho.usno.navy.mil/cgi-bin/timer.pl", DefaultDir$ + "\timer.htm") = 0 then
open DefaultDir$ + "\timer.htm" for input as #f
html$ = lower$(input$(#f, LOF(#f)))
close #f
a= instr( html$, "utc" )-1
print "UTC";mid$( html$, a-9,9)
end if
end
function DownloadToFile(urlfile$, localfile$)
open "URLmon" for dll as #url
calldll #url, "URLDownloadToFileA",_
0 as long,_ 'null
urlfile$ as ptr,_ 'url to download
localfile$ as ptr,_ 'save file name
0 as long,_ 'reserved, must be 0
0 as long,_ 'callback address, can be 0
DownloadToFile as ulong '0=success
close #url
end function |
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
| #Liberty_BASIC | Liberty BASIC | dim words$(100000,2)'words$(a,1)=the word, words$(a,2)=the count
dim lines$(150000)
open "135-0.txt" for input as #txt
while EOF(#txt)=0 and total < 150000
input #txt, lines$(total)
total=total+1
wend
for a = 1 to total
token$ = "?"
index=0
new=0
while token$ <> ""
new=0
index = index + 1
token$ = lower$(word$(lines$(a),index))
token$=replstr$(token$,".","")
token$=replstr$(token$,",","")
token$=replstr$(token$,";","")
token$=replstr$(token$,"!","")
token$=replstr$(token$,"?","")
token$=replstr$(token$,"-","")
token$=replstr$(token$,"_","")
token$=replstr$(token$,"~","")
token$=replstr$(token$,"+","")
token$=replstr$(token$,"0","")
token$=replstr$(token$,"1","")
token$=replstr$(token$,"2","")
token$=replstr$(token$,"3","")
token$=replstr$(token$,"4","")
token$=replstr$(token$,"5","")
token$=replstr$(token$,"6","")
token$=replstr$(token$,"7","")
token$=replstr$(token$,"8","")
token$=replstr$(token$,"9","")
token$=replstr$(token$,"/","")
token$=replstr$(token$,"<","")
token$=replstr$(token$,">","")
token$=replstr$(token$,":","")
for b = 1 to newwordcount
if words$(b,1)=token$ then
num=val(words$(b,2))+1
num$=str$(num)
if len(num$)=1 then num$="0000"+num$
if len(num$)=2 then num$="000"+num$
if len(num$)=3 then num$="00"+num$
if len(num$)=4 then num$="0"+num$
words$(b,2)=num$
new=1
exit for
end if
next b
if new<>1 then newwordcount=newwordcount+1:words$(newwordcount,1)=token$:words$(newwordcount,2)="00001":print newwordcount;" ";token$
wend
next a
print
sort words$(), 1, newwordcount, 2
print "Count Word"
print "===== ================="
for a = newwordcount to newwordcount-10 step -1
print words$(a,2);" ";words$(a,1)
next a
print "-----------------------"
print newwordcount;" unique words found."
print "End of program"
close #txt
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.
| #PARI.2FGP | PARI/GP | \\ 0 = conductor, 1 = tail, 2 = head, 3 = empty
wireworldStep(M)={
my(sz=matsize(M),t);
matrix(sz[1],sz[2],x,y,
t=M[x,y];
if(t,
[0,1,3][t]
,
t=sum(i=max(x-1,1),min(x+1,sz[1]),
sum(j=max(y-1,1),min(y+1,sz[2]),
M[i,j]==2
)
);
if(t==1|t==2,2,3)
)
)
};
animate(M)={
while(1,display(M=wireworldStep(M)))
};
display(M)={
my(sz=matsize(M),t);
for(i=1,sz[1],
for(j=1,sz[2],
t=M[i,j];
print1([".","t","H"," "][t+1])
);
print
)
};
animate(read("wireworld.gp")) |
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.
| #R | R |
win <- tktoplevel()
|
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.
| #Racket | Racket |
#lang racket/gui
(send (new frame%
[label "New Window"]
[width 100] [height 100])
show #t)
|
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.
| #Raku | Raku | use GTK::Simple;
use GTK::Simple::App;
my GTK::Simple::App $app .= new(title => 'Simple GTK Window');
$app.size-request(250, 100);
$app.set-content(
GTK::Simple::VBox.new(
my $button = GTK::Simple::Button.new(label => 'Exit'),
)
);
$app.border-width = 40;
$button.clicked.tap: { $app.exit }
$app.run; |
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
| #Nim | Nim | import std/wordwrap
let txt = "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."
echo txt.wrapWords()
echo ""
echo txt.wrapWords(45)
|
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
| #OCaml | OCaml | #load "str.cma"
let txt = "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."
let () =
let line_width = int_of_string Sys.argv.(1) in
let words = Str.split (Str.regexp "[ \n]+") txt in
let buf = Buffer.create 10 in
let _ =
List.fold_left (fun (width, sep) word ->
let wlen = String.length word in
let len = width + wlen + 1 in
if len > line_width then
begin
Buffer.add_char buf '\n';
Buffer.add_string buf word;
(wlen, " ")
end else begin
Buffer.add_string buf sep;
Buffer.add_string buf word;
(len, " ")
end
) (0, "") words
in
print_endline (Buffer.contents buf) |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #Yabasic | Yabasic | sign$ = "<,<,>,>,&,&"
dim sign$(1)
long = token(sign$, sign$(), ",")
sub substitute_all$(s$)
local i
for i = 1 to long step 2
if s$ = sign$(i) return sign$(i + 1)
next i
return s$
end sub
sub xmlquote_all$(s$)
local i, res$
for i = 1 to len(s$)
res$ = res$ + substitute_all$(mid$(s$, i, 1))
next i
return res$
end sub
sub xml_CharacterRemarks$(datos$())
local res$, i, long
long = arraysize(datos$(), 1)
res$ = "<CharacterRemarks>\n"
for i = 1 to long
res$ = res$ + " <CharacterName=\"" + xmlquote_all$(datos$(i, 1)) + "\">" + xmlquote_all$(datos$(i, 2)) + "</Character>\n"
next i
return res$ + "</CharacterRemarks>\n"
end sub
data "April", "Bubbly: I'm > Tam and <= Emily"
data "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""
data "Emily", "Short & shrift"
dim testset$(3, 2)
for i = 1 to 3
read testset$(i, 1), testset$(i, 2)
next i
print xml_CharacterRemarks$(testset$()) |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.
Note: the example is chosen to show correct escaping of XML strings.
Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.
Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).
Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
| #zkl | zkl | fcn xmlEscape(text){
text.replace(" &"," &") .replace(" \""," "")
.replace(" '"," '") .replace(" <"," <") .replace(" >"," >")
}
fcn toXML(as,bs){
xml:=Sink("<CharacterRemarks>\n");
as.zipWith('wrap(a,b){
xml.write(" <Character name=\"",xmlEscape(a),"\">",
xmlEscape(b),"</Character>\n");
},bs);
xml.write("</CharacterRemarks>\n").close();
}
toXML(T("April", "Tam O'Shanter", "Emily"),
T("Bubbly: I'm > Tam and <= Emily",
0'|Burns: "When chapman billies leave the street ..."|,
"Short & shrift"))
.print(); |
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
| #REXX | REXX | /*REXX program extracts student names from an XML string(s). */
g.=
g.1 = '<Students> '
g.2 = ' <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> '
g.3 = ' <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> '
g.4 = ' <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> '
g.5 = ' <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> '
g.6 = ' <Pet Type="dog" Name="Rover" /> '
g.7 = ' </Student> '
g.8 = ' <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" /> '
g.9 = '</Students> '
do j=1 while g.j\==''
g.j=space(g.j)
parse var g.j 'Name="' studname '"'
if studname\=='' then say studname
end /*j*/ /*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.
| #Phix | Phix | sequence doors = repeat(false,100)
for i=1 to 100 do
for j=i to 100 by i do
doors[j] = not doors[j]
end for
end for
for i=1 to 100 do
if doors[i] == true then
printf(1,"Door #%d is open.\n", i)
end if
end for
|
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #XPL0 | XPL0 | include c:\cxpl\codes;
proc DrawBlock(X, Y);
int X, Y;
[Cursor(X+1, Y); Text(0, "///\");
Cursor(X, Y+1); Text(0,"/// \");
Cursor(X, Y+2); Text(0,"\\\ /");
Cursor(X+1, Y+3); Text(0, "\\\/");
];
int Data, D, X, Y;
[ChOut(0, $C); \form feed, clears screen
Data:= [%1000100011110000100000001110,
%1000100010001000100000010001,
%0101000010001000100000010011,
%0010000011110000100000010101,
%0101000010000000100000011001,
%1000100010000000100000010001,
%1000100010000000111110001110];
for Y:= 0 to 6 do
[D:= Data(Y);
for X:= 0 to 27 do
[if D&1<<27 then DrawBlock(X*2+(6-Y)*2, Y*2);
D:= D<<1;
];
];
] |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Yabasic | Yabasic |
// Method 1
// r$ = system$("explorer \"http://www.network-science.de/ascii/ascii.php?TEXT=${delegate}&x=23&y=10&FONT=block&RICH=no&FORM=left&STRE=no&WIDT=80&TEXT=Yabasic\"")
// Method 2
// print
// print " _| _| _| _| "
// print " _| _| _|_|_| _|_|_| _|_|_| _|_|_| _|_|_| "
// print " _| _| _| _| _| _| _| _|_| _| _| "
// print " _| _| _| _| _| _| _| _|_| _| _| "
// print " _| _|_|_| _|_|_| _|_|_| _|_|_| _| _|_|_| "
// print
// Method 3
clear screen
dim d$(5)
d$(0) = "X X X XXXX X XXX X XXX "
d$(1) = " X X X X X X X X X X X X"
d$(2) = " X XXXXX XXXX XXXXX XXX X X "
d$(3) = " X X X X X X X X X X X"
d$(4) = " X X X XXXX X X XXXX X XXX "
long = len(d$(0))
sub write(dx, dy, c$)
local x, y
for y = 0 to 4
for x = 0 to long
if mid$(d$(y), x, 1) = "X" print at(x + dx, y + dy) c$
next x
next y
end sub
write(2, 2, "\\")
write(1, 1, "#")
print |
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++.
| #Lua | Lua |
local http = require("socket.http") -- Debian package is 'lua-socket'
function scrapeTime (pageAddress, timeZone)
local page = http.request(pageAddress)
if not page then return "Cannot connect" end
for line in page:gmatch("[^<BR>]*") do
if line:match(timeZone) then
return line:match("%d+:%d+:%d+")
end
end
end
local url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
print(scrapeTime(url, "UTC"))
|
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
| #Lua | Lua |
-- This program takes two optional command line arguments. The first (arg[1])
-- specifies the input file, or defaults to standard input. The second
-- (arg[2]) specifies the number of results to show, or defaults to 10.
-- in freq, each key is a word and each value is its count
local freq = {}
for line in io.lines(arg[1]) do
-- %a stands for any letter
for word in string.gmatch(string.lower(line), "%a+") do
if not freq[word] then
freq[word] = 1
else
freq[word] = freq[word] + 1
end
end
end
-- in array, each entry is an array whose first value is the count and whose
-- second value is the word
local array = {}
for word, count in pairs(freq) do
table.insert(array, {count, word})
end
table.sort(array, function (a, b) return a[1] > b[1] end)
for i = 1, arg[2] or 10 do
io.write(string.format('%7d %s\n', array[i][1] , array[i][2]))
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.
| #Perl | Perl | my @f = ([],(map {chomp;['',( split // ),'']} <>),[]);
for (1 .. 10) {
print join "", map {"@$_\n"} @f;
my @a = ([]);
for my $y (1 .. $#f-1) {
my $r = $f[$y];
my $rr = [''];
for my $x (1 .. $#$r-1) {
my $c = $r->[$x];
push @$rr,
$c eq 'H' ? 't' :
$c eq 't' ? '.' :
$c eq '.' ? (join('', map {"@{$f[$_]}[$x-1 .. $x+1]"=~/H/g} ($y-1 .. $y+1)) =~ /^H{1,2}$/ ? 'H' : '.') :
$c;
}
push @$rr, '';
push @a, $rr;
}
@f = (@a,[]);
} |
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.
| #RapidQ | RapidQ | create form as qform
center
width=500
height=400
end create
form.showModal
|
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.
| #REBOL | REBOL |
view layout [size 100x100]
|
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.
| #Red | Red | >>view []
|
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
| #Ol | Ol |
(define (get-one-word start)
(let loop ((chars #null) (end start))
(let ((char (car end)))
(if (has? (list #\space #\newline) char)
(values (reverse chars) (force (cdr end)))
(loop (cons char chars) (force (cdr end)))))))
(define (get-all-words string)
(let loop ((words #null) (start (str-iter string)))
(let* ((word next (get-one-word start)))
(if (null? next)
(reverse words)
(loop (cons (runes->string word) words) next)))))
(define (get-one-line words n)
(let loop ((line #null) (words words) (i 0))
(let*((word (car words))
(len (string-length word)))
(if (null? (cdr words))
(values (reverse (cons word line)) #null)
(if (> (+ i len) n 1)
(values (reverse line) words)
(loop (cons word line) (cdr words) (+ i len 1)))))))
(define (get-all-lines words n)
(let loop ((lines #null) (words words))
(let* ((line words (get-one-line words n)))
(if (null? words)
(reverse (cons line lines))
(loop (cons line lines) words)))))
(define (hyphenation width string)
(let*((words (get-all-words string))
(lines (get-all-lines words width)))
lines))
|
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
| #Ruby | Ruby | require 'rexml/document'
include REXML
doc = Document.new(File.new("sample.xml"))
# or
# doc = Document.new(xml_string)
# without using xpath
doc.each_recursive do |node|
puts node.attributes["Name"] if node.name == "Student"
end
# using xpath
doc.each_element("*/Student") {|node| puts node.attributes["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.
| #Phixmonti | Phixmonti | 101 var l
0 l repeat
l for
var s
s l s 3 tolist
for
var i
i get not i set
endfor
endfor
l for
var i
i get
if
i print " " print
endif
endfor |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #zkl | zkl | #<<<
"
xxxxxx x x x
x x x x
x x x x
x x x x
xxxxx x x xxxx
"
#<<<<
.replace(" "," ").replace("x","_/").println(); |
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++.
| #M2000_Interpreter | M2000 Interpreter |
Module Web_scraping {
Print "Web scraping"
function GetTime$(a$, what$="UTC") {
document a$ ' change string to document
find a$, what$ ' place data to stack
Read find_pos
if find_pos>0 then
read par_order, par_pos
b$=paragraph$(a$, par_order)
k=instr(b$,">")
if k>0 then if k<par_pos then b$=mid$(b$,k+1) :par_pos-=k
k=rinstr(b$,"<")
if k>0 then if k>par_pos then b$=Left(b$,k-1)
=b$
end if
}
declare msxml2 "MSXML2.XMLHTTP.6.0"
rem print type$(msxml2)="IXMLHTTPRequest"
Url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
try ok {
method msxml2, "Open", "GET", url$, false
method msxml2,"Send"
with msxml2,"responseText" as txt$
Print GetTime$(txt$)
}
If error or not ok then Print Error$
declare msxml2 nothing
}
Web_scraping
|
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++.
| #Maple | Maple | text := URL:-Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl"):
printf(StringTools:-StringSplit(text,"<BR>")[2]); |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | TakeLargest[10]@WordCounts[Import["https://www.gutenberg.org/files/135/135-0.txt"], IgnoreCase->True]//Dataset |
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
| #MATLAB_.2F_Octave | MATLAB / Octave |
function [result,count] = word_frequency()
URL='https://www.gutenberg.org/files/135/135-0.txt';
text=webread(URL);
DELIMITER={' ', ',', ';', ':', '.', '/', '*', '!', '?', '<', '>', '(', ')', '[', ']','{', '}', '&','$','§','"','”','“','-','—','‘','\t','\n','\r'};
words = sort(strsplit(lower(text),DELIMITER));
flag = [find(~strcmp(words(1:end-1),words(2:end))),length(words)];
dwords = words(flag); % get distinct words, and ...
count = diff([0,flag]); % ... the corresponding occurance frequency
[tmp,idx] = sort(-count); % sort according to occurance
result = dwords(idx);
count = count(idx);
for k = 1:10,
fprintf(1,'%d\t%s\n',count(k),result{k})
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.
| #Phix | Phix | --
-- demo\rosetta\Wireworld.exw
-- ==========================
--
-- Invoke with file to read, or let it read the one below (if compiled assumes source is in the same directory)
--
-- Note that tabs in description files are not supported - where necessary spaces can be replaced with _ chars.
-- (tab chars in text files should technically always represent (to-next) 8 spaces, but not many editors respect
-- that, and instead assume the file will only ever be read by the same program/with matching settings. </rant>)
-- (see also demo\edix\src\tabs.e\ExpandTabs() for what you'd need if you knew what the tab chars really meant.)
--
with javascript_semantics
constant default_description = """
tH.........
.___.
___...
.___.
Ht.. ......
"""
sequence lines, counts
integer longest
function valid_line(string line, integer l=0)
if length(line)=0 then return 0 end if
for i=1 to length(line) do
integer ch = line[i]
if not find(ch," _.tH") then
if l and ch='\t' then
-- as above
printf(1,"error: tab char on line %d\n",{l})
{} = wait_key()
abort(0)
end if
return 0
end if
end for
return 1
end function
procedure load_desc()
sequence text
if platform()=JS then
text = split(default_description,"\n")
else
string filename = substitute(command_line()[$],".exe",".exw")
integer fn = open(filename,"r")
if fn=-1 then
printf(1,"error opening %s\n",{filename})
{} = wait_key()
abort(0)
end if
text = get_text(fn,GT_LF_STRIPPED)
close(fn)
end if
lines = {}
for i=1 to length(text) do
string line = text[i]
if valid_line(line) then
lines = {line}
longest = length(line)
for j=i+1 to length(text) do
line = text[j]
if not valid_line(line,j) then exit end if
lines = append(lines,line)
if longest<length(line) then
longest = length(line)
end if
end for
exit
end if
end for
counts = deep_copy(lines)
end procedure
constant dxy = {{-1,-1}, {-1,+0}, {-1,+1},
{+0,-1}, {+0,+1},
{+1,-1}, {+1,+0}, {+1,+1}}
procedure set_counts()
for y=1 to length(lines) do
for x=1 to length(lines[y]) do
if lines[y][x]='.' then
integer count = 0
for k=1 to length(dxy) do
integer {cx,cy} = sq_add({x,y},dxy[k])
if cy>=1 and cy<=length(lines)
and cx>=1 and cx<=length(lines[cy])
and lines[cy][cx]='H' then
count += 1
end if
end for
counts[y][x] = (count=1 or count=2)
end if
end for
end for
end procedure
include pGUI.e
constant title = "Wireworld"
Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
integer dx = floor(w/(longest+2))
integer dy = floor(h/(length(lines)+2))
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
set_counts()
for y=1 to length(lines) do
for x=1 to length(lines[y]) do
integer c = lines[y][x], colour
if find(c," _") then
colour = CD_BLACK
elsif c='.' then
colour = CD_YELLOW
if counts[y][x] then
lines[y][x] = 'H'
end if
elsif c='H' then
colour = CD_BLUE
lines[y][x] = 't'
elsif c='t' then
colour = CD_RED
lines[y][x] = '.'
end if
cdCanvasSetForeground(cddbuffer, colour)
cdCanvasBox(cddbuffer,x*dx,x*dx+dx,h-y*dy,h-(y*dy+dy))
end for
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_BLACK)
return IUP_DEFAULT
end function
procedure main()
load_desc()
IupOpen()
canvas = IupCanvas("RASTERSIZE=300x180")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
timer = IupTimer(Icallback("timer_cb"), 500)
dlg = IupDialog(canvas,`TITLE="%s"`, {title})
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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.
| #Ring | Ring |
Load "guilib.ring"
MyApp = New qApp {
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
show()}
exec()}
|
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.
| #Ruby | Ruby | require 'tk'
window = TkRoot::new()
window::mainloop() |
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.
| #Run_BASIC | Run BASIC | html "Close me!"
button #c, "Close Me", [doExit]
wait
' -----------------------------------------------------------------------------------
' Get outta here. depending on how may layers you are into the window (history level)
' If you are at the top level then close the window
' ----------------------------------------------------------------------------------
[doExit]
html "<script language='javascript' type='text/javascript'>
var a = history.length;
a = a - 1;
window.open('','_parent','');
window.close();
history.go(-a);
</script>"
wait |
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
| #PARI.2FGP | PARI/GP | wrap(s,len)={
my(t="",cur);
s=Vec(s);
for(i=1,#s,
if(s[i]==" ",
if(cur>#t,
print1(" "t);
cur-=#t+1
,
print1("\n"t);
cur=len-#t
);
t=""
,
t=concat(t,s[i])
)
);
if(cur>#t,
print1(" "t)
,
print1("\n"t)
)
};
King="And so let freedom ring from the prodigious hilltops of New Hampshire; let freedom ring from the mighty mountains of New York; let freedom ring from the heightening Alleghenies of Pennsylvania; let freedom ring from the snow-capped Rockies of Colorado; let freedom ring from the curvaceous slopes of California. But not only that: let freedom ring from Stone Mountain of Georgia; let freedom ring from Lookout Mountain of Tennessee; let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring.";
wrap(King, 75)
wrap(King, 50) |
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
| #Run_BASIC | Run BASIC | ' ------------------------------------------------------------------------
'XMLPARSER methods
'#handle ELEMENTCOUNT() - Return the number of child XML elements
'#handle KEY$() - Return the key as a string from an XML expression like <key>value</key>
'#handle VALUE$() - Return the value as a string from an XML expression like <key>value</key>
'#handle VALUEFORKEY$(keyExpr$) - Return the value for the specified tag key in keyExpr$
'#handle #ELEMENT(n) - Return the nth child-element XML element
'#handle #ELEMENT(nameExpr$) - Return the child-element XML element named by nameExpr$
'#handle ATTRIBCOUNT() - Return a count of attribute pairs; <a attrA="abc" attrB="def"> has two pairs
'#handle ATTRIBKEY$(n) - Return the key string of the nth attribute
'#handle ATTRIBVALUE$(n) - Return the value string of the nth attribute
'#handle ATTRIBVALUE$(n$) - Return the value string of the attribute with the key n$, or an empty string if it doesn't exist.
'#handle ISNULL() - Returns zero (or false)
'#handle DEBUG$() - Returns the string "Xmlparser"
' ------------------------------------------------------------------------
' The xml string
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>"
' Creates the xml handler, using the string
xmlparser #spies, xml$
' Uses elementCount() to know how many elements are in betweeb <spies>...</spies>
for count = 1 to #spies elementCount()
' Uses "count" to work through the elements, and assigns the element to the
' handle "#spy"
#spy = #spies #element(count)
' Prints the value, or inner text, of "#spy": Sam, Clover, & Alex
print count;" ";#spy value$();" ->";#spy ATTRIBVALUE$(1)
next count |
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.
| #PHL | PHL | module doors;
extern printf;
@Integer main [
@Array<@Boolean> doors = new @Array<@Boolean>.init(100);
var i = 1;
while (i <= 100) {
var j = i-1;
while (j < 100) {
doors.set(j, doors.get(j)::not);
j = j + i;
}
i = i::inc;
}
i = 0;
while (i < 100) {
printf("%i %s\n", i+1, iif(doors.get(i), "open", "closed"));
i = i::inc;
}
return 0;
] |
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++.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | test = StringSplit[Import["http://tycho.usno.navy.mil/cgi-bin/timer.pl"], "\n"];
Extract[test, Flatten@Position[StringFreeQ[test, "UTC"], False]] |
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++.
| #MATLAB_.2F_Octave | MATLAB / Octave | s = urlread('http://tycho.usno.navy.mil/cgi-bin/timer.pl');
ix = [findstr(s,'<BR>'), length(s)+1];
for k = 2:length(ix)
tok = s(ix(k-1)+4:ix(k)-1);
if findstr(tok,'UTC')
disp(tok);
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
| #Nim | Nim | import tables, strutils, sequtils, httpclient
proc take[T](s: openArray[T], n: int): seq[T] = s[0 ..< min(n, s.len)]
var client = newHttpClient()
var text = client.getContent("https://www.gutenberg.org/files/135/135-0.txt")
var wordFrequencies = text.toLowerAscii.splitWhitespace.toCountTable
wordFrequencies.sort
for (word, count) in toSeq(wordFrequencies.pairs).take(10):
echo alignLeft($count, 8), word |
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.
| #PHP | PHP |
$desc = 'tH.........
. .
........
. .
Ht.. ......
..
tH.... .......
..
..
tH..... ......
..';
$steps = 30;
//fill in the world with the cells
$world = array(array());
$row = 0;
$col = 0;
foreach(str_split($desc) as $i){
switch($i){
case "\n":
$row++;
//if($col > $width) $width = $col;
$col = 0;
$world[] = array();
break;
case '.':
$world[$row][$col] = 1;//conductor
$col++;
break;
case 'H':
$world[$row][$col] = 2;//head
$col++;
break;
case 't':
$world[$row][$col] = 3;//tail
$col++;
break;
default:
$world[$row][$col] = 0;//insulator/air
$col++;
break;
};
};
function draw_world($world){
foreach($world as $rowc){
foreach($rowc as $cell){
switch($cell){
case 0:
echo ' ';
break;
case 1:
echo '.';
break;
case 2:
echo 'H';
break;
case 3:
echo 't';
};
};
echo "\n";
};
//var_export($world);
};
echo "Original world:\n";
draw_world($world);
for($i = 0; $i < $steps; $i++){
$old_world = $world; //backup to look up where was an electron head
foreach($world as $row => &$rowc){
foreach($rowc as $col => &$cell){
switch($cell){
case 2:
$cell = 3;
break;
case 3:
$cell = 1;
break;
case 1:
$neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col] == 2;
if($neigh_heads == 1 || $neigh_heads == 2){
$cell = 2;
};
};
};
unset($cell); //just to be safe
};
unset($rowc); //just to be safe
echo "\nStep " . ($i + 1) . ":\n";
draw_world($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.
| #Rust | Rust | use winit::event::{Event, WindowEvent}; // winit 0.24
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn main() {
let event_loop = EventLoop::new();
let _win = WindowBuilder::new()
.with_title("Window")
.build(&event_loop).unwrap();
event_loop.run(move |ev, _, flow| {
match ev {
Event::WindowEvent {
event: WindowEvent::CloseRequested, ..
} => {
*flow = ControlFlow::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.
| #Scala | Scala | import javax.swing.JFrame
object ShowWindow{
def main(args: Array[String]){
var jf = new JFrame("Hello!")
jf.setSize(800, 600)
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
jf.setVisible(true)
}
} |
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.
| #Scheme | Scheme |
#!r6rs
;; PS-TK example: display simple frame
(import (rnrs)
(lib pstk main) ; change this to refer to your installation of PS/Tk
)
(define tk (tk-start))
(tk/wm 'title tk "PS-Tk Example: Frame")
(tk-event-loop tk)
|
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
| #Perl | Perl | 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/\b\s+/ /g;
$s =~ s/\s*$/\n\n/;
my $_ = $s;
s/\s*(.{1,66})\s/$1\n/g, print;
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print; |
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
| #Rust | Rust | extern crate xml; // provided by the xml-rs crate
use xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};
const DOCUMENT: &str = r#"
<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>
"#;
fn main() -> Result<(), xml::reader::Error> {
let parser = EventReader::new(DOCUMENT.as_bytes());
let tag_name = OwnedName::local("Student");
let attribute_name = OwnedName::local("Name");
for event in parser {
match event? {
XmlEvent::StartElement {
name,
attributes,
..
} if name == tag_name => {
if let Some(attribute) = attributes.iter().find(|&attr| attr.name == attribute_name) {
println!("{}", attribute.value);
}
}
_ => (),
}
}
Ok(())
} |
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
| #Scala | Scala | val students =
<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>
students \ "Student" \\ "@Name" foreach 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.
| #PHP | PHP | <?php
for ($i = 1; $i <= 100; $i++) {
$root = sqrt($i);
$state = ($root == ceil($root)) ? 'open' : 'closed';
echo "Door {$i}: {$state}\n";
}
?> |
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++.
| #Microsoft_Small_Basic | Microsoft Small Basic |
'Entered by AykayayCiti -- Earl L. Montgomery
url_name = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
url_data = Network.GetWebPageContents(url_name)
find = "UTC"
' the length from the UTC to the time is -18 so we need
' to subtract from the UTC position
pos = Text.GetIndexOf(url_data,find)-18
result = Text.GetSubText(url_data,pos,(18+3)) 'plus 3 to add the UTC
TextWindow.WriteLine(result)
'you can eleminate a line of code by putting the
' GetIndexOf insde the GetSubText
'result2 = Text.GetSubText(url_data,Text.GetIndexOf(url_data,find)-18,(18+3))
'TextWindow.WriteLine(result2) |
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++.
| #mIRC_Scripting_Language | mIRC Scripting Language | alias utc {
sockclose UTC
sockopen UTC tycho.usno.navy.mil 80
}
on *:SOCKOPEN:UTC: {
sockwrite -n UTC GET /cgi-bin/timer.pl HTTP/1.1
sockwrite -n UTC Host: tycho.usno.navy.mil
sockwrite UTC $crlf
}
on *:SOCKREAD:UTC: {
sockread %UTC
while ($sockbr) {
if (<BR>*Universal Time iswm %UTC) {
echo -ag $remove(%UTC,<BR>,$chr(9),Universal Time)
unset %UTC
sockclose UTC
return
}
sockread %UTC
}
} |
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
| #Objeck | Objeck | use System.IO.File;
use Collection;
use RegEx;
class Rosetta {
function : Main(args : String[]) ~ Nil {
if(args->Size() <> 1) {
return;
};
input := FileReader->ReadFile(args[0]);
filter := RegEx->New("\\w+");
words := filter->Find(input);
word_counts := StringMap->New();
each(i : words) {
word := words->Get(i)->As(String);
if(word <> Nil & word->Size() > 0) {
word := word->ToLower();
if(word_counts->Has(word)) {
count := word_counts->Find(word)->As(IntHolder);
count->Set(count->Get() + 1);
}
else {
word_counts->Insert(word, IntHolder->New(1));
};
};
};
count_words := IntMap->New();
words := word_counts->GetKeys();
each(i : words) {
word := words->Get(i)->As(String);
count := word_counts->Find(word)->As(IntHolder);
count_words->Insert(count->Get(), word);
};
counts := count_words->GetKeys();
counts->Sort();
index := 1;
"Rank\tWord\tFrequency"->PrintLine();
"====\t====\t===="->PrintLine();
for(i := count_words->Size() - 1; i >= 0; i -= 1;) {
if(count_words->Size() - 10 <= i) {
count := counts->Get(i);
word := count_words->Find(count)->As(String);
"{$index}\t{$word}\t{$count}"->PrintLine();
index += 1;
};
};
}
} |
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.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(let
(Data (in "wire.data" (make (while (line) (link @))))
Grid (grid (length (car Data)) (length Data)) )
(mapc
'((G D) (mapc put G '(val .) D))
Grid
(apply mapcar (flip Data) list) )
(loop
(disp Grid T
'((This) (pack " " (: val) " ")) )
(wait 1000)
(for Col Grid
(for This Col
(case (=: next (: val))
("H" (=: next "t"))
("t" (=: next "."))
("."
(when
(>=
2
(cnt # Count neighbors
'((Dir) (= "H" (get (Dir This) 'val)))
(quote
west east south north
((X) (south (west X)))
((X) (north (west X)))
((X) (south (east X)))
((X) (north (east X))) ) )
1 )
(=: next "H") ) ) ) ) )
(for Col Grid # Update
(for This Col
(=: val (: next)) ) )
(prinl) ) ) |
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.
| #PureBasic | PureBasic | Enumeration
#Empty
#Electron_head
#Electron_tail
#Conductor
EndEnumeration
#Delay=100
#XSize=23
#YSize=12
Procedure Limit(n, min, max)
If n<min
n=min
ElseIf n>max
n=max
EndIf
ProcedureReturn n
EndProcedure
Procedure Moore_neighborhood(Array World(2),x,y)
Protected cnt=0, i, j
For i=Limit(x-1, 0, #XSize) To Limit(x+1, 0, #XSize)
For j=Limit(y-1, 0, #YSize) To Limit(y+1, 0, #YSize)
If World(i,j)=#Electron_head
cnt+1
EndIf
Next
Next
ProcedureReturn cnt
EndProcedure
Procedure PresentWireWorld(Array World(2))
Protected x,y
;ClearConsole()
For y=0 To #YSize
For x=0 To #XSize
ConsoleLocate(x,y)
Select World(x,y)
Case #Electron_head
ConsoleColor(12,0): Print("#")
Case #Electron_tail
ConsoleColor(4,0): Print("#")
Case #Conductor
ConsoleColor(6,0): Print("#")
Default
ConsoleColor(15,0): Print(" ")
EndSelect
Next
PrintN("")
Next
EndProcedure
Procedure UpdateWireWorld(Array World(2))
Dim NewArray(#XSize,#YSize)
Protected i, j
For i=0 To #XSize
For j=0 To #YSize
Select World(i,j)
Case #Electron_head
NewArray(i,j)=#Electron_tail
Case #Electron_tail
NewArray(i,j)=#Conductor
Case #Conductor
Define m=Moore_neighborhood(World(),i,j)
If m=1 Or m=2
NewArray(i,j)=#Electron_head
Else
NewArray(i,j)=#Conductor
EndIf
Default ; e.g. should be Empty
NewArray(i,j)=#Empty
EndSelect
Next
Next
CopyArray(NewArray(),World())
EndProcedure
If OpenConsole()
EnableGraphicalConsole(#True)
ConsoleTitle("XOR() WireWorld")
;- Set up the WireWorld
Dim WW.i(#XSize,#YSize)
Define x, y
Restore StartWW
For y=0 To #YSize
For x=0 To #XSize
Read.i WW(x,y)
Next
Next
;- Start the WireWorld simulation
Repeat
PresentWireWorld(WW())
UpdateWireWorld(WW())
Delay(#Delay)
ForEver
EndIf
DataSection
StartWW:
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,0,3,3,3,3,2,1,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0
Data.i 0,0,0,2,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,3,3,3,3,3
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0
Data.i 0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0
Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0
Data.i 0,0,0,2,3,3,3,3,1,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EndDataSection |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
const proc: main is func
begin
screen(200, 200);
KEYBOARD := GRAPH_KEYBOARD;
ignore(getc(KEYBOARD));
end func; |
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.
| #Sidef | Sidef | var tk = require('Tk');
%s'MainWindow'.new;
tk.MainLoop; |
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.
| #Smalltalk | Smalltalk | SystemWindow new openInWorld. |
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
| #Phix | Phix | string s = substitute("""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.""","\n"," ")
procedure word_wrap(string s, integer maxwidth)
sequence words = split(s)
string line = words[1]
for i=2 to length(words) do
string word = words[i]
if length(line)+length(word)+1>maxwidth then
puts(1,line&"\n")
line = word
else
line &= " "&word
end if
end for
puts(1,line&"\n")
end procedure
word_wrap(s,72)
word_wrap(s,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
| #Sidef | Sidef | require('XML::Simple');
var ref = %S'XML::Simple'.XMLin('<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>');
ref{:Student}.each { say _{: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.
| #Picat | Picat | doors(N) =>
Doors = new_array(N),
foreach(I in 1..N) Doors[I] := 0 end,
foreach(I in 1..N)
foreach(J in I..I..N)
Doors[J] := 1^Doors[J]
end,
if N <= 10 then
print_open(Doors)
end
end,
println(Doors),
print_open(Doors),
nl.
print_open(Doors) => println([I : I in 1..Doors.length, Doors[I] == 1]).
|
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++.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
parse arg full_short .
if 'FULL'.abbrev(full_short.upper(), 1) then
dateFull = isTrue()
else
dateFull = isFalse()
do
timeURL = java.net.URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
conn = timeURL.openConnection()
ibr = BufferedReader(InputStreamReader(conn.getInputStream()))
line = Rexx
loop label readLoop while ibr.ready()
line = ibr.readLine()
if line = null then leave readLoop
line = line.translate(' ', '\t')
if line.wordpos('UTC') > 0 then do
parse line . '>' udatetime 'UTC' . -
0 . '>' . ',' utime 'UTC' .
if dateFull then
say udatetime.strip() 'UTC'
else
say utime.strip()
leave readLoop
end
end readLoop
ibr.close()
catch ex = IOException
ex.printStackTrace()
end
method isTrue() public constant returns boolean
return 1 == 1
method isFalse() public constant returns boolean
return \isTrue()
|
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
| #OCaml | OCaml | let () =
let n =
try int_of_string Sys.argv.(1)
with _ -> 10
in
let ic = open_in "135-0.txt" in
let h = Hashtbl.create 97 in
let w = Str.regexp "[^A-Za-zéèàêâôîûœ]+" in
try
while true do
let line = input_line ic in
let words = Str.split w line in
List.iter (fun word ->
let word = String.lowercase_ascii word in
match Hashtbl.find_opt h word with
| None -> Hashtbl.add h word 1
| Some x -> Hashtbl.replace h word (succ x)
) words
done
with End_of_file ->
close_in ic;
let l = Hashtbl.fold (fun word count acc -> (word, count)::acc) h [] in
let s = List.sort (fun (_, c1) (_, c2) -> compare c2 c1) l in
let r = List.init n (fun i -> List.nth s i) in
List.iter (fun (word, count) ->
Printf.printf "%d %s\n" count word
) r |
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.
| #Python | Python | '''
Wireworld implementation.
'''
from io import StringIO
from collections import namedtuple
from pprint import pprint as pp
import copy
WW = namedtuple('WW', 'world, w, h')
head, tail, conductor, empty = allstates = 'Ht. '
infile = StringIO('''\
tH.........
. .
...
. .
Ht.. ......\
''')
def readfile(f):
'''file > initial world configuration'''
world = [row.rstrip('\r\n') for row in f]
height = len(world)
width = max(len(row) for row in world)
# fill right and frame in empty cells
nonrow = [ " %*s " % (-width, "") ]
world = nonrow + \
[ " %*s " % (-width, row) for row in world ] + \
nonrow
world = [list(row) for row in world]
return WW(world, width, height)
def newcell(currentworld, x, y):
istate = currentworld[y][x]
assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate
if istate == head:
ostate = tail
elif istate == tail:
ostate = conductor
elif istate == empty:
ostate = empty
else: # istate == conductor
n = sum( currentworld[y+dy][x+dx] == head
for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),
(+0,-1), (+0,+1),
(+1,-1), (+1,+0), (+1,+1) ) )
ostate = head if 1 <= n <= 2 else conductor
return ostate
def nextgen(ww):
'compute next generation of wireworld'
world, width, height = ww
newworld = copy.deepcopy(world)
for x in range(1, width+1):
for y in range(1, height+1):
newworld[y][x] = newcell(world, x, y)
return WW(newworld, width, height)
def world2string(ww):
return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )
ww = readfile(infile)
infile.close()
for gen in range(10):
print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww) |
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.
| #Standard_ML | Standard ML |
open XWindows ;
open Motif ;
val showWindow = fn () =>
let
val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 400, XmNheight 300 ] ;
val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ;
val buttn = XmCreateDrawnButton main "stop" [ XmNlabelString "Exit"] ;
val quit = fn (w,c,t) => (XtUnrealizeWidget shell; t) ;
in
(
XtSetCallbacks buttn [ (XmNactivateCallback, quit) ] XmNarmCallback ;
XtManageChildren [buttn];
XtManageChild main;
XtRealizeWidget shell
)
end;
|
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.
| #Tcl | Tcl | package require Tk |
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.
| #TI-89_BASIC | TI-89 BASIC | :Text "Rosetta Code" |
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
72 var long
0 >ps
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh."
split
len for drop
pop swap len ps> + >ps
tps long > if ps> drop len >ps nl endif
print " " print
ps> 1 + >ps
endfor
drop ps> drop
|
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
| #PHP | PHP | <?php
$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day
So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life
Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;
// remove preexisting line breaks
$text = str_replace( PHP_EOL, " " , $text );
echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
|
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
| #Slate | Slate | slate[1]> [ |tree|
tree: (Xml SimpleParser newOn: '<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>') parse.
tree name = 'Students' ifTrue: [(tree children select: #is: `er <- Xml Element)
do: [|:child| child name = 'Student' ifTrue: [inform: (child attributes at: 'Name' ifAbsent: ['Noname'])]]].
] do.
April
Bob
Chad
Dave
Émily
Nil |
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.
| #PicoLisp | PicoLisp | (let Doors (need 100)
(for I 100
(for (D (nth Doors I) D (cdr (nth D I)))
(set D (not (car D))) ) )
(println 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++.
| #Nim | Nim | import httpclient, strutils
var client = newHttpClient()
var res: string
for line in client.getContent("https://rosettacode.org/wiki/Talk:Web_scraping").splitLines:
let k = line.find("UTC")
if k >= 0:
res = line[0..(k - 3)]
let k = res.rfind("</a>")
res = res[(k + 6)..^1]
break
echo if res.len > 0: res else: "No date/time found." |
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++.
| #Objeck | Objeck |
use Net;
use IO;
use Structure;
bundle Default {
class Scrape {
function : Main(args : String[]) ~ Nil {
client := HttpClient->New();
lines := client->Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl", 80);
i := 0;
found := false;
while(found <> true & i < lines->Size()) {
line := lines->Get(i)->As(String);
index := line->Find("UTC");
if(index > -1) {
time := line->SubString(index - 9, 9)->Trim();
time->PrintLine();
found := true;
};
i += 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
| #Perl | Perl | $top = 10;
open $fh, "<", '135-0.txt';
($text = join '', <$fh>) =~ tr/A-Z/a-z/
or die "Can't open '135-0.txt': $!\n";
@matcher = (
qr/[a-z]+/, # simple 7-bit ASCII
qr/\w+/, # word characters with underscore
qr/[a-z0-9]+/, # word characters without underscore
);
for $reg (@matcher) {
print "\nTop $top using regex: " . $reg . "\n";
@matches = $text =~ /$reg/g;
my %words;
for $w (@matches) { $words{$w}++ };
$c = 0;
for $w ( sort { $words{$b} <=> $words{$a} } keys %words ) {
printf "%-7s %6d\n", $w, $words{$w};
last if ++$c >= $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.
| #Racket | Racket |
#lang racket
(require 2htdp/universe)
(require 2htdp/image)
(require racket/fixnum)
; see the forest fire task, from which this is derived...
(define-struct wire-world (width height cells) #:prefab)
(define state:_ 0)
(define state:. 1)
(define state:H 2)
(define state:t 3)
(define (char->state c)
(case c
((#\_ #\space) state:_)
((#\.) state:.)
((#\H) state:H)
((#\t) state:t)))
(define (initial-world l)
(let ((h (length l))
(w (string-length (first l))))
(make-wire-world w h
(for*/fxvector
#:length (* h w)
((row (in-list l))
(cell (in-string row)))
(char->state cell)))))
(define initial-list
'("tH........."
". . "
" ... "
". . "
"Ht.. ......"))
(define-syntax-rule (count-neighbours-in-state ww wh wc r# c# state-to-match)
(for/sum
((r (in-range (- r# 1) (+ r# 2)))
#:when (< -1 r wh)
(c (in-range (- c# 1) (+ c# 2)))
#:when (< -1 c ww)
;; note, this will check cell at (r#, c#), too but it's not
;; worth checking that r=r# and c=c# each time in
;; this case, we know that (r#, c#) is a conductor:
; #:unless (and (= r# r) (= c# c))
(i (in-value (+ (* r ww) c)))
#:when (= state-to-match (fxvector-ref wc i)))
1))
(define (cell-new-state ww wh wc row col)
(let ((cell (fxvector-ref wc (+ col (* row ww)))))
(cond
((= cell state:_) cell) ; empty -> empty
((= cell state:t) state:.) ; tail -> empty
((= cell state:H) state:t) ; head -> tail
((<= 1 (count-neighbours-in-state ww wh wc row col state:H) 2) state:H)
(else cell))))
(define (wire-world-tick world)
(define ww (wire-world-width world))
(define wh (wire-world-height world))
(define wc (wire-world-cells world))
(define (/w x) (quotient x ww))
(define (%w x) (remainder x ww))
(make-wire-world
ww wh
(for/fxvector
#:length (* ww wh)
((cell (in-fxvector wc))
(r# (sequence-map /w (in-naturals)))
(c# (sequence-map %w (in-naturals))))
(cell-new-state ww wh wc r# c#))))
(define colour:_ (make-color 0 0 0)) ; black
(define colour:. (make-color 128 128 128)) ; grey
(define colour:H (make-color 128 255 255)) ; bright cyan
(define colour:t (make-color 0 128 128)) ; dark cyan
(define colour-vector (vector colour:_ colour:. colour:H colour:t))
(define (cell-state->colour state) (vector-ref colour-vector state))
(define render-scaling 20)
(define (render-world W)
(define ww (wire-world-width W))
(define wh (wire-world-height W))
(define wc (wire-world-cells W))
(let* ((flat-state
(for/list ((cell (in-fxvector wc)))
(cell-state->colour cell))))
(place-image (scale render-scaling (color-list->bitmap flat-state ww wh))
(* ww (/ render-scaling 2))
(* wh (/ render-scaling 2))
(empty-scene (* render-scaling ww) (* render-scaling wh)))))
(define (run-wire-world #:initial-state W)
(big-bang
(initial-world W) ;; initial state
[on-tick wire-world-tick
1/8 ; tick time (seconds)
]
[to-draw render-world]))
(run-wire-world #:initial-state initial-list)
|
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.
| #Toka | Toka | needs sdl
800 600 sdl_setup
|
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.
| #TorqueScript | TorqueScript |
new GuiControl(GuiName)
{
profile = "GuiDefaultProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "0 0";
extent = "640 480";
minExtent = "8 2";
enabled = 1;
visible = 1;
clipToParent = 1;
new GuiWindowCtrl()
{
profile = "GuiWindowProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "0 0";
extent = "100 200";
minExtent = "8 2";
enabled = 1;
visible = 1;
clipToParent = 1;
command = "canvas.popDialog(GuiName);";
accelerator = "escape";
maxLength = 255;
resizeWidth = 1;
resizeHeight = 1;
canMove = 1;
canClose = 1;
canMinimize = 1;
canMaximize = 1;
minSize = "50 50";
closeCommand = "canvas.popDialog(GuiName);";
};
};
canvas.pushDialog(GuiName);
|
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.
| #TXR | TXR | (defvarl SDL_INIT_VIDEO #x00000020)
(defvarl SDL_SWSURFACE #x00000000)
(defvarl SDL_HWPALETTE #x20000000)
(typedef SDL_Surface (cptr SDL_Surface))
(typedef SDL_EventType (enumed uint8 SDL_EventType
(SDL_KEYUP 3)
(SDL_QUIT 12)))
(typedef SDL_Event (union SD_Event
(type SDL_EventType)
(pad (array 8 uint32))))
(with-dyn-lib "libSDL.so"
(deffi SDL_Init "SDL_Init" int (uint32))
(deffi SDL_SetVideoMode "SDL_SetVideoMode"
SDL_Surface (int int int uint32))
(deffi SDL_GetError "SDL_GetError" str ())
(deffi SDL_WaitEvent "SDL_WaitEvent" int ((ptr-out SDL_Event)))
(deffi SDL_Quit "SDL_Quit" void ()))
(when (neql 0 (SDL_Init SDL_INIT_VIDEO))
(put-string `unable to initialize SDL: @(SDL_GetError)`)
(exit nil))
(unwind-protect
(progn
(SDL_SetVideoMode 800 600 16 (logior SDL_SWSURFACE SDL_HWPALETTE))
(let ((e (make-union (ffi SDL_Event))))
(until* (memql (union-get e 'type) '(SDL_KEYUP SDL_QUIT))
(SDL_WaitEvent e))))
(SDL_Quit)) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.