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_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
| #Swift | Swift | import Foundation
func printTopWords(path: String, count: Int) throws {
// load file contents into a string
let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
var dict = Dictionary<String, Int>()
// split text into words, convert to lowercase and store word counts in dict
let regex = try NSRegularExpression(pattern: "\\w+")
regex.enumerateMatches(in: text, range: NSRange(text.startIndex..., in: text)) {
(match, _, _) in
guard let match = match else { return }
let word = String(text[Range(match.range, in: text)!]).lowercased()
dict[word, default: 0] += 1
}
// sort words by number of occurrences
let wordCounts = dict.sorted(by: {$0.1 > $1.1})
// print the top count words
print("Rank\tWord\tCount")
for (i, (word, n)) in wordCounts.prefix(count).enumerated() {
print("\(i + 1)\t\(word)\t\(n)")
}
}
do {
try printTopWords(path: "135-0.txt", count: 10)
} catch {
print(error.localizedDescription)
} |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: wrap (in string: aText, in integer: lineWidth) is func
result
var string: wrapped is "";
local
var array string: words is 0 times "";
var string: word is "";
var integer: spaceLeft is 0;
begin
words := split(aText, " ");
if length(words) <> 0 then
wrapped := words[1];
words := words[2 ..];
spaceLeft := lineWidth - length(wrapped);
for word range words do
if length(word) + 1 > spaceLeft then
wrapped &:= "\n" & word;
spaceLeft := lineWidth - length(word);
else
wrapped &:= " " & word;
spaceLeft -:= 1 + length(word);
end if;
end for;
end if;
end func;
const proc: main is func
local
const string: frog is "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.";
var integer: width is 0;
begin
for width range [] (72, 80) do
writeln("Wrapped at " <& width <& ":");
writeln(wrap(frog, width));
end for;
end func; |
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
| #Sidef | Sidef | class String {
method wrap(width) {
var txt = self.gsub(/\s+/, " ");
var len = txt.len;
var para = [];
var i = 0;
while (i < len) {
var j = (i + width);
while ((j < len) && (txt.char_at(j) != ' ')) { --j };
para.append(txt.substr(i, j-i));
i = j+1;
};
return para.join("\n");
}
}
var text = 'aaa bb cc ddddd';
say text.wrap(6); |
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.
| #ProDOS | ProDOS | enableextensions
enabledelayedexpansion
editvar /newvar /value=0 /title=closed
editvar /newvar /value=1 /title=open
editvar /newvar /range=1-100 /increment=1 /from=2
editvar /newvar /value=2 /title=next
:doors
for /alloccurrences (!next!-!102!) do editvar /modify /value=-open-
editvar /modify /value=-next-=+1
if -next- /hasvalue=100 goto :cont else goto :doors
:cont
printline !1!-!102!
stoptask |
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++.
| #Standard_ML | Standard ML |
val getTime = fn url =>
let
val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
val shellCommand = " fetch -o - \""^ url ^"\" | sed -ne 's/^.*alt=.Los Angeles:\\(.* (Daylight Saving)\\).*$/\\1/p' " ;
val me = ( Posix.FileSys.mkfifo
(fname,
Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
) ;
Posix.Process.fork ()
)
in
if (Option.isSome me) then
let
val fin =TextIO.openIn fname
in
( Posix.Process.sleep (Time.fromReal 0.5) ;
TextIO.inputLine fin before
(TextIO.closeIn fin ; OS.FileSys.remove fname )
)
end
else
( OS.Process.system ( shellCommand ^ " > " ^ fname ^ " 2>&1 " ) ;
SOME "" before OS.Process.exit OS.Process.success
)
end;
print ( valOf (getTime "http://www.time.org"));
|
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++.
| #Tcl | Tcl | package require http
set request [http::geturl "http://tycho.usno.navy.mil/cgi-bin/timer.pl"]
if {[regexp -line {<BR>(.* UTC)} [http::data $request] --> utc]} {
puts $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
| #Tcl | Tcl | lassign $argv head
while { [gets stdin line] >= 0 } {
foreach word [regexp -all -inline {[A-Za-z]+} $line] {
dict incr wordcount [string tolower $word]
}
}
set sorted [lsort -stride 2 -index 1 -int -decr $wordcount]
foreach {word count} [lrange $sorted 0 [expr {$head * 2 - 1}]] {
puts "$count\t$word"
} |
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
| #Standard_ML | Standard ML | fun wordWrap n s =
let
fun appendLine (line, text) =
text ^ line ^ "\n"
fun wrap (word, prev as (line, text)) =
if size line + 1 + size word > n
then (word, appendLine prev)
else (line ^ " " ^ word, text)
in
case String.tokens Char.isSpace s of
[] => ""
| (w :: ws) => appendLine (foldl wrap (w, "") ws)
end
val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn |
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
| #Tcl | Tcl | package require Tcl 8.5
proc wrapParagraph {n text} {
regsub -all {\s+} [string trim $text] " " text
set RE "^(.{1,$n})(?:\\s+(.*))?$"
for {set result ""} {[regexp $RE $text -> line text]} {} {
append result $line "\n"
}
return [string trimright $result "\n"]
}
set 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."
puts "[string repeat - 80]"
puts [wrapParagraph 80 $txt]
puts "[string repeat - 72]"
puts [wrapParagraph 72 $txt] |
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.
| #Prolog | Prolog | main :-
forall(between(1,100,Door), ignore(display(Door))).
% show output if door is open after the 100th pass
display(Door) :-
status(Door, 100, open),
format("Door ~d is open~n", [Door]).
% true if Door has Status after Pass is done
status(Door, Pass, Status) :-
Pass > 0,
Remainder is Door mod Pass,
toggle(Remainder, OldStatus, Status),
OldPass is Pass - 1,
status(Door, OldPass, OldStatus).
status(_Door, 0, closed).
toggle(Remainder, Status, Status) :-
Remainder > 0.
toggle(0, open, closed).
toggle(0, closed, open).
|
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++.
| #ToffeeScript | ToffeeScript | e, page = require('request').get! 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'
l = line for line in page.body.split('\n') when line.indexOf('UTC')>0
console.log l.substr(4,l.length-20) |
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++.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SET time = REQUEST ("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
SET utc = FILTER (time,":*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
| #TMG | TMG | /* Input format: N text */
/* Only lowercase letters can constitute a word in text. */
/* (c) 2020, Andrii Makukha, 2-clause BSD licence. */
progrm: readn/error
table(freq) table(chain) [firstword = ~0]
loop: not(!<<>>) output
| [j=777] batch/loop loop; /* Main loop */
/* To use less stack, divide input into batches. */
/* (Avoid interpreting entire input as a single "sentence".) */
batch: [j<=0?] succ
| word/skip [j--] skip batch;
skip: string(other);
not: params(1) (any($1) fail | ());
readn: string(!<<0123456789>>) readint(n) skip;
error: diag(( ={ <ERROR: input must start with a number> * } ));
/* Process a word */
word: smark any(letter) string(letter) scopy
locate/new
[freq[k]++] newmax;
locate: find(freq, k);
new: enter(freq, k)
[freq[k] = 1] newmax
[firstword = firstword==~0 ? k : firstword]
enter(chain, i) [chain[i]=prevword] [prevword=k];
newmax: [max = max<freq[k] ? freq[k] : max];
/* Output logic */
output: [next=max]
outmax: [max=next] [next=0] [max>0?] [j = prevword] cycle/outmax;
cycle: [i = j] [k = freq[i]] [n>0?]
( [max==freq[i]?] parse(wn)
| [(freq[i]<max) & (next<freq[i])?] [next = freq[i]]
| ())
[i != firstword?] [j = chain[i]] cycle;
wn: getnam(freq, i) [k = freq[i]] decimal(k) [n--]
= { 2 < > 1 * };
/* Reads decimal integer */
readint: proc(n;i) ignore(<<>>) [n=0] inta
int1: [n = n*12+i] inta\int1;
inta: char(i) [i<72?] [(i =- 60)>=0?];
/* Variables */
prevword: 0; /* Head of the linked list */
firstword: 0; /* First word's index to know where to stop output */
k: 0;
i: 0;
j: 0;
n: 0; /* Number of most frequent words to display */
max: 0; /* Current highest number of occurrences */
next: 0; /* Next highest number of occurrences */
/* Tables */
freq: 0;
chain: 0;
/* Character classes */
letter: <<abcdefghijklmnopqrstuvwxyz>>;
other: !<<abcdefghijklmnopqrstuvwxyz>>; |
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
| #UNIX_Shell | UNIX Shell | #!/bin/sh
<"$1" tr -cs A-Za-z '\n' | tr A-Z a-z | LC_ALL=C sort | uniq -c | sort -rn | head -n "$2" |
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
| #TPP | TPP | The kings youngest daughter was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. |
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
text="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."
ERROR/STOP CREATE ("text",seq-E,-std-)
length=80
line=REPEAT ("-",length)
FILE "text" = line
firstline=nextlines=""
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext
length=72
line=REPEAT ("-",length)
FILE "text" = line
firstline=CONCAT ("Length ",length,": ")
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext
|
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.
| #Pure | Pure | using system;
// initialize doors as pairs: number, status where 0 means open
let doors = zip (1..100) (repeat 1);
toogle (x,y) = x,~y;
toogleEvery n d = map (tooglep n) d with
tooglep n d@((x,_)) = toogle d if ~(x mod n);
= d otherwise; end;
// show description of given doors
status (n,x) = (str n) + (case x of
1 = " close";
0 = " open"; end);
let result = foldl (\a n -> toogleEvery n a) doors (1..100);
// pretty print the result (only open doors)
showResult = do (puts.status) final when
final = filter open result with
open (_,x) = ~x;
end; 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++.
| #TXR | TXR | @(next @(open-command "wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null"))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>
<html>
<body>
<TITLE>What time is it?</TITLE>
<H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
@(collect :vars (MO DD HH MM SS (PM " ") TZ TZNAME))
<BR>@MO. @DD, @HH:@MM:@SS @(maybe)@{PM /PM/} @(end)@TZ@/\t+/@TZNAME
@ (until)
</PRE>@/.*/
@(end)
</PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A>
</body></html>
@(output)
@ (repeat)
@MO-@DD @HH:@MM:@SS @PM @TZ
@ (end)
@(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++.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
curl -s http://tycho.usno.navy.mil/cgi-bin/timer.pl |
sed -ne 's/^<BR>\(.* UTC\).*$/\1/p' |
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
| #VBA | VBA |
Option Explicit
Private Const PATHFILE As String = "C:\HOME\VBA\ROSETTA"
Sub Main()
Dim arr
Dim Dict As Object
Dim Book As String, temp As String
Dim T#
T = Timer
Book = ExtractTxt(PATHFILE & "\les miserables.txt")
temp = RemovePunctuation(Book)
temp = UCase(temp)
arr = Split(temp, " ")
Set Dict = CreateObject("Scripting.Dictionary")
FillDictionary Dict, arr
Erase arr
SortDictByFreq Dict, arr
DisplayTheTopMostUsedWords arr, 10
Debug.Print "Words different in this book : " & Dict.Count
Debug.Print "-------------------------"
Debug.Print ""
Debug.Print "Optionally : "
Debug.Print "Frequency of the word MISERABLE : " & DisplayFrequencyOf("MISERABLE", Dict)
Debug.Print "Frequency of the word DISASTER : " & DisplayFrequencyOf("DISASTER", Dict)
Debug.Print "Frequency of the word ROSETTA_CODE : " & DisplayFrequencyOf("ROSETTA_CODE", Dict)
Debug.Print "-------------------------"
Debug.Print "Execution Time : " & Format(Timer - T, "0.000") & " sec."
End Sub
Private Function ExtractTxt(strFile As String) As String
'http://rosettacode.org/wiki/File_input/output#VBA
Dim i As Integer
i = FreeFile
Open strFile For Input As #i
ExtractTxt = Input(LOF(1), #i)
Close #i
End Function
Private Function RemovePunctuation(strBook As String) As String
Dim T, i As Integer, temp As String
Const PUNCT As String = """,;:!?."
T = Split(StrConv(PUNCT, vbUnicode), Chr(0))
temp = strBook
For i = LBound(T) To UBound(T) - 1
temp = Replace(temp, T(i), " ")
Next
temp = Replace(temp, "--", " ")
temp = Replace(temp, "...", " ")
temp = Replace(temp, vbCrLf, " ")
RemovePunctuation = Replace(temp, " ", " ")
End Function
Private Sub FillDictionary(d As Object, a As Variant)
Dim L As Long
For L = LBound(a) To UBound(a)
If a(L) <> "" Then _
d(a(L)) = d(a(L)) + 1
Next
End Sub
Private Sub SortDictByFreq(d As Object, myArr As Variant)
Dim K
Dim L As Long
ReDim myArr(1 To d.Count, 1 To 2)
For Each K In d.keys
L = L + 1
myArr(L, 1) = K
myArr(L, 2) = CLng(d(K))
Next
SortArray myArr, LBound(myArr), UBound(myArr), 2
End Sub
Private Sub SortArray(a, Le As Long, Ri As Long, Col As Long)
Dim ref As Long, L As Long, r As Long, temp As Variant
ref = a((Le + Ri) \ 2, Col)
L = Le
r = Ri
Do
Do While a(L, Col) < ref
L = L + 1
Loop
Do While ref < a(r, Col)
r = r - 1
Loop
If L <= r Then
temp = a(L, 1)
a(L, 1) = a(r, 1)
a(r, 1) = temp
temp = a(L, 2)
a(L, 2) = a(r, 2)
a(r, 2) = temp
L = L + 1
r = r - 1
End If
Loop While L <= r
If L < Ri Then SortArray a, L, Ri, Col
If Le < r Then SortArray a, Le, r, Col
End Sub
Private Sub DisplayTheTopMostUsedWords(arr As Variant, Nb As Long)
Dim L As Long, i As Integer
i = 1
Debug.Print "Rank Word Frequency"
Debug.Print "==== ======= ========="
For L = UBound(arr) To UBound(arr) - Nb + 1 Step -1
Debug.Print Left(CStr(i) & " ", 5) & Left(arr(L, 1) & " ", 8) & " " & Format(arr(L, 2), "0 000")
i = i + 1
Next
End Sub
Private Function DisplayFrequencyOf(Word As String, d As Object) As Long
If d.Exists(Word) Then _
DisplayFrequencyOf = d(Word)
End Function |
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
| #VBScript | VBScript |
column = 60
text = "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."
Call wordwrap(text,column)
Sub wordwrap(s,n)
word = Split(s," ")
row = ""
For i = 0 To UBound(word)
If Len(row) = 0 Then
row = row & word(i)
ElseIf Len(row & " " & word(i)) <= n Then
row = row & " " & word(i)
Else
WScript.StdOut.WriteLine row
row = word(i)
End If
Next
If Len(row) > 0 Then
WScript.StdOut.WriteLine row
End If
End Sub
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Pure_Data | Pure Data | 100Doors.pd
#N canvas 241 375 414 447 10;
#X obj 63 256 expr doors[$f1] = doors[$f1] ^ 1;
#X msg 83 118 \; doors const 0;
#X msg 44 66 bang;
#X obj 44 92 t b b b;
#X obj 43 28 table doors 101;
#X obj 44 360 sel 0;
#X obj 44 336 expr if (doors[$f1] == 1 \, $f1 \, 0);
#X obj 63 204 t b f f;
#X text 81 66 run;
#X obj 71 384 print -n;
#X text 132 310 print results (open doors);
#X obj 63 179 loop 1 100 1;
#X obj 63 231 loop 1 100 1;
#X obj 44 310 loop 1 100 1;
#X text 148 28 create array;
#X text 151 180 100 passes;
#X text 179 123 set values to 0;
#X connect 2 0 3 0;
#X connect 3 0 13 0;
#X connect 3 1 11 0;
#X connect 3 2 1 0;
#X connect 5 1 9 0;
#X connect 6 0 5 0;
#X connect 7 0 12 0;
#X connect 7 1 12 1;
#X connect 7 2 12 3;
#X connect 11 0 7 0;
#X connect 12 0 0 0;
#X connect 13 0 6 0;
loop.pd
#N canvas 656 375 427 447 10;
#X obj 62 179 until;
#X obj 102 200 f;
#X obj 62 89 inlet;
#X obj 303 158 f \$3;
#X obj 270 339 outlet;
#X obj 223 89 inlet;
#X obj 138 89 inlet;
#X obj 324 89 inlet;
#X obj 117 158 f \$1;
#X text 323 68 step;
#X obj 202 158 f \$2;
#X obj 62 118 t b b b b;
#X obj 270 315 spigot;
#X obj 89 314 sel 0;
#X obj 137 206 +;
#X obj 102 237 expr $f1 \; if ($f3 > 0 \, if ($f1 > $f2 \, 0 \, 1)
\, if ($f3 < 0 \, if ($f1 < $f2 \, 0 \, 1) \, 0)), f 34;
#X text 63 68 run;
#X text 136 68 start;
#X text 227 68 end;
#X text 58 31 loop (abstraction);
#X connect 0 0 1 0;
#X connect 1 0 14 0;
#X connect 1 0 15 0;
#X connect 2 0 11 0;
#X connect 3 0 14 1;
#X connect 3 0 15 2;
#X connect 5 0 10 1;
#X connect 6 0 8 1;
#X connect 7 0 3 1;
#X connect 8 0 1 1;
#X connect 10 0 15 1;
#X connect 11 0 0 0;
#X connect 11 1 8 0;
#X connect 11 2 10 0;
#X connect 11 3 3 0;
#X connect 12 0 4 0;
#X connect 13 0 0 1;
#X connect 14 0 1 1;
#X connect 15 0 12 0;
#X connect 15 1 12 1;
#X connect 15 1 13 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++.
| #Ursala | Ursala | #import std
#import cli
#executable ('parameterized','')
whatime =
<.file$[contents: --<''>]>+ -+
@hm skip/*4+ ~=(9%cOi&)-~l*+ *~ ~&K3/'UTC',
(ask bash)/0+ -[wget -O - http://tycho.usno.navy.mil/cgi-bin/timer.pl]-!+- |
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++.
| #VBA | VBA | Rem add Microsoft VBScript Regular Expression X.X to your Tools References
Function GetUTC() As String
Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
With CreateObject("MSXML2.XMLHTTP.6.0")
.Open "GET", Url, False
.send
arrt = Split(.responseText, vbLf)
End With
For Each t In arrt
If InStr(t, "UTC") Then
GetUTC = StripHttpTags(t)
Exit For
End If
Next
End Function
Function StripHttpTags(s)
With New RegExp
.Global = True
.Pattern = "\<.+?\>"
If .Test(s) Then
StripHttpTags = .Replace(s, "")
Else
StripHttpTags = s
End If
End With
End Function
Sub getTime()
Rem starting point
Dim ReturnValue As String
ReturnValue = GetUTC
Rem debug.print can be removed
Debug.Print ReturnValue
MsgBox (ReturnValue)
End Sub |
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
| #Wren | Wren | import "io" for File
import "/str" for Str
import "/sort" for Sort
import "/fmt" for Fmt
import "/pattern" for Pattern
var fileName = "135-0.txt"
var text = File.read(fileName).trimEnd()
var groups = {}
// match runs of A-z, a-z, 0-9 and any non-ASCII letters with code-points < 256
var p = Pattern.new("+1&w")
var lines = text.split("\n")
for (line in lines) {
var ms = p.findAll(line)
for (m in ms) {
var t = Str.lower(m.text)
groups[t] = groups.containsKey(t) ? groups[t] + 1 : 1
}
}
var keyVals = groups.toList
Sort.quick(keyVals, 0, keyVals.count - 1) { |i, j| (j.value - i.value).sign }
System.print("Rank Word Frequency")
System.print("==== ==== =========")
for (rank in 1..10) {
var word = keyVals[rank-1].key
var freq = keyVals[rank-1].value
Fmt.print("$2d $-4s $5d", rank, word, freq)
} |
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
| #Vlang | Vlang | fn wrap(text string, line_width int) string {
mut wrapped := ''
words := text.fields()
if words.len == 0 {
return wrapped
}
wrapped = words[0]
mut space_left := line_width - wrapped.len
for word in words[1..] {
if word.len+1 > space_left {
wrapped += "\n" + word
space_left = line_width - word.len
} else {
wrapped += " " + word
space_left -= 1 + word.len
}
}
return wrapped
}
const frog = "
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."
fn main() {
println("wrapped at 80:")
println(wrap(frog, 80))
println("wrapped at 72:")
println(wrap(frog, 72))
} |
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.
| #PureBasic | PureBasic | Dim doors.i(100)
For x = 1 To 100
y = x
While y <= 100
doors(y) = 1 - doors(y)
y + x
Wend
Next
OpenConsole()
PrintN("Following Doors are open:")
For x = 1 To 100
If doors(x)
Print(Str(x) + ", ")
EndIf
Next
Input() |
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++.
| #VBScript | VBScript | Function GetUTC() As String
Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
With CreateObject("MSXML2.XMLHTTP.6.0")
.Open "GET", Url, False
.send
arrt = Split(.responseText, vbLf)
End With
For Each t In arrt
If InStr(t, "UTC") Then
GetUTC = StripHttpTags(t)
Exit For
End If
Next
End Function
Function StripHttpTags(s)
With New RegExp
.Global = True
.Pattern = "\<.+?\>"
If .Test(s) Then
StripHttpTags = .Replace(s, "")
Else
StripHttpTags = s
End If
End With
End Function
WScript.StdOut.Write GetUTC
WScript.StdOut.WriteLine |
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++.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Net
Imports System.IO
Dim client As WebClient = New WebClient()
Dim content As String = client.DownloadString("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
Dim sr As New StringReader(content)
While sr.peek <> -1
Dim s As String = sr.ReadLine
If s.Contains("UTC") Then
Dim time As String() = s.Substring(4).Split(vbTab)
Console.WriteLine(time(0))
End If
End While |
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
| #XQuery | XQuery | let $maxentries := 10,
$uri := 'https://www.gutenberg.org/files/135/135-0.txt'
return
<words in="{$uri}" top="{$maxentries}"> {
(
let $doc := unparsed-text($uri),
$tokens := (
tokenize($doc, '\W+')[normalize-space()]
! lower-case(.)
! normalize-unicode(., 'NFC')
)
return
for $token in $tokens
let $key := $token
group by $key
let $count := count($token)
order by $count descending
return <word key="{$key}" count="{$count}"/>
)[position()=(1 to $maxentries)]
}</words> |
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
| #zkl | zkl | fname,count := vm.arglist; // grab cammand line args
// words may have leading or trailing "_", ie "the" and "_the"
File(fname).pump(Void,"toLower", // read the file line by line and hash words
RegExp("[a-z]+").pump.fp1(Dictionary().incV)) // line-->(word:count,..)
.toList().copy().sort(fcn(a,b){ b[1]<a[1] })[0,count.toInt()] // hash-->list
.pump(String,Void.Xplode,"%s,%s\n".fmt).println(); |
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
| #Wren | Wren | var greedyWordWrap = Fn.new { |text, lineWidth|
var words = text.split(" ")
var sb = words[0]
var spaceLeft = lineWidth - words[0].count
for (word in words.skip(1)) {
var len = word.count
if (len + 1 > spaceLeft) {
sb = sb + "\n" + word
spaceLeft = lineWidth - len
} else {
sb = sb + " " + word
spaceLeft = spaceLeft - len - 1
}
}
return sb
}
var text =
"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."
System.print("Greedy algorithm - wrapped at 72:")
System.print(greedyWordWrap.call(text, 72))
System.print("\nGreedy algorithm - wrapped at 80:")
System.print(greedyWordWrap.call(text, 80)) |
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.
| #Pyret | Pyret |
data Door:
| open
| closed
end
fun flip-door(d :: Door) -> Door:
cases(Door) d:
| open => closed
| closed => open
end
end
fun flip-doors(doors :: List<Door>) -> List<Door>:
doc:```Given a list of door positions, repeatedly switch the positions of
every nth door for every nth pass, and return the final list of door
positions```
for fold(flipped-doors from doors, n from range(1, doors.length() + 1)):
for map_n(m from 1, d from flipped-doors):
if num-modulo(m, n) == 0:
flip-door(d)
else:
d
end
end
end
where:
flip-doors([list: closed, closed, closed]) is
[list: open, closed, closed]
flip-doors([list: closed, closed, closed, closed]) is
[list: open, closed, closed, open]
flip-doors([list: closed, closed, closed, closed, closed, closed]) is
[list: open, closed, closed, open, closed, closed]
closed-100 = for map(_ from range(1, 101)): closed end
answer-100 = for map(n from range(1, 101)):
if num-is-integer(num-sqrt(n)): open
else: closed
end
end
flip-doors(closed-100) is answer-100
end
fun find-indices<A>(pred :: (A -> Boolean), xs :: List<A>) -> List<Number>:
doc:```Given a list and a predicate function, produce a list of index
positions where there's a match on the predicate```
ps = map_n(lam(n,e): if pred(e): n else: -1 end end, 1, xs)
ps.filter(lam(x): x >= 0 end)
where:
find-indices((lam(i): i == true end), [list: true,false,true]) is [list:1,3]
end
fun run(n):
doc:```Given a list of doors that are closed, make repeated passes
over the list, switching the positions of every nth door for
each nth pass. Return a list of positions in the list where the
door is Open.```
doors = repeat(n, closed)
ys = flip-doors(doors)
find-indices((lam(y): y == open end), ys)
where:
run(4) is [list: 1,4]
end
run(100)
|
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++.
| #Wren | Wren | /* web_scraping.wren */
import "./pattern" for Pattern
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
var BUFSIZE = 16384
foreign class Buffer {
construct new(size) {}
// returns buffer contents as a string
foreign value
}
foreign class Curl {
construct easyInit() {}
foreign easySetOpt(opt, param)
foreign easyPerform()
foreign easyCleanup()
}
var buffer = Buffer.new(BUFSIZE)
var curl = Curl.easyInit()
curl.easySetOpt(CURLOPT_URL, "https://rosettacode.org/wiki/Talk:Web_scraping")
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C
curl.easySetOpt(CURLOPT_WRITEDATA, buffer)
curl.easyPerform()
curl.easyCleanup()
var html = buffer.value
var ix = html.indexOf("(UTC)")
if (ix == -1) {
System.print("UTC time not found.")
return
}
var p = Pattern.new("/d/d:/d/d, #12/d +1/a =4/d")
var m = p.find(html[(ix - 30).max(0)...ix])
System.print(m.text) |
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
| #XPL0 | XPL0 | string 0;
proc WordWrap(Text, LineWidth); \Display Text string wrapped at LineWidth
char Text, LineWidth, Word, SpaceLeft, WordWidth, I;
[SpaceLeft:= 0;
loop [loop [if Text(0) = 0 then return; \skip whitespace (like CR)
if Text(0) > $20 then quit;
Text:= Text+1;
];
Word:= Text; WordWidth:= 0;
while Word(WordWidth) > $20 do
WordWidth:= WordWidth+1;
Text:= Text + WordWidth; \move to Word terminator
if WordWidth+1 > SpaceLeft then
[CrLf(0);
for I:= 0 to WordWidth-1 do ChOut(0, Word(I));
SpaceLeft:= LineWidth - WordWidth;
]
else [ChOut(0, ^ );
for I:= 0 to WordWidth-1 do ChOut(0, Word(I));
SpaceLeft:= SpaceLeft - WordWidth - 1;
];
];
];
char Text;
[Text:=
"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(Text, 72); CrLf(0);
WordWrap(Text, 80); CrLf(0);
] |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
Extra credit
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you must reference documentation indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Yabasic | Yabasic | t$ = "In olden times when wishing still helped one, there lived a king "
t$ = t$ + "whose daughters were all beautiful, but the youngest was so beautiful "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
t$ = t$ + "it shone in her face.\n\n"
t$ = t$ + t$
t$ = trim$(t$)
input "Width: " width // user specifies width
dim p$(1)
d$ = " .,\n"
n = words(t$, p$(), d$)
for i = 1 to n
if p$(i) = "\n" or len(docOut$) + len(p$(i)) > width then
print docOut$
docOut$ = ""
end if
if p$(i) <> "\n" docOut$ = docOut$ + p$(i)
next i
print docOut$
sub words(w$, p$(), d$)
local n, i, p
n = split(w$, p$(), d$)
p = 1
for i = 1 to n
p$(i) = p$(i) + mid$(w$, p + len(p$(i)), 1)
p = p + len(p$(i))
next i
return n
end sub |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Python | Python |
doors = [False] * 100
for i in range(100):
for j in range(i, 100, i+1):
doors[j] = not doors[j]
print("Door %d:" % (i+1), 'open' if doors[i] else 'close')
|
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++.
| #Xidel | Xidel | $ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
//p[1]/text()[last()]
'
20:53, 20 August 2008 (UTC)
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
'
2008-08-20T20:53:00
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
adjust-dateTime-to-timezone(
x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy'),
dayTimeDuration('PT0H')
)
'
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
! adjust-dateTime-to-timezone(.,dayTimeDuration('PT0H'))
'
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
=> adjust-dateTime-to-timezone(dayTimeDuration('PT0H'))
'
2008-08-20T20:53:00Z |
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++.
| #zkl | zkl | const HOST="tycho.usno.navy.mil", PORT=80, dir="/cgi-bin/timer.pl";
get:="GET %s HTTP/1.0\r\nHost: %s:%s\r\n\r\n".fmt(dir,HOST,PORT);
server:=Network.TCPClientSocket.connectTo(HOST,PORT);
server.write(get); // send request to web serer
data:=server.read(True); // read data from web server
data.seek(data.find("UTC")); // middle of line
c:=data.seek(Void,0); // start of line
line:=data[c,data.seek(Void,1)-c].text;
line.print(); // the HTML UTC line
re:=RegExp(0'|.*(\d\d:\d\d:\d\d)|); // get time
re.search(line);
re.matched[1].println(); |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #11l | 11l | UInt32 seed = 0
F nonrandom(n)
:seed = (1664525 * :seed + 1013904223) [&] FFFF'FFFF
R Int(:seed >> 16) % n
F nonrandom_shuffle(&x)
L(i) (x.len - 1 .< 0).step(-1)
V j = nonrandom(i + 1)
swap(&x[i], &x[j])
V SUITS = [‘♣’, ‘♦’, ‘♥’, ‘♠’]
V FACES = [‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘J’, ‘Q’, ‘K’, ‘A’]
V DECK = multiloop(FACES, SUITS, (f, s) -> f‘’s)
V CARD_TO_RANK = Dict((0 .< DECK.len).map(i -> (:DECK[i], (i + 3) I/ 4)))
T WarCardGame
[String] deck1, deck2, pending
F ()
V deck = copy(:DECK)
nonrandom_shuffle(&deck)
.deck1 = deck[0.<26]
.deck2 = deck[26..]
F gameover()
‘ game over who won message ’
I .deck2.empty
I .deck1.empty
print("\nGame ends as a tie.")
E
print("\nPlayer 1 wins the game.")
E
print("\nPlayer 2 wins the game.")
R 0B
F turn()
‘ one turn, may recurse on tie ’
I .deck1.empty | .deck2.empty
R .gameover()
V card1 = .deck1.pop(0)
V card2 = .deck2.pop(0)
V (rank1, rank2) = (:CARD_TO_RANK[card1], :CARD_TO_RANK[card2])
print(‘#<10#<10’.format(card1, card2), end' ‘’)
I rank1 > rank2
print(‘Player 1 takes the cards.’)
.deck1.extend([card1, card2])
.deck1.extend(.pending)
.pending.clear()
E I rank1 < rank2
print(‘Player 2 takes the cards.’)
.deck2.extend([card2, card1])
.deck2.extend(.pending)
.pending.clear()
E
print(‘Tie!’)
I .deck1.empty | .deck2.empty
R .gameover()
V card3 = .deck1.pop(0)
V card4 = .deck2.pop(0)
.pending.extend([card1, card2, card3, card4])
print(‘#<10#<10’.format(‘?’, ‘?’)‘Cards are face down.’)
R .turn()
R 1B
V WG = WarCardGame()
L WG.turn()
L.continue |
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
| #zkl | zkl | fcn formatText(text, // text can be String,Data,File, -->Data
length=72, calcIndents=True){
sink:=Data();
getIndents:='wrap(w){ // look at first two lines to indent paragraph
reg lines=L(), len=0, prefix="", one=True;
do(2){
if(w._next()){
lines.append(line:=w.value);
word:=line.split(Void,1)[0,1]; // get first word, if line !blank
if(word){
p:=line[0,line.find(word[0]]);
if(one){ sink.write(p); len=p.len(); one=False; }
else prefix=p;
}
}
}
w.push(lines.xplode()); // put first two lines back to be formated
return(len,prefix);
};
reg len=0, prefix="", w=text.walker(1); // lines
if(calcIndents) len,prefix=getIndents(w);
foreach line in (w){
if(not line.strip()){ // blank line
sink.write("\n",line); // blank line redux
if(calcIndents) len,prefix=getIndents(w);
else len=0; // restart formating
}else
len=line.split().reduce('wrap(len,word){
n:=word.len();
if(len==0) { sink.write(word); return(n); }
nn:=n+1+len; if(nn<=length) { sink.write(" ",word); return(nn); }
sink.write("\n",prefix,word); return(prefix.len()+word.len());
},len);
}
sink
} |
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.
| #Q | Q | `closed`open(100#0b){@[x;where y;not]}/100#'(til[100]#'0b),'1b |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #AutoHotkey | AutoHotkey | suits := ["♠", "♦", "♥", "♣"]
faces := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
deck := [], p1 := [], p2 := []
for i, s in suits
for j, v in faces
deck.Push(v s)
deck := shuffle(deck)
deal := deal(deck, p1, p2)
p1 := deal.1, p2 := deal.2
for i, v in p2
{
if InStr(v, "A")
p2[i] := p1[i], p1[i] := v
if InStr(v, "K")
p2[i] := p1[i], p1[i] := v
if InStr(v, "Q")
p2[i] := p1[i], p1[i] := v
if InStr(v, "J")
p2[i] := p1[i], p1[i] := v
}
MsgBox % war(p1, p2)
return
war(p1, p2){
J:=11, Q:=11, K:=11, A:=12, stack := [], cntr := 0
output := "------------------------------------------"
. "`nRound# Deal Winner P1 P1"
. "`n------------------------------------------"
. "`nround0 26 26"
while (p1.Count() && p2.Count()) {
cntr++
stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1))
r1:=SubStr(c1,1,-1) ,r2:=SubStr(c2,1,-1)
v1:=r1<11?r1:%r1% ,v2:=r2<11?r2:%r2%
output .= "`nround# " cntr "`t" SubStr(c1 " n", 1, 4) "vs " SubStr(c2 " ", 1, 4)
if (v1 > v2){
loop % stack.Count()
p1.Push(stack.RemoveAt(1))
output .= "`t`tP1 wins"
}
else if (v1 < v2){
loop % stack.Count()
p2.Push(stack.RemoveAt(1))
output .= "`t`tP2 wins"
}
if (v1 = v2){
output .= "`t`t**WAR**`t" P1.Count() "`t" P2.Count()
stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1))
if !(p1.Count() && p2.Count())
break
output .= "`nround# " ++cntr "`t(" SubStr(c1 " ", 1, 3) ") - (" SubStr(c2 " ", 1, 3) ")"
output .= "`tFace Dn"
}
output .= "`t" P1.Count() "`t" P2.Count()
if !Mod(cntr, 20)
{
MsgBox % output
output := ""
}
}
output .= "`n" (P1.Count() ? "P1 Wins" : "P2 Wins")
output := StrReplace(output, " )", ") ")
output := StrReplace(output, " -", " -")
return output |
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.
| #QB64 | QB64 |
Const Opened = -1, Closed = 0
Dim Doors(1 To 100) As Integer, Passes As Integer, Index As Integer
Rem Normal implementation
Print "100doors Normal method"
For Passes = 1 To 100 Step 1
Doors(Passes) = Closed
Next Passes
For Passes = 1 To 100 Step 1
For Index = 0 To 100 Step Passes
If Index > 100 Then Exit For
If Index > 0 Then If Doors(Index) = Opened Then Doors(Index) = Closed Else Doors(Index) = Opened
Next Index
Next Passes
Print "OPEN DOORS after 100th passes"
For Passes = 1 To 100 Step 1
If Doors(Passes) = Opened Then Print Passes; " ";
Next
Rem Alternative solution of perfect squares
Print "Alternative method"
Passes = 0
For Passes = 1 To 100 Step 1
Doors(Passes) = Closed
Next Passes
For Passes = 1 To 100 Step 1
If Sqr(Passes) = Int(Sqr(Passes)) Then Doors(Passes) = Opened
Next
Print "Opened doors found by SQR method"
For Passes = 1 To 100 Step 1
If Doors(Passes) = Opened Then Print Passes; " ";
Next Passes
End
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
var suits = []string{"♣", "♦", "♥", "♠"}
var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}
var cards = make([]string, 52)
var ranks = make([]int, 52)
func init() {
for i := 0; i < 52; i++ {
cards[i] = fmt.Sprintf("%s%s", faces[i%13], suits[i/13])
ranks[i] = i % 13
}
}
func war() {
deck := make([]int, 52)
for i := 0; i < 52; i++ {
deck[i] = i
}
rand.Shuffle(52, func(i, j int) {
deck[i], deck[j] = deck[j], deck[i]
})
hand1 := make([]int, 26, 52)
hand2 := make([]int, 26, 52)
for i := 0; i < 26; i++ {
hand1[25-i] = deck[2*i]
hand2[25-i] = deck[2*i+1]
}
for len(hand1) > 0 && len(hand2) > 0 {
card1 := hand1[0]
copy(hand1[0:], hand1[1:])
hand1[len(hand1)-1] = 0
hand1 = hand1[0 : len(hand1)-1]
card2 := hand2[0]
copy(hand2[0:], hand2[1:])
hand2[len(hand2)-1] = 0
hand2 = hand2[0 : len(hand2)-1]
played1 := []int{card1}
played2 := []int{card2}
numPlayed := 2
for {
fmt.Printf("%s\t%s\t", cards[card1], cards[card2])
if ranks[card1] > ranks[card2] {
hand1 = append(hand1, played1...)
hand1 = append(hand1, played2...)
fmt.Printf("Player 1 takes the %d cards. Now has %d.\n", numPlayed, len(hand1))
break
} else if ranks[card1] < ranks[card2] {
hand2 = append(hand2, played2...)
hand2 = append(hand2, played1...)
fmt.Printf("Player 2 takes the %d cards. Now has %d.\n", numPlayed, len(hand2))
break
} else {
fmt.Println("War!")
if len(hand1) < 2 {
fmt.Println("Player 1 has insufficient cards left.")
hand2 = append(hand2, played2...)
hand2 = append(hand2, played1...)
hand2 = append(hand2, hand1...)
hand1 = hand1[0:0]
break
}
if len(hand2) < 2 {
fmt.Println("Player 2 has insufficient cards left.")
hand1 = append(hand1, played1...)
hand1 = append(hand1, played2...)
hand1 = append(hand1, hand2...)
hand2 = hand2[0:0]
break
}
fdCard1 := hand1[0] // face down card
card1 = hand1[1] // face up card
copy(hand1[0:], hand1[2:])
hand1[len(hand1)-1] = 0
hand1[len(hand1)-2] = 0
hand1 = hand1[0 : len(hand1)-2]
played1 = append(played1, fdCard1, card1)
fdCard2 := hand2[0] // face down card
card2 = hand2[1] // face up card
copy(hand2[0:], hand2[2:])
hand2[len(hand2)-1] = 0
hand2[len(hand2)-2] = 0
hand2 = hand2[0 : len(hand2)-2]
played2 = append(played2, fdCard2, card2)
numPlayed += 4
fmt.Println("? \t? \tFace down cards.")
}
}
}
if len(hand1) == 52 {
fmt.Println("Player 1 wins the game!")
} else {
fmt.Println("Player 2 wins the game!")
}
}
func main() {
rand.Seed(time.Now().UnixNano())
war()
} |
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.
| #Quackery | Quackery | /O> [ bit ^ ] is toggle ( f n --> f )
...
... [ 0
... 100 times
... [ i^ 1+ swap
... 101 times
... [ i^ toggle over step ]
... nip ] ] is toggledoors ( --> f )
...
... [ 100 times
... [ 1 >> dup 1 &
... if [ i^ 1+ echo sp ] ]
... drop ] is echodoors ( f --> )
...
... toggledoors
... say " These doors are open: " echodoors cr
... say " The rest are closed." cr
...
These doors are open: 1 4 9 16 25 36 49 64 81 100
The rest are closed.
Stack empty.
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Julia | Julia | # https://bicyclecards.com/how-to-play/war/
using Random
const SUITS = ["♣", "♦", "♥", "♠"]
const FACES = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" ]
const DECK = vec([f * s for s in SUITS, f in FACES])
const rdict = Dict(DECK[i] => div(i + 3, 4) for i in eachindex(DECK))
deal2(deck) = begin d = shuffle(deck); d[1:2:51], d[2:2:52] end
function turn!(d1, d2, pending)
(isempty(d1) || isempty(d2)) && return false
c1, c2 = popfirst!(d1), popfirst!(d2)
r1, r2 = rdict[c1], rdict[c2]
print(rpad(c1, 10), rpad(c2, 10))
if r1 > r2
println("Player 1 takes the cards.")
push!(d1, c1, c2, pending...)
empty!(pending)
elseif r1 < r2
println("Player 2 takes the cards.")
push!(d2, c2, c1, pending...)
empty!(pending)
else # r1 == r2
println("Tie!")
(isempty(d1) || isempty(d2)) && return false
c3, c4 = popfirst!(d1), popfirst!(d2)
println(rpad("?", 10), rpad("?", 10), "Cards are face down.")
return turn!(d1, d2, push!(pending, c1, c2, c3, c4))
end
return true
end
function warcardgame()
deck1, deck2 = deal2(DECK)
while turn!(deck1, deck2, []) end
if isempty(deck2)
if isempty(deck1)
println("Game ends as a tie.")
else
println("Player 1 wins the game.")
end
else
println("Player 2 wins the game.")
end
end
warcardgame()
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Lua | Lua | -- main.lua
function newGame ()
-- new deck
local deck = {}
for iSuit = 1, #CardSuits do
for iRank = 1, #CardRanks do
local card = {
iSuit = iSuit,
iRank = iRank,
suit = CardSuits[iSuit],
rank = iRank,
name = CardRanks[iRank] .. CardSuits[iSuit]
}
local i = math.random (#deck + 1)
table.insert (deck, i, card)
end
end
-- new deal
Players = {
{index = 1, cards = {}},
{index = 2, cards = {}},
}
for i = 1, #deck/#Players do
for iPlayer = 1, #Players do
table.insert (Players[iPlayer].cards, table.remove(deck))
end
end
WarCards = {}
Turn = 1
Statistics = {}
end
function getHigherCard (cardA, cardB)
if cardA.rank > cardB.rank then
return cardA, 1
elseif cardA.rank < cardB.rank then
return cardB, 2
else
return nil
end
end
function love.load()
-- there is no card suits in the standard font
CardSuits = {"@", "#", "$", "%"}
CardRanks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "V", "Q", "K", "A"}
newGame ()
end
function love.draw()
for iPlayer = 1, #Players do
local player = Players[iPlayer]
love.graphics.print ('Player '..player.index, 50*(iPlayer-1), 0)
for iCard, card in ipairs (player.cards) do
love.graphics.print (card.name, 50*(iPlayer-1), 14*iCard)
end
end
for i = 1, math.min(40, #Statistics) do
local str = Statistics[i]
love.graphics.print (str, 150, 20+(i-1)*14)
end
end
function makeTurn ()
local card1 = table.remove (Players[1].cards)
local card2 = table.remove (Players[2].cards)
if card1 and card2 then
table.insert (WarCards, 1, card1)
table.insert (WarCards, math.random (1, 2), card2)
local winCard, index = getHigherCard (card1, card2)
if winCard then
table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' get ' .. #WarCards .. ' cards: ' .. card1.name .. ' vs ' .. card2.name)
for iCard = #WarCards, 1, -1 do
table.insert (Players[index].cards, 1, table.remove (WarCards))
end
elseif (#Players[1].cards > 0) and (#Players[2].cards > 0) then
-- start war
table.insert (Statistics, 1, Turn .. ' War: ' .. card1.name .. ' vs ' .. card2.name)
table.insert (WarCards, table.remove (Players[1].cards))
table.insert (WarCards, table.remove (Players[2].cards))
else
local index = 2
if #Players[1].cards == 0 then index = 1 end
table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' has no cards for this war.')
-- GameOver = true
end
Turn = Turn + 1
elseif GameOver then
GameOver = false
newGame ()
else
local index = 2
if #Players[1].cards > #Players[2].cards then index = 1 end
table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' wins the game!')
GameOver = true
end
end
function love.keypressed(key, scancode, isrepeat)
if false then
elseif key == "space" then
makeTurn ()
elseif scancode == "n" then
GameOver = false
newGame ()
elseif scancode == "q" then
local lastTurn = Turn
while not (GameOver or (Turn > lastTurn + 10000-1)) do
makeTurn ()
end
elseif key == "escape" then
love.event.quit()
end
if #Statistics > 40 then
local i = #Statistics, 40, -1 do
table.remove (Statistics, i)
end
end
end
function love.mousepressed( x, y, button, istouch, presses )
if button == 1 then -- left mouse button
makeTurn ()
elseif button == 2 then -- right mouse button
end
end
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #R | R | doors_puzzle <- function(ndoors, passes = ndoors) {
doors <- logical(ndoors)
for (ii in seq(passes)) {
mask <- seq(ii, ndoors, ii)
doors[mask] <- !doors[mask]
}
which(doors)
}
doors_puzzle(100) |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Nim | Nim | import strformat
import playing_cards
const
None = -1
Player1 = 0
Player2 = 1
type Player = range[None..Player2]
const PlayerNames: array[Player1..Player2, string] = ["Player 1", "Player 2"]
#---------------------------------------------------------------------------------------------------
proc `<`(a, b: Card): bool =
## Compare two cards by their rank, Ace being the greatest.
if a.rank == Ace: false
elif b.rank == Ace: true
else: a.rank < b.rank
#---------------------------------------------------------------------------------------------------
proc displayRound(round: int; hands: openArray[Hand]; card1, card2: string; text: string) =
## Display text for a round.
stdout.write &"Round {round:<4} "
stdout.write &"Cards: {hands[Player1].len:>2}/{hands[Player2].len:<2} "
stdout.write &"{card1:>3} {card2:>3} "
echo text
#---------------------------------------------------------------------------------------------------
proc outOfCards(player: Player) =
## Display a message when a player has run out of cards.
echo &"{PlayerNames[player]} has run out of cards."
#---------------------------------------------------------------------------------------------------
proc doRound(hands: var openArray[Hand]; num: Positive) =
## Execute a round.
var stack1, stack2: seq[Card]
var winner: Player = None
while winner == None:
let card1 = hands[Player1].draw()
let card2 = hands[Player2].draw()
stack1.add card1
stack2.add card2
if card1.rank != card2.rank:
winner = if card1 < card2: Player2 else: Player1
displayRound(num, hands, $card1, $card2, &"{PlayerNames[winner]} takes the cards.")
else:
# There is a war.
displayRound(num, hands, $card1, $card2, "This is a war.")
if hands[Player1].len == 0:
winner = Player2
elif hands[Player2].len == 0:
winner = Player1
else:
# Add a hidden card on stacks.
stack1.add hands[Player1].draw()
stack2.add hands[Player2].draw()
displayRound(num, hands, " ?", " ?", "Cards are face down.")
# Check if each player has enough cards to continue the war.
if hands[Player1].len == 0:
Player1.outOfCards()
winner = Player2
elif hands[Player2].len == 0:
Player2.outOfCards()
winner = Player1
# Update hands.
var stack = stack1 & stack2
stack.shuffle()
hands[winner] = stack & hands[winner]
#———————————————————————————————————————————————————————————————————————————————————————————————————
var deck = initDeck()
deck.shuffle()
var hands = deck.deal(2, 26)
var num = 0
while true:
inc num
hands.doRound(num)
if hands[Player1].len == 0:
echo "Player 2 wins this game."
break
if hands[Player2].len == 0:
echo "Player 1 wins this game."
break |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/War_Card_Game
use warnings;
use List::Util qw( shuffle );
my %rank;
@rank{ 2 .. 9, qw(t j q k a) } = 1 .. 13; # for winner
local $_ = join '', shuffle
map { my $f = $_; map $f.$_, qw( S H C D ) } 2 .. 9, qw( a t j q k );
substr $_, 52, 0, "\n"; # split deck into two parts
my $war = '';
my $cnt = 0;
$cnt++ while print( /(.*)\n(.*)/ && "one: $1\ntwo: $2\n\n" ),
s/^((.).)(.*)\n((?!\2)(.).)(.*)$/ my $win = $war; $war = ''; # capture
$rank{$2} > $rank{$5} ? "$3$1$4$win\n$6" : "$3\n$6$4$1$win" /e
||
s/^(.{4})(.*)\n(.{4})(.*)$/ print "WAR!!!\n\n"; $war .= "$1$3";
"$2\n$4" /e; # tie means war
print "player '", /^.{10}/ ? 'one' : 'two', "' wins in $cnt moves\n"; |
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.
| #Racket | Racket |
#lang racket
;; Applies fun to every step-th element of seq, leaving the others unchanged.
(define (map-step fun step seq)
(for/list ([elt seq] [i (in-naturals)])
((if (zero? (modulo i step)) fun values) elt)))
(define (toggle-nth n seq)
(map-step not n seq))
(define (solve seq)
(for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)])
(toggle-nth pass result)))
(for ([door (solve (make-vector 101 #f))] [index (in-naturals)]
#:when (and door (> index 0)))
(printf "~a is open~%" index))
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Phix | Phix | with javascript_semantics
sequence deck = shuffle(tagset(52)),
hand1 = deck[1..26],
hand2 = deck[27..52],
pending = {}
function pop1()
integer res
{res, hand1} = {hand1[1],hand1[2..$]}
return res
end function
function pop2()
integer res
{res, hand2} = {hand2[1],hand2[2..$]}
return res
end function
function show(integer c)
integer r = remainder(c-1,13)+1,
s = floor((c-1)/13)+1
printf(1,"%s ",{"23456789TJQKA"[r]&"SHDC"[s]})
return r
end function
while true do
if length(hand1)=0 then
if length(hand2)=0 then
printf(1,"Game ends as a tie.\n")
exit
end if
printf(1,"Player 2 wins the game.\n")
exit
elsif length(hand2)=0 then
printf(1,"Player 1 wins the game.\n")
exit
end if
integer c1 = pop1(),
c2 = pop2(),
r1 = show(c1),
r2 = show(c2)
if r1>r2 then
printf(1,"Player 1 takes the cards.\n")
hand1 &= shuffle(c1&c2&pending)
pending = {}
elsif r1<r2 then
printf(1,"Player 2 takes the cards.\n")
hand2 &= shuffle(c1&c2&pending)
pending = {}
else -- r1==r2
printf(1,"Tie!\n")
if length(hand1)!=0 and length(hand2)!=0 then
pending &= shuffle(c1&c2&pop1()&pop2())
printf(1,"?? ?? Cards are face down.\n")
end if
end if
end while
|
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.
| #Raku | Raku | my @doors = False xx 101;
(.=not for @doors[0, $_ ... 100]) for 1..100;
say "Door $_ is ", <closed open>[ @doors[$_] ] for 1..100; |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Python | Python | """ https://bicyclecards.com/how-to-play/war/ """
from numpy.random import shuffle
SUITS = ['♣', '♦', '♥', '♠']
FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
DECK = [f + s for f in FACES for s in SUITS]
CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))
class WarCardGame:
""" card game War """
def __init__(self):
deck = DECK.copy()
shuffle(deck)
self.deck1, self.deck2 = deck[:26], deck[26:]
self.pending = []
def turn(self):
""" one turn, may recurse on tie """
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
card1, card2 = self.deck1.pop(0), self.deck2.pop(0)
rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]
print("{:10}{:10}".format(card1, card2), end='')
if rank1 > rank2:
print('Player 1 takes the cards.')
self.deck1.extend([card1, card2])
self.deck1.extend(self.pending)
self.pending = []
elif rank1 < rank2:
print('Player 2 takes the cards.')
self.deck2.extend([card2, card1])
self.deck2.extend(self.pending)
self.pending = []
else: # rank1 == rank2
print('Tie!')
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
card3, card4 = self.deck1.pop(0), self.deck2.pop(0)
self.pending.extend([card1, card2, card3, card4])
print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='')
return self.turn()
return True
def gameover(self):
""" game over who won message """
if len(self.deck2) == 0:
if len(self.deck1) == 0:
print('\nGame ends as a tie.')
else:
print('\nPlayer 1 wins the game.')
else:
print('\nPlayer 2 wins the game.')
return False
if __name__ == '__main__':
WG = WarCardGame()
while WG.turn():
continue
|
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.
| #RapidQ | RapidQ |
dim x as integer, y as integer
dim door(1 to 100) as byte
'initialize array
for x = 1 to 100 : door(x) = 0 : next
'set door values
for y = 1 to 100
for x = y to 100 step y
door(x) = not door(x)
next x
next y
'print result
for x = 1 to 100
if door(x) then print "Door " + str$(x) + " = open"
next
while inkey$="":wend
end
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Racket | Racket | #lang racket
(define current-battle-length (make-parameter 3))
(define cards (string->list (string-append "🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂭🂮🂡" "🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂽🂾🂱"
"🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃍🃎🃁" "🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃝🃞🃑")))
(define face (curry hash-ref (for/hash ((c cards) (i (in-naturals))) (values c (+ 2 (modulo i 13))))))
(define (print-draw-result turn-number d1 c1 d2 c2 → (pending null))
(printf "#~a\t~a ~a ~a\t~a|~a|~a~%" turn-number c1 → c2 (length d1) (length pending)(length d2)))
(define (turn d1 d2 (n 1) (pending null) (battle 0))
(match* (d1 d2)
[('() '()) "Game ends in a tie!"]
[(_ '()) "Player 1 wins."]
[('() _) "Player 2 wins."]
[((list c3 d1- ...) (list c4 d2- ...))
#:when (positive? battle)
(define pending+ (list* c3 c4 pending))
(print-draw-result n d1- "🂠" d2- "🂠" "?" pending+)
(turn d1- d2- (add1 n) pending+ (sub1 battle))]
[((list (and c1 (app face r)) d1- ...) (list (and c2 (app face r)) d2- ...))
(define pending+ (list* c1 c2 pending))
(print-draw-result n d1- c1 d2- c2 #\= pending+)
(turn d1- d2- (add1 n) pending+ (current-battle-length))]
[((list (and c1 (app face r1)) d1- ...) (list (and c2 (app face r2)) d2- ...))
(define spoils (shuffle (list* c1 c2 pending)))
(define p1-win? (> r1 r2))
(define d1+ (if p1-win? (append d1- spoils) d1-))
(define d2+ (if p1-win? d2- (append d2- spoils)))
(print-draw-result n d1+ c1 d2+ c2 (if p1-win? "←" "→"))
(turn d1+ d2+ (add1 n))]))
(define (war-card-game)
(call-with-values (λ () (split-at (shuffle cards) (quotient (length cards) 2)))
turn))
(displayln (war-card-game)) |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Raku | Raku | unit sub MAIN (:$war where 2..4 = 4, :$sleep = .1);
my %c = ( # convenience hash of ANSI colors
red => "\e[38;2;255;10;0m",
blue => "\e[38;2;05;10;200m",
black => "\e[38;2;0;0;0m"
);
my @cards = flat (flat
<🂢 🂣 🂤 🂥 🂦 🂧 🂨 🂩 🂪 🂫 🂭 🂮 🂡
🃒 🃓 🃔 🃕 🃖 🃗 🃘 🃙 🃚 🃛 🃝 🃞 🃑>.map({ "{%c<black>}$_" }),
<🂲 🂳 🂴 🂵 🂶 🂷 🂸 🂹 🂺 🂻 🂽 🂾 🂱
🃂 🃃 🃄 🃅 🃆 🃇 🃈 🃉 🃊 🃋 🃍 🃎 🃁>.map({ "{%c<red>}$_" })
).batch(13).map({ .flat Z 2..14 })».map: { .[1] but .[0] };
my $back = "{%c<blue>}🂠";
my @won = <👈 👉>;
sub shuffle (@cards) { @cards.pick: * }
sub deal (@cards) { [@cards[0,*+2 … *], @cards[1,*+2 … *]] }
my ($rows, $cols) = qx/stty size/.words».Int; # get the terminal size
note "Terminal is only $cols characters wide, needs to be at least 80, 120 or more recommended."
and exit if $cols < 80;
sub clean-up {
reset-scroll-region;
show-cursor;
print-at $rows, 1, '';
print "\e[0m";
exit(0)
}
signal(SIGINT).tap: { clean-up() }
my @index = ($cols div 2 - 5, $cols div 2 + 4);
my @player = (deal shuffle @cards)».Array;
my $lose = False;
sub take (@player, Int $cards) {
if +@player >= $cards {
return @player.splice(0, $cards);
}
else {
$lose = True;
return @player.splice(0, +@player);
}
}
use Terminal::ANSI;
clear-screen;
hide-cursor;
# Set background color
print "\e[H\e[J\e[48;2;245;245;245m", ' ' xx $rows * $cols + 1;
# Add header
print-at 1, $cols div 2 - 1, "{%c<red>}WAR!";
print-at 2, 1, '━' x $cols;
my $row = 3;
my $height = $rows - $row - 2;
set-scroll-region($row, $height);
# footer
print-at $height + 1, 1, '━' x $cols;
my $round = 0;
my @round;
loop {
@round = [@player[0].&take(1)], [@player[1].&take(1)] unless +@round;
print-at $row, $cols div 2, "{%c<red>}┃";
print-at $row, @index[0], @round[0;0] // ' ';
print-at $row, @index[1], @round[1;0] // ' ';
if $lose {
if @player[0] < @player[1] {
print-at $row, $cols div 2 + 1, @won[1] unless +@round[1] == 1;
print-at $height + 3, $cols div 2 - 10, "{%c<red>} Player 1 is out of cards "
} else {
print-at $row, $cols div 2 - 2, @won[0] unless +@round[0] == 1;
print-at $height + 3, $cols div 2 - 10, "{%c<red>} Player 2 is out of cards "
}
}
if (@round[0].tail // 0) > (@round[1].tail // 0) {
print-at $row, $cols div 2 - 2, @won[0];
@player[0].append: flat (|@round[0],|@round[1]).pick: *;
@round = ();
}
elsif (@round[0].tail // 0) < (@round[1].tail // 0) {
print-at $row, $cols div 2 + 1, @won[1];
@player[1].append: flat (|@round[0],|@round[1]).pick: *;
@round = ();
}
else {
@round[0].append: @player[0].&take($war);
@round[1].append: @player[1].&take($war);
print-at $row, @index[0] - $_ * 2, ($_ %% $war) ?? @round[0; $_] !! $back for ^@round[0];
print-at $row, @index[1] + $_ * 2, ($_ %% $war) ?? @round[1; $_] !! $back for ^@round[1];
next
}
last if $lose;
print-at $height + 2, $cols div 2 - 4, "{%c<blue>} Round {++$round} ";
print-at $height + 2, $cols div 2 - 40, "{%c<blue>} Player 1: {+@player[0]} cards ";
print-at $height + 2, $cols div 2 + 21, "{%c<blue>} Player 2: {+@player[1]} cards ";
sleep $sleep if +$sleep;
if $row >= $height { scroll-up } else { ++$row }
}
# game over
print-at $height + 2, $cols div 2 - 40, "{%c<blue>} Player 1: {+@player[0] ?? '52' !! "{%c<red>}0"}{%c<blue>} cards ";
print-at $height + 2, $cols div 2 + 20, "{%c<blue>} Player 2: {+@player[1] ?? '52' !! "{%c<red>}0"}{%c<blue>} cards ";
clean-up; |
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.
| #REBOL | REBOL | doors: array/initial 100 'closed
repeat i 100 [
door: at doors i
forskip door i [change door either 'open = first door ['closed] ['open]]
] |
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #Wren | Wren | import "random" for Random
import "/queue" for Deque
var rand = Random.new()
var suits = ["♣", "♦", "♥", "♠"]
var faces = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" ]
var cards = List.filled(52, null)
for (i in 0..51) cards[i] = "%(faces[i%13])%(suits[(i/13).floor])"
var ranks = List.filled(52, 0)
for (i in 0..51) ranks[i] = i % 13
var war = Fn.new {
var deck = List.filled(52, 0)
for (i in 0..51) deck[i] = i
rand.shuffle(deck)
var hand1 = Deque.new()
var hand2 = Deque.new()
for (i in 0..25) {
hand1.pushFront(deck[2*i])
hand2.pushFront(deck[2*i+1])
}
while (hand1.count > 0 && hand2.count > 0) {
var card1 = hand1.popFront()
var card2 = hand2.popFront()
var played1 = [card1]
var played2 = [card2]
var numPlayed = 2
while (true) {
System.write("%(cards[card1])\t%(cards[card2])\t")
if (ranks[card1] > ranks[card2]) {
hand1.pushAllBack(played1)
hand1.pushAllBack(played2)
System.print("Player 1 takes the %(numPlayed) cards. Now has %(hand1.count).")
break
} else if (ranks[card1] < ranks[card2]) {
hand2.pushAllBack(played2)
hand2.pushAllBack(played1)
System.print("Player 2 takes the %(numPlayed) cards. Now has %(hand2.count).")
break
} else {
System.print("War!")
if (hand1.count < 2) {
System.print("Player 1 has insufficient cards left.")
hand2.pushAllBack(played2)
hand2.pushAllBack(played1)
hand2.pushAllBack(hand1)
hand1.clear()
break
}
if (hand2.count < 2) {
System.print("Player 2 has insufficient cards left.")
hand1.pushAllBack(played1)
hand1.pushAllBack(played2)
hand1.pushAllBack(hand2)
hand2.clear()
break
}
played1.add(hand1.popFront()) // face down card
card1 = hand1.popFront() // face up card
played1.add(card1)
played2.add(hand2.popFront()) // face down card
card2 = hand2.popFront() // face up card
played2.add(card2)
numPlayed = numPlayed + 4
System.print("? \t? \tFace down cards.")
}
}
}
if (hand1.count == 52) {
System.print("Player 1 wins the game!")
} else {
System.print("Player 2 wins the game!")
}
}
war.call() |
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.
| #Red | Red | Red [
Purpose: "100 Doors Problem (Perfect Squares)"
Author: "Barry Arthur"
Date: "07-Oct-2016"
]
doors: make vector! [char! 8 100]
repeat i 100 [change at doors i #"."]
repeat i 100 [
j: i
while [j <= 100] [
door: at doors j
change door either #"O" = first door [#"."] [#"O"]
j: j + i
]
]
repeat i 10 [
print copy/part at doors (i - 1 * 10 + 1) 10
]
|
http://rosettacode.org/wiki/War_card_game | War card game | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
Bicycle card company: War game site
Wikipedia: War (card game)
Related tasks:
Playing cards
Card shuffles
Deal cards for FreeCell
Poker hand_analyser
Go Fish
| #XPL0 | XPL0 | char Deck(52), \initial card deck (low 2 bits = suit)
Stack(2, 52); \each player's stack of cards (52 maximum)
int Inx(2), \index to last card (+1) for each stack
Top, \index to compared cards, = stack top if not war
Card, N, I, J, P, T;
char Suit, Rank;
proc MoveCard(To, From); \Move top card From Stack to bottom of To Stack
int To, From;
int Card, I;
[Card:= Stack(From, 0); \take top Card from From Stack
for I:= 0 to Inx(From)-2 do \shift remaining cards over
Stack(From, I):= Stack(From, I+1);
if Inx(From) > 0 then \remove From card from its Stack
Inx(From):= Inx(From)-1;
Stack(To, Inx(To)):= Card; \add Card to bottom of To Stack
if Inx(To) < 52 then \remove From card from its Stack
Inx(To):= Inx(To)+1;
];
[\\Suit:= "^C^D^E^F "; \IBM OEM card symbols aren't displayable on RC
Suit:= "HDCS ";
Rank:= "23456789TJQKA "; \T = 10
for Card:= 0 to 52-1 do \make a complete deck of cards
Deck(Card):= Card;
for N:= 0 to 10_000 do \shuffle the deck by swapping random locations
[I:= Ran(52); J:= Ran(52);
T:= Deck(I); Deck(I):= Deck(J); Deck(J):= T;
];
for N:= 0 to 52-1 do \deal deck into two stacks
[Card:= Deck(N);
I:= N/2;
P:= rem(0);
Stack(P, I):= Card;
];
Inx(0):= 52/2; Inx(1):= 52/2; \set indexes to last card +1
loop [for P:= 0 to 1 do \show both stacks of cards
[for I:= 0 to Inx(P)-1 do
[Card:= Stack(P, I); ChOut(0, Rank(Card>>2))];
CrLf(0);
for I:= 0 to Inx(P)-1 do
[Card:= Stack(P, I); ChOut(0, Suit(Card&3))];
CrLf(0);
];
if Inx(0)=0 or Inx(1)=0 then quit; \game over
Top:= 0; \compare card ranks (above 2-bit suits)
loop [if Stack(0, Top)>>2 = Stack(1, Top)>>2 then
[Text(0, "War!"); CrLf(0);
Top:= Top+2; \play a card down and a card up
]
else if Stack(0, Top)>>2 > Stack(1, Top)>>2 then
[for I:= 0 to Top do \move cards to Stack 0
[MoveCard(0, 0); MoveCard(0, 1)];
quit;
]
else [for I:= 0 to Top do \move cards to Stack 1
[MoveCard(1, 1); MoveCard(1, 0)];
quit;
];
];
T:= ChIn(1); \wait for keystroke (no key echo)
CrLf(0);
];
]
] |
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.
| #Relation | Relation |
relation door, state
set i = 1
while i <= 100
insert i, 1
set i = i+1
end while
set i = 2
while i <= 100
update state = 1-state where not (door mod i)
set i = i+1
end while
update state = "open" where state
update state = "closed" where state !== "open"
print
|
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.
| #Retro | Retro | :doors (n-) [ #1 repeat dup-pair n:square gt? 0; drop dup n:square n:put sp n:inc again ] do drop-pair ;
#100 doors |
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.
| #REXX | REXX | /*REXX pgm solves the 100 doors puzzle, doing it the hard way by opening/closing doors.*/
parse arg doors . /*obtain the optional argument from CL.*/
if doors=='' | doors=="," then doors=100 /*not specified? Then assume 100 doors*/
/* 0 = the door is closed. */
/* 1 = " " " open. */
door.=0 /*assume all doors are closed at start.*/
do #=1 for doors /*process a pass─through for all doors.*/
do j=# by # to doors /* ··· every Jth door from this point.*/
door.j= \door.j /*toggle the "openness" of the door. */
end /*j*/
end /*#*/
say 'After ' doors " passes, the following doors are open:"
say
do k=1 for doors
if door.k then say right(k, 20) /*add some indentation for the output. */
end /*k*/ /*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.
| #Ring | Ring | doors = list(100)
for i = 1 to 100
doors[i] = false
next
For pass = 1 To 100
For door = pass To 100
if doors[door] doors[door] = false else doors[door] = true ok
door += pass-1
Next
Next
For door = 1 To 100
see "Door (" + door + ") is "
If doors[door] see "Open" else see "Closed" ok
see nl
Next |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Ruby | Ruby | doors = Array.new(101,0)
print "Open doors "
(1..100).step(){ |i|
(i..100).step(i) { |d|
doors[d] = doors[d]^= 1
if i == d and doors[d] == 1 then
print "#{i} "
end
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Run_BASIC | Run BASIC | dim doors(100)
print "Open doors ";
for i = 1 to 100
for door = i to 100 step i
doors(door) = (doors(door) <> 1)
if i = door and doors(door) = 1 then print i;" ";
next door
next i |
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.
| #Rust | Rust | fn main() {
let mut door_open = [false; 100];
for pass in 1..101 {
let mut door = pass;
while door <= 100 {
door_open[door - 1] = !door_open[door - 1];
door += pass;
}
}
for (i, &is_open) in door_open.iter().enumerate() {
println!("Door {} is {}.", i + 1, if is_open {"open"} else {"closed"});
}
} |
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.
| #S-BASIC | S-BASIC |
$constant DOOR_OPEN = 1
$constant DOOR_CLOSED = 0
$constant MAX_DOORS = 100
var i, j = integer
dim integer doors(MAX_DOORS)
rem - all doors are initially closed
for i = 1 to MAX_DOORS
doors(i) = DOOR_CLOSED
next i
rem - cycle through at increasing intervals and flip doors
for i = 1 to MAX_DOORS
for j = i to MAX_DOORS step i
doors(j) = 1 - doors(j)
next j
next i
rem - report results
print "The open doors are:"
for i = 1 to MAX_DOORS
if doors(i) = DOOR_OPEN then
print i;
next i
end |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #S-lang | S-lang | variable door,
isOpen = Char_Type [101],
pass;
for (door = 1; door <= 100; door++) {
isOpen[door] = 0;
}
for (pass = 1; pass <= 100; pass++) {
for (door = pass; door <= 100; door += pass) {
isOpen[door] = not isOpen[door];
}
}
for (door = 1; door <= 100; door++) {
if (isOpen[door]) {
print("Door " + string(door) + ":open");
} else {
print("Door " + string(door) + ":close");
}
} |
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.
| #Salmon | Salmon | variable open := <<(* --> false)>>;
for (pass; 1; pass <= 100)
for (door_num; pass; door_num <= 100; pass)
open[door_num] := !(open[door_num]);;;
iterate (door_num; [1...100])
print("Door ", door_num, " is ",
(open[door_num] ? "open.\n" : "closed.\n"));; |
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.
| #SAS | SAS | data _null_;
open=1;
close=0;
array Door{100};
do Pass = 1 to 100;
do Current = Pass to 100 by Pass;
if Door{Current} ne open
then Door{Current} = open;
else Door{Current} = close;
end;
end;
NumberOfOpenDoors = sum(of Door{*});
put "Number of Open Doors: " NumberOfOpenDoors;
run; |
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.
| #Sather | Sather | class MAIN is
main is
doors :ARRAY{BOOL} := #(100);
loop
pass::= doors.ind!;
loop
i::= pass.stepto!(doors.size - 1, pass + 1);
doors[i] := ~doors[i];
end;
end;
loop
#OUT + (doors.ind! + 1) + " " + doors.elt! + "\n";
end;
end;
end; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Scala | Scala | for { i <- 1 to 100
r = 1 to 100 map (i % _ == 0) reduceLeft (_^_)
} println (i +" "+ (if (r) "open" else "closed")) |
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.
| #Scheme | Scheme | (define *max-doors* 100)
(define (show-doors doors)
(let door ((i 0)
(l (vector-length doors)))
(cond ((= i l)
(newline))
(else
(printf "~nDoor ~a is ~a"
(+ i 1)
(if (vector-ref doors i) "open" "closed"))
(door (+ i 1) l)))))
(define (flip-doors doors)
(define (flip-all i)
(cond ((> i *max-doors*) doors)
(else
(let flip ((idx (- i 1)))
(cond ((>= idx *max-doors*)
(flip-all (+ i 1)))
(else
(vector-set! doors idx (not (vector-ref doors idx)))
(flip (+ idx i))))))))
(flip-all 1))
(show-doors (flip-doors (make-vector *max-doors* #f))) |
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.
| #Scilab | Scilab | doors=zeros(1,100);
for i = 1:100
for j = i:i:100
doors(j) = ~doors(j);
end
end
for i = 1:100
if ( doors(i) )
s = "open";
else
s = "closed";
end
printf("%d %s\n", i, s);
end |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Scratch | Scratch | $ include "seed7_05.s7i";
const proc: main is func
local
var array boolean: doorOpen is 100 times FALSE;
var integer: pass is 0;
var integer: index is 0;
var array[boolean] string: closedOrOpen is [boolean] ("closed", "open");
begin
for pass range 1 to 100 do
for key index range doorOpen do
if index rem pass = 0 then
doorOpen[index] := not doorOpen[index];
end if;
end for;
end for;
for key index range doorOpen do
write(index lpad 3 <& " is " <& closedOrOpen[doorOpen[index]] rpad 7);
if index rem 5 = 0 then
writeln;
end if;
end for;
end func; |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var array boolean: doorOpen is 100 times FALSE;
var integer: pass is 0;
var integer: index is 0;
var array[boolean] string: closedOrOpen is [boolean] ("closed", "open");
begin
for pass range 1 to 100 do
for key index range doorOpen do
if index rem pass = 0 then
doorOpen[index] := not doorOpen[index];
end if;
end for;
end for;
for key index range doorOpen do
write(index lpad 3 <& " is " <& closedOrOpen[doorOpen[index]] rpad 7);
if index rem 5 = 0 then
writeln;
end if;
end for;
end func; |
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.
| #SenseTalk | SenseTalk |
put false repeated 100 times as a list into Doors100
repeat 1 to 100
set step to it
repeat step to 100 by step
set newValue to not item it of Doors100
set item it of Doors100 to newValue
end repeat
end repeat
put the counter for each item of Doors100 which is true
|
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.
| #SequenceL | SequenceL |
import <Utilities/Sequence.sl>;
main:=
let
doors := flipDoors(duplicate(false, 100), 1);
open[i] := i when doors[i];
in
open;
flipDoors(doors(1), count) :=
let
newDoors[i] := not doors[i] when i mod count = 0 else doors[i];
in
doors when count >= 100 else flipDoors(newDoors, count + 1);
|
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.
| #SETL | SETL | program hundred_doors;
const toggle := {['open', 'closed'], ['closed', 'open']};
doorStates := ['closed'] * 100;
(for interval in [1..100])
doorStates := [if i mod interval = 0 then
toggle(prevState) else
prevState end:
prevState = doorStates(i)];
end;
(for finalState = doorStates(i))
print('door', i, 'is', finalState);
end;
end program; |
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.
| #SheerPower_4GL | SheerPower 4GL |
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! I n i t i a l i z a t i o n
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
doors% = 100
dim doorArray?(doors%)
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! M a i n L o g i c A r e a
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Initialize Array
for index% = 1 to doors%
doorArray?(index%) = false
next index%
// Execute routine
toggle_doors
// Print results
for index% = 1 to doors%
if doorArray?(index%) = true then print index%, ' is open'
next index%
stop
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! R o u t i n e s
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
routine toggle_doors
for index_outer% = 1 to doors%
for index_inner% = 1 to doors%
if mod(index_inner%, index_outer%) = 0 then
doorArray?(index_inner%) = not doorArray?(index_inner%)
end if
next index_inner%
next index_outer%
end routine
end
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Sidef | Sidef | var doors = []
{ |pass|
{ |i|
if (pass `divides` i) {
doors[i] := false -> not!
}
} << 1..100
} << 1..100
{ |i|
say ("Door %3d is %s" % (i, doors[i] ? 'open' : 'closed'))
} << 1..100 |
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.
| #Simula | Simula | BEGIN
INTEGER LIMIT = 100, door, stride;
BOOLEAN ARRAY DOORS(1:LIMIT);
TEXT intro;
FOR stride := 1 STEP 1 UNTIL LIMIT DO
FOR door := stride STEP stride UNTIL LIMIT DO
DOORS(door) := NOT DOORS(door);
intro :- "All doors closed but ";
FOR door := 1 STEP 1 UNTIL LIMIT DO
IF DOORS(door) THEN BEGIN
OUTTEXT(intro); OUTINT(door, 0); intro :- ", "
END;
OUTIMAGE
END. |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Slate | Slate | define: #a -> (Array newSize: 100).
a infect: [| :_ | False].
a keysDo: [| :pass |
pass to: a indexLast by: pass do: [| :door |
a at: door infect: #not `er]].
a keysAndValuesDo: [| :door :isOpen |
inform: 'door #' ; door ; ' is ' ; (isOpen ifTrue: ['open'] ifFalse: ['closed'])]. |
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.
| #Smalltalk | Smalltalk | |a|
a := Array new: 100 .
1 to: 100 do: [ :i | a at: i put: false ].
1 to: 100 do: [ :pass |
pass to: 100 by: pass do: [ :door |
a at: door put: (a at: door) not .
]
].
"output"
1 to: 100 do: [ :door |
( 'door #%1 is %2' %
{ door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl
] |
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.
| #smart_BASIC | smart BASIC | x=1!y=3!z=0
PRINT "Open doors: ";x;" ";
DO
z=x+y
PRINT z;" ";
x=z
y=y+2
UNTIL z>=100
END |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #SNOBOL4 | SNOBOL4 |
DEFINE('PASS(A,I),O') :(PASS.END)
PASS O = 0
PASS.LOOP O = O + I
EQ(A<O>,1) :S(PASS.1)F(PASS.0)
PASS.0 A<O> = 1 :S(PASS.LOOP)F(RETURN)
PASS.1 A<O> = 0 :S(PASS.LOOP)F(RETURN)
PASS.END
MAIN D = ARRAY(100,0)
I = 0
MAIN.LOOP I = LE(I,100) I + 1 :F(OUTPUT)
PASS(D,I) :(MAIN.LOOP)
OUTPUT I = 1 ; OPEN = 'Opened doors are: '
OUTPUT.LOOP OPEN = OPEN EQ(D<I>,1) " " I
I = LE(I,100) I + 1 :S(OUTPUT.LOOP)F(OUTPUT.WRITE)
OUTPUT.WRITE OUTPUT = OPEN
END
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Sparkling | Sparkling | /* declare the variables */
var isOpen = {};
var pass, door;
/* initialize the doors */
for door = 0; door < 100; door++ {
isOpen[door] = true;
}
/* do the 99 remaining passes */
for pass = 1; pass < 100; ++pass {
for door = pass; door < 100; door += pass+1 {
isOpen[door] = !isOpen[door];
}
}
/* print the results */
var states = { true: "open", false: "closed" };
for door = 0; door < 100; door++ {
printf("Door #%d is %s.\n", door+1, states[isOpen[door]]);
} |
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.
| #Spin | Spin | con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub init
ser.start(31, 30, 0, 115200)
doors
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
var
byte door[101] ' waste one byte by using only door[1..100]
pri doors | i,j
repeat i from 1 to 100
repeat j from i to 100 step i
not door[j]
ser.str(string("Open doors: "))
repeat i from 1 to 100
if door[i]
ser.dec(i)
ser.tx(32)
ser.str(string(13,10)) |
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.
| #SQL | SQL |
DECLARE @sqr INT,
@i INT,
@door INT;
SELECT @sqr =1,
@i = 3,
@door = 1;
WHILE(@door <=100)
BEGIN
IF(@door = @sqr)
BEGIN
PRINT 'Door ' + RTRIM(CAST(@door AS CHAR)) + ' is open.';
SET @sqr= @sqr+@i;
SET @i=@i+2;
END
ELSE
BEGIN
PRINT 'Door ' + RTRIM(CONVERT(CHAR,@door)) + ' is closed.';
END
SET @door = @door + 1
END
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #SQL_PL | SQL PL |
--#SET TERMINATOR @
SET SERVEROUTPUT ON @
BEGIN
DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY [100];
DECLARE DOORS DOORS_ARRAY;
DECLARE I SMALLINT;
DECLARE J SMALLINT;
DECLARE STATUS CHAR(10);
DECLARE SIZE SMALLINT DEFAULT 100;
-- Initializes the array, with all spaces (doors) as false (closed).
SET I = 1;
WHILE (I <= SIZE) DO
SET DOORS[I] = FALSE;
SET I = I + 1;
END WHILE;
-- Processes the doors.
SET I = 1;
WHILE (I <= SIZE) DO
SET J = 1;
WHILE (J <= SIZE) DO
IF (MOD(J, I) = 0) THEN
IF (DOORS[J] = TRUE) THEN
SET DOORS[J] = FALSE;
ELSE
SET DOORS[J] = TRUE;
END IF;
END IF;
SET J = J + 1;
END WHILE;
SET I = I + 1;
END WHILE;
-- Prints the final status o the doors.
SET I = 1;
WHILE (I <= SIZE) DO
SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END);
CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS);
SET I = I + 1;
END WHILE;
END @
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Standard_ML | Standard ML |
datatype Door = Closed | Opened
fun toggle Closed = Opened
| toggle Opened = Closed
fun pass (step, doors) = List.map (fn (index, door) => if (index mod step) = 0
then (index, toggle door)
else (index, door))
doors
(* [1..n] *)
fun runs n = List.tabulate (n, fn k => k+1)
fun run n =
let
val initialdoors = List.tabulate (n, fn i => (i+1, Closed))
val counter = runs n
in
foldl pass initialdoors counter
end
fun opened_doors n = List.mapPartial (fn (index, Closed) => NONE
| (index, Opened) => SOME (index))
(run n)
|
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.
| #Stata | Stata | clear
set obs 100
gen doors=0
gen index=_n
forvalues i=1/100 {
quietly replace doors=!doors if mod(_n,`i')==0
}
list index if doors, noobs noheader
+-------+
| 1 |
| 4 |
| 9 |
| 16 |
| 25 |
|-------|
| 36 |
| 49 |
| 64 |
| 81 |
| 100 |
+-------+ |
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.
| #SuperCollider | SuperCollider | (
var n = 100, doors = false ! n;
var pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };
(1..n-1).do(pass);
doors.selectIndices { |open| open }; // all are closed except [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]
) |
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.
| #Swift | Swift | /* declare enum to identify the state of a door */
enum DoorState : String {
case Opened = "Opened"
case Closed = "Closed"
}
/* declare list of doors state and initialize them */
var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)
/* do the 100 passes */
for i in 1...100 {
/* map on a strideTo instance to only visit the needed doors on each iteration */
map(stride(from: i - 1, to: 100, by: i)) {
doorsStateList[$0] = doorsStateList[$0] == .Opened ? .Closed : .Opened
}
}
/* print the results */
for (index, item) in enumerate(doorsStateList) {
println("Door \(index+1) is \(item.rawValue)")
} |
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.
| #Tailspin | Tailspin |
source hundredDoors
@: [ 1..100 -> 0 ];
templates toggle
def jump: $;
$jump..100:$jump -> \(when <?($@hundredDoors($) <=0>)> do @hundredDoors($): 1; otherwise @hundredDoors($): 0;\) -> !VOID
end toggle
1..100 -> toggle -> !VOID
$@ -> \[i](<=1> ' $i;' !\) !
end hundredDoors
$hundredDoors -> 'Open doors:$...;' -> !OUT::write
|
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.
| #Tcl | Tcl | package require Tcl 8.5
set n 100
set doors [concat - [lrepeat $n 0]]
for {set step 1} {$step <= $n} {incr step} {
for {set i $step} {$i <= $n} {incr i $step} {
lset doors $i [expr { ! [lindex $doors $i]}]
}
}
for {set i 1} {$i <= $n} {incr i} {
puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]]
} |
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.
| #TI-83_BASIC | TI-83 BASIC | seq(0,X,1,100
For(X,1,100
0 or Ans-not(fPart(cumSum(1 or Ans)/A
End
Pause Ans
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.