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/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#GUISS
GUISS
Start,Programs,Accessories,Notepad
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
#Go
Go
package main   import ( "fmt" "strings" )   func wrap(text string, lineWidth int) (wrapped string) { words := strings.Fields(text) if len(words) == 0 { return } wrapped = words[0] spaceLeft := lineWidth - len(wrapped) for _, word := range words[1:] { if len(word)+1 > spaceLeft { wrapped += "\n" + word spaceLeft = lineWidth - len(word) } else { wrapped += " " + word spaceLeft -= 1 + len(word) } } return }   var 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.`   func main() { fmt.Println("wrapped at 80:") fmt.Println(wrap(frog, 80)) fmt.Println("wrapped at 72:") fmt.Println(wrap(frog, 72)) }
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Phix
Phix
with javascript_semantics constant {hchars,hsubs} = columnize({{"<","&lt;"}, {">","&gt;"}, {"&","&amp;"}, {"\"","&quot;"}, {"\'","&apos;"}}) function xmlquote_all(sequence s) for i=1 to length(s) do s[i] = substitute_all(s[i],hchars,hsubs) end for return s end function function xml_CharacterRemarks(sequence data) string res = "<CharacterRemarks>\n" for i=1 to length(data) do res &= sprintf(" <CharacterName=\"%s\">%s</Character>\n",xmlquote_all(data[i])) end for return res & "</CharacterRemarks>\n" end function constant testset = { {"April", "Bubbly: I'm > Tam and <= Emily"}, {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, {"Emily", "Short & shrift"} } printf(1,xml_CharacterRemarks(testset)) -- Sample output: -- <CharacterRemarks> -- <CharacterName="April">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character> -- <CharacterName="Tam O&apos;Shanter">Burns: &quot;When chapman billies leave the street ...&quot;</Character> -- <CharacterName="Emily">Short &amp; shrift</Character> -- </CharacterRemarks>
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#newLISP
newLISP
  (set 'xml-input "<Students> <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /> <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /> <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /> <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\"> <Pet Type=\"dog\" Name=\"Rover\" /> </Student> <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" /> </Students>")   (set 'sexp (xml-parse xml-input))   (dolist (x (ref-all "Name" sexp)) (if (= (length x) 6) (println (last (sexp (chop x))))))  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Vlang
Vlang
// Arrays, in V // Tectonics: v run arrays.v module main   // A little bit about V variables. V does not allow uninitialized data. // If an identifier exists, there is a valid value. "Empty" arrays have // values in all positions, and V provides defaults for base types if not // explicitly specified. E.g. 0 for numbers, `0` for rune, "" for strings.   // V uses := for definition and initialization, and = for assignment   // starts here, V programs start by invoking the "main" function. pub fn main() {   // Array definition in source literal form (immutable) array := [1,2,3,4] // print first element, 0 relative indexing println("array: $array") println("array[0]: ${array[0]}") // immutable arrays cannot be modified after initialization // array[1] = 5, would fail to compile with a message it needs mut   // Dynamic arrays have some property fields println("array.len: $array.len") println("array.cap: $array.cap")   // array specs are [n]type{properties} // Dynamic array definition, initial default values, "" for string mut array2 := []string{} // Append an element, using lessless array2 << "First" println("array2[0]: ${array2[0]}") println("array2.len: $array2.len") println("array2.cap: $array2.cap")   // Fixed array definition, capacity is fixed (! suffix), mutable entries mut array3 := ["First", "Second", "Third"]! println("array3: $array3") array3[array3.len-1] = "Last" println("array3: $array3") println("array3.len: $array3.len")   // Advanced, array intiailization using non default value mut array4 := [4]int{init: 42} array4[2] = 21 println("array4: $array4")   // Arrays can be sliced, creating a copy mut array5 := array4[0..3] println("array5: $array5") array5[2] = 10 println("array4: $array4") println("array5: $array5") }
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.
#Objeck
Objeck
  bundle Default { class Doors { function : Main(args : String[]) ~ Nil { doors := Bool->New[100];   for(pass := 0; pass < 10; pass += 1;) { doors[(pass + 1) * (pass + 1) - 1] := true; };   for(i := 0; i < 100; i += 1;) { IO.Console->GetInstance()->Print("Door #")->Print(i + 1)->Print(" is "); if(doors[i]) { "open."->PrintLine(); } else { "closed."->PrintLine(); }; }; } } }  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => take(25, weirds());     // weirds :: Gen [Int] function* weirds() { let x = 1, i = 1; while (true) { x = until(isWeird, succ, x) console.log(i.toString() + ' -> ' + x) yield x; x = 1 + x; i = 1 + i; } }     // isWeird :: Int -> Bool const isWeird = n => { const ds = descProperDivisors(n), d = sum(ds) - n; return 0 < d && !hasSum(d, ds) };   // hasSum :: Int -> [Int] -> Bool const hasSum = (n, xs) => { const go = (n, xs) => 0 < xs.length ? (() => { const h = xs[0], t = xs.slice(1); return n < h ? ( go(n, t) ) : ( n == h || hasSum(n - h, t) || hasSum(n, t) ); })() : false; return go(n, xs); };     // descProperDivisors :: Int -> [Int] const descProperDivisors = n => { const rRoot = Math.sqrt(n), intRoot = Math.floor(rRoot), blnPerfect = rRoot === intRoot, lows = enumFromThenTo(intRoot, intRoot - 1, 1) .filter(x => (n % x) === 0); return ( reverse(lows) .slice(1) .map(x => n / x) ).concat((blnPerfect ? tail : id)(lows)) };     // GENERIC FUNCTIONS ----------------------------     // enumFromThenTo :: Int -> Int -> Int -> [Int] const enumFromThenTo = (x1, x2, y) => { const d = x2 - x1; return Array.from({ length: Math.floor(y - x2) / d + 2 }, (_, i) => x1 + (d * i)); };   // id :: a -> a const id = x => x;   // reverse :: [a] -> [a] const reverse = xs => 'string' !== typeof xs ? ( xs.slice(0).reverse() ) : xs.split('').reverse().join('');   // succ :: Enum a => a -> a const succ = x => 1 + x;   // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0);   // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : [];   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; };   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Pascal
Pascal
  program WritePascal;   const i64: int64 = 1055120232691680095; (* This defines "Pascal" *) cc: array[-1..15] of string = (* Here are all string-constants *) ('_______v---', '__', '\_', '___', '\__', ' ', ' ', ' ', ' ', '/ ', ' ', '_/ ', '\/ ', ' _', '__', ' _', ' _'); var x, y: integer;   begin for y := 0 to 7 do begin Write(StringOfChar(cc[(not y and 1) shl 2][1], 23 - y and 6)); Write(cc[((i64 shr (y div 2)) and 1) shl 3 + (not y and 1) shl 2 + 2]); for x := 0 to 15 do Write(cc[((i64 shr ((x and 15) * 4 + y div 2)) and 1) + ((i64 shr (((x + 1) and 15) * 4 + y div 2)) and 1) shl 3 + (x mod 3) and 2 + (not y and 1) shl 2]); writeln(cc[1 + (not y and 1) shl 2] + cc[(not y and 1) shl 3 - 1]); 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++.
#Clojure
Clojure
  (second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "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++.
#CoffeeScript
CoffeeScript
  http = require 'http'   CONFIG = host: 'tycho.usno.navy.mil' path: '/cgi-bin/timer.pl'   # Web scraping code tends to be brittle, and this is no exception. # The tycho time page does not use highly structured markup, so # we do a real dirty scrape. scrape_tycho_ust_time = (text) -> for line in text.split '\n' matches = line.match /(.*:\d\d UTC)/ if matches console.log matches[0].replace '<BR>', '' return throw Error("unscrapable page!")   # This is low-level-ish code to get data from a URL. It's # pretty general purpose, so you'd normally tuck this away # in a library (or use somebody else's library). wget = (host, path, cb) -> options = host: host path: path headers: "Cache-Control": "max-age=0"   req = http.request options, (res) -> s = '' res.on 'data', (chunk) -> s += chunk res.on 'end', -> cb s req.end()   # Do our web scrape do -> wget CONFIG.host, CONFIG.path, (data) -> scrape_tycho_ust_time data  
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
#Clojure
Clojure
(defn count-words [file n] (->> file slurp clojure.string/lower-case (re-seq #"\w+") frequencies (sort-by val >) (take n)))
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. WordFrequency. AUTHOR. Bill Gunshannon. DATE-WRITTEN. 30 Jan 2020. ************************************************************ ** Program Abstract: ** Given a text file and an integer n, print the n most ** common words in the file (and the number of their ** occurrences) in decreasing frequency. ** ** A file named Parameter.txt provides this information. ** Format is: ** 12345678901234567890123456789012345678901234567890 ** |------------------|----| ** ^^^^^^^^^^^^^^^^ ^^^^ ** | | ** Source Text File Number of words with count ** 20 Characters 5 digits with leading zeroes ** ** ************************************************************   ENVIRONMENT DIVISION.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Parameter-File ASSIGN TO "Parameter.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Input-File ASSIGN TO Source-Text ORGANIZATION IS LINE SEQUENTIAL. SELECT Word-File ASSIGN TO "Word.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Output-File ASSIGN TO "Output.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Print-File ASSIGN TO "Printer.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Sort-File ASSIGN TO DISK.   DATA DIVISION.   FILE SECTION.   FD Parameter-File DATA RECORD IS Parameter-Record. 01 Parameter-Record. 05 Source-Text PIC X(20). 05 How-Many PIC 99999.   FD Input-File DATA RECORD IS Input-Record. 01 Input-Record. 05 Input-Line PIC X(80).   FD Word-File DATA RECORD IS Word-Record. 01 Word-Record. 05 Input-Word PIC X(20).   FD Output-File DATA RECORD IS Output-Rec. 01 Output-Rec. 05 Output-Rec-Word PIC X(20). 05 Output-Rec-Word-Cnt PIC 9(5).   FD Print-File DATA RECORD IS Print-Rec. 01 Print-Rec. 05 Print-Rec-Word PIC X(20). 05 Print-Rec-Word-Cnt PIC 9(5).   SD Sort-File. 01 Sort-Rec. 05 Sort-Word PIC X(20). 05 Sort-Word-Cnt PIC 9(5).     WORKING-STORAGE SECTION.   01 Eof PIC X VALUE 'F'. 01 InLine PIC X(80). 01 Word1 PIC X(20). 01 Current-Word PIC X(20). 01 Current-Word-Cnt PIC 9(5). 01 Pos PIC 99 VALUE 1. 01 Cnt PIC 99. 01 Report-Rank. 05 IRank PIC 99999 VALUE 1. 05 Rank PIC ZZZZ9.   PROCEDURE DIVISION.   Main-Program. ** ** Read the Parameters ** OPEN INPUT Parameter-File. READ Parameter-File. CLOSE Parameter-File.   ** ** Open Files for first stage ** OPEN INPUT Input-File. OPEN OUTPUT Word-File.   ** ** Pare\se the Source Text into a file of invidual words ** PERFORM UNTIL Eof = 'T' READ Input-File AT END MOVE 'T' TO Eof END-READ   PERFORM Parse-a-Words   MOVE SPACES TO Input-Record MOVE 1 TO Pos END-PERFORM.   ** ** Cleanup from the first stage ** CLOSE Input-File Word-File   ** ** Sort the individual words in alphabetical order ** SORT Sort-File ON ASCENDING KEY Sort-Word USING Word-File GIVING Word-File.   ** ** Count each time a word is used ** PERFORM Collect-Totals.   ** ** Sort data by number of usages per word ** SORT Sort-File ON DESCENDING KEY Sort-Word-Cnt USING Output-File GIVING Print-File.   ** ** Show the work done ** OPEN INPUT Print-File. DISPLAY " Rank Word Frequency" PERFORM How-Many TIMES READ Print-File MOVE IRank TO Rank DISPLAY Rank " " Print-Rec ADD 1 TO IRank END-PERFORM.   ** ** Cleanup ** CLOSE Print-File. CALL "C$DELETE" USING "Word.txt" ,0 CALL "C$DELETE" USING "Output.txt" ,0   STOP RUN.     Parse-a-Words. INSPECT Input-Record CONVERTING '-.,"();:/[]{}!?|' TO SPACE PERFORM UNTIL Pos > FUNCTION STORED-CHAR-LENGTH(Input-Record)     UNSTRING Input-Record DELIMITED BY SPACE INTO Word1 WITH POINTER Pos TALLYING IN Cnt MOVE FUNCTION TRIM(FUNCTION LOWER-CASE(Word1)) TO Word-Record   IF Word-Record NOT EQUAL SPACES AND Word-Record IS ALPHABETIC THEN WRITE Word-Record END-IF   END-PERFORM.   Collect-Totals. MOVE 'F' to Eof OPEN INPUT Word-File OPEN OUTPUT Output-File READ Word-File MOVE Input-Word TO Current-Word MOVE 1 to Current-Word-Cnt PERFORM UNTIL Eof = 'T' READ Word-File AT END MOVE 'T' TO Eof END-READ   IF FUNCTION TRIM(Word-Record) EQUAL FUNCTION TRIM(Current-Word) THEN ADD 1 to Current-Word-Cnt ELSE MOVE Current-Word TO Output-Rec-Word MOVE Current-Word-Cnt TO Output-Rec-Word-Cnt WRITE Output-Rec MOVE 1 to Current-Word-Cnt MOVE Word-Record TO Current-Word MOVE SPACES TO Input-Record END-IF   END-PERFORM. CLOSE Word-File Output-File. END-PROGRAM.  
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#FreeBASIC
FreeBASIC
#define MAXX 319 #define MAXY 199   enum state E=0, C=8, H=9, T=4 'doubles as colours: black, grey, bright blue, red end enum   dim as uinteger world(0 to 1, 0 to MAXX, 0 to MAXY), active = 0, buffer = 1 dim as double rate = 1./3. 'seconds per frame dim as double tick dim as uinteger x, y   function turn_on( world() as unsigned integer, x as uinteger, y as uinteger, a as uinteger ) as boolean dim as ubyte n = 0 dim as integer qx, qy for qx = -1 to 1 for qy = -1 to 1 if qx=0 andalso qy=0 then continue for if world(a,(x+qx+MAXX+1) mod (MAXX+1), (y+qy+MAXY+1) mod (MAXY+1))=H then n=n+1 'handles wrap-around next qy next qx if n=1 then return true if n=2 then return true return false end function   'generate sample map   for x=20 to 30 world(active, x, 20) = C world(active, x, 24) = C next x world(active, 24, 24 ) = E world(active, 20, 21 ) = C world(active, 20, 23 ) = C world(active, 24, 21 ) = C world(active, 23, 22 ) = C world(active, 24, 22 ) = C world(active, 25, 22 ) = C world(active, 24, 23 ) = C world(active, 20, 20 ) = T world(active, 21, 20 ) = H world(active, 21, 24 ) = T world(active, 20, 24 ) = H   screen 12   do tick = timer for x = 0 to 319 for y = 0 to 199 pset (x,y), world(active, x, y) if world(active,x,y) = E then world(buffer,x,y) = E 'empty cells stay empty if world(active,x,y) = H then world(buffer,x,y) = T 'electron heads turn into electron tails if world(active,x,y) = T then world(buffer,x,y) = C 'electron tails revert to conductors if world(active,x,y) = C then if turn_on(world(),x,y,active) then world(buffer,x,y) = H 'maybe electron heads spread else world(buffer,x,y) = C 'otherwise condutor remains conductor end if end if next y next x while tick + rate > timer wend cls buffer = 1 - buffer active = 1 - buffer loop
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#TXR
TXR
/* window_creation_x11.wren */   var KeyPressMask = 1 << 0 var ExposureMask = 1 << 15 var KeyPress = 2 var Expose = 12   foreign class XGC { construct default(display, screenNumber) {} }   foreign class XEvent { construct new() {}   foreign eventType }   foreign class XDisplay { construct openDisplay(displayName) {}   foreign defaultScreen()   foreign rootWindow(screenNumber)   foreign blackPixel(screenNumber)   foreign whitePixel(screenNumber)   foreign selectInput(w, eventMask)   foreign mapWindow(w)   foreign closeDisplay()   foreign nextEvent(eventReturn)   foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)   foreign fillRectangle(d, gc, x, y, width, height)   foreign drawString(d, gc, x, y, string, length) }   var xd = XDisplay.openDisplay("") if (xd == 0) { System.print("Cannot open display.") return } var s = xd.defaultScreen() var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 100, 100, 1, xd.blackPixel(s), xd.whitePixel(s)) xd.selectInput(w, ExposureMask | KeyPressMask) xd.mapWindow(w) var msg = "Hello, World!" var e = XEvent.new() while (true) { xd.nextEvent(e) var gc = XGC.default(xd, s) if (e.eventType == Expose) { xd.fillRectangle(w, gc, 20, 20, 10, 10) xd.drawString(w, gc, 10, 50, msg, msg.count) } if (e.eventType == KeyPress) break } xd.closeDisplay()
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Haskell
Haskell
import Graphics.HGL   aWindow = runGraphics $ withWindow_ "Rosetta Code task: Creating a window" (300, 200) $ \ w -> do drawInWindow w $ text (100, 100) "Hello World" getKey w
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#HicEst
HicEst
WINDOW(WINdowhandle=handle, Width=80, Height=-400, X=1, Y=1/2, TItle="Rosetta Window_creation Example") ! window units: as pixels < 0, as relative window size 0...1, ascurrent character sizes > 1   WRITE(WINdowhandle=handle) '... some output ...'
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
#Groovy
Groovy
def wordWrap(text, length = 80) { def sb = new StringBuilder() def line = ''   text.split(/\s/).each { word -> if (line.size() + word.size() > length) { sb.append(line.trim()).append('\n') line = '' } line += " $word" } sb.append(line.trim()).toString() }
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#PicoLisp
PicoLisp
(load "@lib/xml.l")   (de characterRemarks (Names Remarks) (xml (cons 'CharacterRemarks NIL (mapcar '((Name Remark) (list 'Character (list (cons 'name Name)) Remark) ) Names Remarks ) ) ) )   (characterRemarks '("April" "Tam O'Shanter" "Emily") (quote "I'm > Tam and <= Emily" "Burns: \"When chapman billies leave the street ..." "Short & shrift" ) )
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#PureBasic
PureBasic
DataSection dataItemCount: Data.i 3   names: Data.s "April", "Tam O'Shanter", "Emily"   remarks: Data.s "Bubbly: I'm > Tam and <= Emily", ~"Burns: \"When chapman billies leave the street ...\"", "Short & shrift" EndDataSection   Structure characteristic name.s remark.s EndStructure   NewList didel.characteristic() Define item.s, numberOfItems, i   Restore dataItemCount Read.i numberOfItems   ;add names Restore names For i = 1 To numberOfItems AddElement(didel()) Read.s item didel()\name = item Next   ;add remarks ResetList(didel()) FirstElement(didel()) Restore remarks: For i = 1 To numberOfItems Read.s item didel()\remark = item NextElement(didel()) Next   Define xml, mainNode, itemNode ResetList(didel()) FirstElement(didel()) xml = CreateXML(#PB_Any) mainNode = CreateXMLNode(RootXMLNode(xml), "CharacterRemarks") ForEach didel() itemNode = CreateXMLNode(mainNode, "Character") SetXMLAttribute(itemNode, "name", didel()\name) SetXMLNodeText(itemNode, didel()\remark) Next FormatXML(xml, #PB_XML_ReFormat | #PB_XML_WindowsNewline | #PB_XML_ReIndent)   If OpenConsole() PrintN(ComposeXML(xml, #PB_XML_NoDeclaration)) Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Nim
Nim
import xmlparser, xmltree, streams   let doc = newStringStream """<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students>"""   for i in doc.parseXml.findAll "Student": echo i.attr "Name"
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Objeck
Objeck
  use XML;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { in := String->New(); in->Append("<Students>"); in->Append("<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"); in->Append("<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />"); in->Append("<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />"); in->Append("<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">"); in->Append("<Pet Type=\"dog\" Name=\"Rover\" />"); in->Append("</Student>"); in->Append("<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" /></Students>");   parser := XmlParser->New(in); if(parser->Parse()) { root := parser->GetRoot(); children := root->GetChildren("Student"); each(i : children) { child : XMLElement := children->Get(i)->As(XMLElement); XMLElement->DecodeString(child->GetAttribute("Name"))->PrintLine(); }; }; } } }  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Wee_Basic
Wee Basic
dim array$(2) let array$(1)="Hello!" let array$(2)="Goodbye!" print 1 array$(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.
#Objective-C
Objective-C
  @import Foundation;   int main(int argc, const char * argv[]) { @autoreleasepool {   // Create a mutable array NSMutableArray *doorArray = [@[] mutableCopy];   // Fill the doorArray with 100 closed doors for (NSInteger i = 0; i < 100; ++i) { doorArray[i] = @NO; }   // Do the 100 passes for (NSInteger pass = 0; pass < 100; ++pass) { for (NSInteger door = pass; door < 100; door += pass+1) { doorArray[door] = [doorArray[door] isEqual: @YES] ? @NO : @YES; } }   // Print the results [doorArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj isEqual: @YES]) { NSLog(@"Door number %lu is open", idx + 1); } }]; } }  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Julia
Julia
using Primes   function nosuchsum(revsorted, num) if sum(revsorted) < num return true end for (i, n) in enumerate(revsorted) if n > num continue elseif n == num return false elseif !nosuchsum(revsorted[i+1:end], num - n) return false end end true end   function isweird(n) if n < 70 || isodd(n) return false else f = [one(n)] for (p, x) in factor(n) f = reduce(vcat, [f*p^i for i in 1:x], init=f) end pop!(f) return sum(f) > n && nosuchsum(sort(f, rev=true), n) end end   function testweird(N) println("The first $N weird numbers are: ") count, n = 0, 69 while count < N if isweird(n) count += 1 print("$n ") end n += 1 end end   testweird(25)  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Kotlin
Kotlin
// Version 1.3.21   fun divisors(n: Int): List<Int> { val divs = mutableListOf(1) val divs2 = mutableListOf<Int>() var i = 2 while (i * i <= n) { if (n % i == 0) { val j = n / i divs.add(i) if (i != j) divs2.add(j) } i++ } divs2.addAll(divs.asReversed()) return divs2 }   fun abundant(n: Int, divs: List<Int>) = divs.sum() > n   fun semiperfect(n: Int, divs: List<Int>): Boolean { if (divs.size > 0) { val h = divs[0] val t = divs.subList(1, divs.size) if (n < h) { return semiperfect(n, t) } else { return n == h || semiperfect(n-h, t) || semiperfect(n, t) } } else { return false } }   fun sieve(limit: Int): BooleanArray { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 val w = BooleanArray(limit) for (i in 2 until limit step 2) { if (w[i]) continue val divs = divisors(i) if (!abundant(i, divs)) { w[i] = true } else if (semiperfect(i, divs)) { for (j in i until limit step i) w[j] = true } } return w }   fun main() { val w = sieve(17000) var count = 0 val max = 25 println("The first 25 weird numbers are:") var n = 2 while (count < max) { if (!w[n]) { print("$n ") count++ } n += 2 } println() }
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Perl
Perl
#!/usr/bin/perl use strict; use warnings;   for my $tuple ([" ", 2], ["_", 1], [" ", 1], ["\\", 1], [" ", 11], ["|", 1], ["\n", 1], [" ", 1], ["|", 1], [" ", 3], ["|", 1], [" ", 1], ["_", 1], [" ", 1], ["\\", 1], [" ", 2], ["_", 2], ["|", 1], [" ", 1], ["|", 1], ["\n", 1], [" ", 1], ["_", 3], ["/", 1], [" ", 2], ["_", 2], ["/", 1], [" ", 1], ["|", 1], [" ", 4], ["|", 1], ["\n", 1], ["_", 1], ["|", 1], [" ", 3], ["\\", 1], ["_", 3], ["|", 1], ["_", 1], ["|", 1], [" ", 3], ["_", 1], ["|", 1], ["\n", 1] ) { print $tuple->[0] x $tuple->[1]; }
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#Common_Lisp
Common Lisp
BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl") (regexp (load-time-value (cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)"))) (data (drakma:http-request url))) (multiple-value-bind (start end start-regs end-regs) (cl-ppcre:scan regexp data) (declare (ignore end)) (when start (subseq data (aref start-regs 0) (aref end-regs 0))))) "Aug. 12, 04:29:51 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
#Common_Lisp
Common Lisp
  (defun count-word (n pathname) (with-open-file (s pathname :direction :input) (loop for line = (read-line s nil nil) while line nconc (list-symb (drop-noise line)) into words finally (return (subseq (sort (pair words) #'> :key #'cdr) 0 n)))))   (defun list-symb (s) (let ((*read-eval* nil)) (read-from-string (concatenate 'string "(" s ")"))))   (defun drop-noise (s) (delete-if-not #'(lambda (x) (or (alpha-char-p x) (equal x #\space) (equal x #\-))) s))   (defun pair (words &aux (hash (make-hash-table)) ac) (dolist (word words) (incf (gethash word hash 0))) (maphash #'(lambda (e n) (push `(,e . ,n) ac)) hash) ac)  
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#GML
GML
//Create event /* Wireworld first declares constants and then reads a wireworld from a textfile. In order to implement wireworld in GML a single array is used. To make it behave properly, there need to be states that are 'in-between' two states: 0 = empty 1 = conductor from previous state 2 = electronhead from previous state 5 = electronhead that was a conductor in the previous state 3 = electrontail from previous state 4 = electrontail that was a head in the previous state */ empty = 0; conduc = 1; eHead = 2; eTail = 3; eHead_to_eTail = 4; coduc_to_eHead = 5; working = true;//not currently used, but setting it to false stops wireworld. (can be used to pause) toroidalMode = false; factor = 3;//this is used for the display. 3 means a single pixel is multiplied by three in size.   var tempx,tempy ,fileid, tempstring, gridid, listid, maxwidth, stringlength; tempx = 0; tempy = 0; tempstring = ""; maxwidth = 0;   //the next piece of code loads the textfile containing a wireworld. //the program will not work correctly if there is no textfile. if file_exists("WW.txt") { fileid = file_text_open_read("WW.txt"); gridid = ds_grid_create(0,0); listid = ds_list_create(); while !file_text_eof(fileid) { tempstring = file_text_read_string(fileid); stringlength = string_length(tempstring); ds_list_add(listid,stringlength); if maxwidth < stringlength { ds_grid_resize(gridid,stringlength,ds_grid_height(gridid) + 1) maxwidth = stringlength } else { ds_grid_resize(gridid,maxwidth,ds_grid_height(gridid) + 1) }   for (i = 1; i <= stringlength; i +=1) { switch (string_char_at(tempstring,i)) { case ' ': ds_grid_set(gridid,tempx,tempy,empty); break; case '.': ds_grid_set(gridid,tempx,tempy,conduc); break; case 'H': ds_grid_set(gridid,tempx,tempy,eHead); break; case 't': ds_grid_set(gridid,tempx,tempy,eTail); break; default: break; } tempx += 1; } file_text_readln(fileid); tempy += 1; tempx = 0; } file_text_close(fileid); //fill the 'open' parts of the grid tempy = 0; repeat(ds_list_size(listid)) { tempx = ds_list_find_value(listid,tempy); repeat(maxwidth - tempx) { ds_grid_set(gridid,tempx,tempy,empty); tempx += 1; } tempy += 1; } boardwidth = ds_grid_width(gridid); boardheight = ds_grid_height(gridid); //the contents of the grid are put in a array, because arrays are faster. //the grid was needed because arrays cannot be resized properly. tempx = 0; tempy = 0; repeat(boardheight) { repeat(boardwidth) { board[tempx,tempy] = ds_grid_get(gridid,tempx,tempy); tempx += 1; } tempy += 1; tempx = 0; } //the following code clears memory ds_grid_destroy(gridid); ds_list_destroy(listid); }
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Wren
Wren
/* window_creation_x11.wren */   var KeyPressMask = 1 << 0 var ExposureMask = 1 << 15 var KeyPress = 2 var Expose = 12   foreign class XGC { construct default(display, screenNumber) {} }   foreign class XEvent { construct new() {}   foreign eventType }   foreign class XDisplay { construct openDisplay(displayName) {}   foreign defaultScreen()   foreign rootWindow(screenNumber)   foreign blackPixel(screenNumber)   foreign whitePixel(screenNumber)   foreign selectInput(w, eventMask)   foreign mapWindow(w)   foreign closeDisplay()   foreign nextEvent(eventReturn)   foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)   foreign fillRectangle(d, gc, x, y, width, height)   foreign drawString(d, gc, x, y, string, length) }   var xd = XDisplay.openDisplay("") if (xd == 0) { System.print("Cannot open display.") return } var s = xd.defaultScreen() var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 100, 100, 1, xd.blackPixel(s), xd.whitePixel(s)) xd.selectInput(w, ExposureMask | KeyPressMask) xd.mapWindow(w) var msg = "Hello, World!" var e = XEvent.new() while (true) { xd.nextEvent(e) var gc = XGC.default(xd, s) if (e.eventType == Expose) { xd.fillRectangle(w, gc, 20, 20, 10, 10) xd.drawString(w, gc, 10, 50, msg, msg.count) } if (e.eventType == KeyPress) break } xd.closeDisplay()
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#IDL
IDL
Id = WIDGET_BASE(TITLE='Window Title',xsize=200,ysize=100) WIDGET_CONTROL, /REALIZE, id
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main(arglist)   WOpen("size=300, 300", "fg=blue", "bg=light gray") WDone() end
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#J
J
wdinfo 'Hamlet';'To be, or not to be: that is the question:'
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
#Haskell
Haskell
ss = concat [ "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 maxlen = wrap_ 0 . words where wrap_ _ [] = "\n" wrap_ pos (w:ws) -- at line start: put down the word no matter what | pos == 0 = w ++ wrap_ (pos + lw) ws | pos + lw + 1 > maxlen = '\n' : wrap_ 0 (w : ws) | otherwise = ' ' : w ++ wrap_ (pos + lw + 1) ws where lw = length w   main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Python
Python
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root)   >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#OCaml
OCaml
# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;; # #load "xml-light.cma" ;;   # let x = Xml.parse_string " <Students> <Student Name='April' Gender='F' DateOfBirth='1989-01-02' /> <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' /> <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' /> <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'> <Pet Type='dog' Name='Rover' /> </Student> <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' /> </Students>" in Xml.iter (function Xml.Element ("Student", attrs, _) -> List.iter (function ("Name", name) -> print_endline name | _ -> ()) attrs | _ -> ()) x ;; April Bob Chad Dave &#x00C9;mily - : unit = ()
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Wren
Wren
var arr = [] arr.add(1) arr.add(2) arr.count // 2 arr.clear()   arr.add(0) arr.add(arr[0]) arr.add(1) arr.add(arr[-1]) // [0, 0, 1, 1]   arr[-1] = 0 arr.insert(-1, 0) // [0, 0, 1, 0, 0] arr.removeAt(2) // [0, 0, 0, 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.
#OCaml
OCaml
let max_doors = 100   let show_doors = Array.iteri (fun i x -> Printf.printf "Door %d is %s\n" (i+1) (if x then "open" else "closed"))   let flip_doors doors = for i = 1 to max_doors do let rec flip idx = if idx < max_doors then begin doors.(idx) <- not doors.(idx); flip (idx + i) end in flip (i - 1) done; doors   let () = show_doors (flip_doors (Array.make max_doors false))
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Lua
Lua
function make(n, d) local a = {} for i=1,n do table.insert(a, d) end return a end   function reverse(t) local n = #t local i = 1 while i < n do t[i],t[n] = t[n],t[i] i = i + 1 n = n - 1 end end   function tail(list) return { select(2, unpack(list)) } end   function divisors(n) local divs = {} table.insert(divs, 1)   local divs2 = {}   local i = 2 while i * i <= n do if n % i == 0 then local j = n / i table.insert(divs, i) if i ~= j then table.insert(divs2, j) end end i = i + 1 end   reverse(divs) for i,v in pairs(divs) do table.insert(divs2, v) end return divs2 end   function abundant(n, divs) local sum = 0 for i,v in pairs(divs) do sum = sum + v end return sum > n end   function semiPerfect(n, divs) if #divs > 0 then local h = divs[1] local t = tail(divs) if n < h then return semiPerfect(n, t) else return n == h or semiPerfect(n - h, t) or semiPerfect(n, t) end else return false end end   function sieve(limit) -- false denotes abundant and not semi-perfect. -- Only interested in even numbers >= 2 local w = make(limit, false) local i = 2 while i < limit do if not w[i] then local divs = divisors(i) if not abundant(i, divs) then w[i] = true elseif semiPerfect(i, divs) then local j = i while j < limit do w[j] = true j = j + i end end end i = i + 1 end return w end   function main() local w = sieve(17000) local count = 0 local max = 25 print("The first 25 weird numbers:") local n = 2 while count < max do if not w[n] then io.write(n, ' ') count = count + 1 end n = n + 2 end print() end   main()
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Phix
Phix
constant s = """ ------*** * -----* * * ----* * * * ---*** * --* *** * * * -* * * * * * * * * * * """ puts(1,substitute_all(s,"* ",{"_/"," "}))
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++.
#D
D
void main() { import std.stdio, std.string, std.net.curl, std.algorithm;   foreach (line; "http://tycho.usno.navy.mil/cgi-bin/timer.pl".byLine) if (line.canFind(" UTC")) line[4 .. $].writeln; }
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++.
#Delphi
Delphi
    program WebScrape;   {$APPTYPE CONSOLE}   {.$DEFINE DEBUG}   uses Classes, Winsock;     { Function to connect to host, send HTTP request and retrieve response } function DoHTTPGET(const hostName: PAnsiChar; const resource: PAnsiChar; HTTPResponse: TStrings): Boolean; const Port: integer = 80; CRLF = #13#10; // carriage return/line feed var WSAData: TWSAData; Sock: TSocket; SockAddrIn: TSockAddrIn; IPAddress: PHostEnt; bytesIn: integer; inBuffer: array [0..1023] of char; Req: string; begin Result := False; HTTPResponse.Clear;   { Initialise use of the Windows Sockets DLL. Older Windows versions support Winsock 1.1 whilst newer Windows include Winsock 2 but support 1.1. Therefore, we'll specify version 1.1 ($101) as being the highest version of Windows Sockets that we can use to provide greatest flexibility. WSAData receives details of the Windows Sockets implementation } Winsock.WSAStartUp($101, WSAData); try   { Create a socket for TCP/IP usage passing in Address family spec: AF_INET (TCP, UDP, etc.) Type specification: SOCK_STREAM Protocol: IPPROTO_TCP (TCP) } Sock := WinSock.Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); try   // Check we have a valid socket if (Sock <> INVALID_SOCKET) then begin // Populate socket address structure with SockAddrIn do begin // Address family specification sin_family := AF_INET; // Port sin_port := htons(Port); // Address sin_addr.s_addr := inet_addr(hostName); end;   if (SockAddrIn.sin_addr.s_addr = INADDR_NONE) then begin { As we're using a domain name instead of an IP Address, we need to resolve the domain name } IPAddress := Winsock.gethostbyname(hostName);   // Quit if we didn't get an IP Address if (IPAddress = nil) then Exit;   // Update the structure with the IP Address SockAddrIn.sin_addr.s_addr := PLongint(IPAddress^.h_addr_list^)^; end;   // Try to connect to host if (Winsock.connect(Sock, SockAddrIn, SizeOf(SockAddrIn)) <> SOCKET_ERROR) then begin // OK - Connected   // Compose our request // Each line of the request must be terminated with a carriage return/line feed   { The First line specifies method (e.g. GET, POST), path to required resource, and the HTTP version being used. These three fields are space separated. } Req := 'GET '+resource+' HTTP/1.1' + CRLF +   // Host: is the only Required header in HTTP 1.1 'Host: '+hostName + CRLF +   { Persistent connections are the default in HTTP 1.1 but, as we don't want or need one for this exercise, we must include the "Connection: close" header in our request } 'Connection: close' + CRLF +   CRLF; // Request must end with an empty line!   // Try to send the request to the host if (Winsock.send(Sock,Req[1],Length(Req),0) <> SOCKET_ERROR) then begin // Initialise incoming data buffer (i.e. fill array with nulls) FillChar(inBuffer,SizeOf(inBuffer),#0); // Loop until nothing left to read repeat // Read incoming data from socket bytesIn := Winsock.recv(Sock, inBuffer, SizeOf(inBuffer), 0); // Assign buffer to Stringlist HTTPResponse.Text := HTTPResponse.Text + Copy(string(inBuffer),1,bytesIn); until (bytesIn <= 0) or (bytesIn = SOCKET_ERROR);   { Our list of response strings should contain at least 1 line } Result := HTTPResponse.Count > 0; end;   end;   end;   finally // Close our socket Winsock.closesocket(Sock); end;   finally { This causes our application to deregister itself from this Windows Sockets implementation and allows the implementation to free any resources allocated on our behalf. } Winsock.WSACleanup; end;   end;   { Simple function to locate and return the UTC time from the request sent to http://tycho.usno.navy.mil/cgi-bin/timer.pl The HTTPResponse parameter contains both the HTTP Headers and the HTML served up by the requested resource. } function ParseResponse(HTTPResponse: TStrings): string; var i: Integer; begin Result := '';   { Check first line for server response code We want something like this: HTTP/1.1 200 OK } if Pos('200',HTTPResponse[0]) > 0 then begin for i := 0 to Pred(HTTPResponse.Count) do begin { The line we're looking for is something like this: <BR>May. 04. 21:55:19 UTC Universal Time }   // Check each line if Pos('UTC',HTTPResponse[i]) > 0 then begin Result := Copy(HTTPResponse[i],5,Pos('UTC',HTTPResponse[i])-1); Break; end;   end; end else Result := 'HTTP Error: '+HTTPResponse[0]; end;     const host: PAnsiChar = 'tycho.usno.navy.mil'; res : PAnsiChar = '/cgi-bin/timer.pl';     var Response: TStrings;   begin { A TStringList is a TStrings descendant class that is used to store and manipulate a list of strings.   Instantiate a stringlist class to hold the results of our HTTP GET } Response := TStringList.Create; try // Try an HTTP GET request if DoHTTPGET(host,res,Response) then begin {$IFDEF DEBUG} { Write the entire response to the console window } Writeln(Response.text); {$ELSE} { Parse the response and write the result to the console window } Writeln(ParseResponse(Response)); {$ENDIF DEBUG} end else Writeln('Error retrieving data');   finally Response.Free; end;   // Keep console window open Readln;     end.    
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Crystal
Crystal
require "http/client" require "regex"   # Get the text from the internet response = HTTP::Client.get "https://www.gutenberg.org/files/135/135-0.txt" text = response.body   text .downcase .scan(/[a-zA-ZáéíóúÁÉÍÓÚâêôäüöàèìòùñ']+/) .reduce({} of String => Int32) { |hash, match| word = match[0] hash[word] = hash.fetch(word, 0) + 1 # using fetch to set a default value (1) to the new found word hash } .to_a # convert the returned hash to an array of tuples (String, Int32) -> {word, sum} .sort { |a, b| b[1] <=> a[1] }[0..9] # sort and get the first 10 elements .each_with_index(1) { |(word, n), i| puts "#{i} \t #{word} \t #{n}" } # print the result
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Go
Go
package main   import ( "bytes" "fmt" "io/ioutil" "strings" )   var rows, cols int // extent of input configuration var rx, cx int // grid extent (includes border) var mn []int // offsets of moore neighborhood   func main() { // read input configuration from file src, err := ioutil.ReadFile("ww.config") if err != nil { fmt.Println(err) return } srcRows := bytes.Split(src, []byte{'\n'})   // compute package variables rows = len(srcRows) for _, r := range srcRows { if len(r) > cols { cols = len(r) } } rx, cx = rows+2, cols+2 mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}   // allocate two grids and copy input into first grid odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for ri, r := range srcRows { copy(odd[(ri+1)*cx+1:], r) }   // run for { print(odd) step(even, odd) fmt.Scanln()   print(even) step(odd, even) fmt.Scanln() } }   func print(grid []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if grid[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", grid[r*cx+c]) } } fmt.Println() } }   func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case 'H': dst[x] = 't' case 't': dst[x] = '.' case '.': var nn int for _, n := range mn { if src[x+n] == 'H' { nn++ } } if nn == 1 || nn == 2 { dst[x] = 'H' } } } } }
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Java
Java
import javax.swing.JFrame;   public class Main { public static void main(String[] args) throws Exception { JFrame w = new JFrame("Title"); w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); w.setSize(800,600); w.setVisible(true); } }
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#JavaScript
JavaScript
window.open("webpage.html", "windowname", "width=800,height=600");
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
#Icon_and_Unicon
Icon and Unicon
  procedure main(A) ll := integer(A[1]) | 72 wordWrap(&input, ll) end   procedure wordWrap(f, ll) every (sep := "", s := "", w := words(f)) do if w == "\n" then write(1(.s, s := sep := ""),"\n") else if (*s + *w) >= ll then write(1(.s, s := w, sep := " ")) else (s ||:= .sep||("\n" ~== w), sep := " ") if *s > 0 then write(s) end   procedure words(f) static wc initial wc := &cset -- ' \t' # Loose definition of a 'word'... while l := !f do { l ? while tab(upto(wc)) do suspend tab(many(wc))\1 if *trim(l) = 0 then suspend "\n" # Paragraph boundary } end
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#R
R
library(XML) char2xml <- function(names, remarks){ tt <- xmlHashTree() head <- addNode(xmlNode("CharacterRemarks"), character(), tt) node <- list() for (i in 1:length(names)){ node[[i]] <- addNode(xmlNode("Character", attrs=c(name=names[i])), head, tt) addNode(xmlTextNode(remarks[i]), node[[i]], tt) } return(tt) } output <- char2xml( names=c("April","Tam O'Shanter","Emily"), remarks=c("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift") )
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Racket
Racket
  #lang racket (require xml)   (define (make-character-xexpr characters remarks) `(CharacterRemarks ,@(for/list ([character characters] [remark remarks]) `(Character ((name ,character)) ,remark))))   (display-xml/content (xexpr->xml (make-character-xexpr '("April" "Tam O'Shanter" "Emily") '("Bubbly: I'm > Tam and <= Emily" "Burns: \"When chapman billies leave the street ...\"" "Short & shrift"))))  
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#OpenEdge_ABL.2FProgress_4GL
OpenEdge ABL/Progress 4GL
  /** ==== Definitions ===== **/ DEFINE VARIABLE chXMLString AS LONGCHAR NO-UNDO. DEFINE TEMP-TABLE ttStudent NO-UNDO XML-NODE-NAME 'Student' FIELD StudentName AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'Name' LABEL 'Name' FIELD Gender AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'Gender' LABEL 'Gender' FIELD DateOfBirth AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'DateOfBirth' LABEL 'Date Of Birth'. DEFINE DATASET dsStudents XML-NODE-NAME 'Students' FOR ttStudent.   /** ==== Main block ====**/   /** ASSIGN the XML string with the XML data.. **/ chXMLString = '<Students>~ <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />~ <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />~ <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />~ <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">~ <Pet Type="dog" Name="Rover" />~ </Student>~ <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />~ </Students>'.   /** Read the string into the dataset...**/ DATASET dsStudents:READ-XML('LONGCHAR', chXMLString, 'EMPTY',?,?).   /** Loop thought each temp-table record to produce the results...**/ FOR EACH ttStudent: DISPLAY ttStudent.StudentName. END.    
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#OpenEdge.2FProgress
OpenEdge/Progress
  DEF VAR lcc AS LONGCHAR. DEF VAR hxdoc AS HANDLE. DEF VAR hxstudents AS HANDLE. DEF VAR hxstudent AS HANDLE. DEF VAR hxname AS HANDLE. DEF VAR ii AS INTEGER EXTENT 2. DEF VAR cstudents AS CHARACTER.   lcc = '<Students>' + '<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' + '<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />' + '<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />' + '<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">' + '<Pet Type="dog" Name="Rover" />' + '</Student>' + '<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />' + '</Students>'.   CREATE X-DOCUMENT hxdoc. hxdoc:LOAD( 'LONGCHAR', lcc, FALSE ).   DO ii[1] = 1 TO hxdoc:NUM-CHILDREN: CREATE X-NODEREF hxstudents. hxdoc:GET-CHILD( hxstudents, ii[1] ). IF hxstudents:NAME = 'Students' THEN DO ii[2] = 1 TO hxstudents:NUM-CHILDREN: CREATE X-NODEREF hxstudent. hxstudents:GET-CHILD( hxstudent, ii[2] ). IF hxstudent:NAME = 'Student' THEN cstudents = cstudents + hxstudent:GET-ATTRIBUTE( 'Name' ) + '~n'. DELETE OBJECT hxstudent. END. DELETE OBJECT hxstudents. END. DELETE OBJECT hxdoc.   MESSAGE cstudents VIEW-AS ALERT-BOX.
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#X86_Assembly
X86 Assembly
  section .text global _start   _print: mov ebx, 1 mov eax, 4 int 0x80 ret   _start: ;print out our byte array. ergo, String. mov edx, sLen mov ecx, sArray call _print mov edx, f_len mov ecx, f_msg call _print mov edx, 6 ;our array members length. xor ecx, ecx mov ecx, 4 ;turnicate through the array and print all it's members. ;At an offset of *4, each array member is referenced ;at 1,2,3 and so on. _out_loops: push ecx mov ecx, [fArray+esi*4] call _print inc esi pop ecx loop _out_loops mov edx, u_len mov ecx, u_msg call _print ;Let's populate 'uArray' with something from sArray. ;mov edi, uArray mov ecx, 4 xor esi, esi _read_loops: push dword [fArray+esi*4] pop dword [uArray+esi*4] inc esi loop _read_loops mov ecx, 4 xor esi, esi _out_loops2: push ecx mov ecx, [uArray+esi*4] call _print inc esi pop ecx loop _out_loops2 push 0x1 mov eax, 1 push eax int 0x80   section .data sArray db 'a','r','r','a','y','s',' ','a','r','e',' ','f','u','n',0xa sLen equ $-sArray   crap1 db "crap1",0xa crap2 db "crap2",0xa crap3 db "crap3",0xa crap4 db "crap4",0xa   fArray dd crap1,crap2 dd crap3,crap4   f_msg db "fArray contents",0xa,"----------------------",0xa f_len equ $-f_msg u_msg db "uArray now holds fArray contents.. dumping..",0xa,"----------------------",0xa u_len equ $-u_msg   section .bss uArray resd 1 resd 1 resd 1 resd 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.
#Octave
Octave
doors = false(100,1); for i = 1:100 for j = i:i:100 doors(j) = !doors(j); endfor endfor for i = 1:100 if ( doors(i) ) s = "open"; else s = "closed"; endif printf("%d %s\n", i, s); endfor
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[WeirdNumberQ, HasSumQ] HasSumQ[n_Integer, xs_List] := HasSumHelperQ[n, ReverseSort[xs]] HasSumHelperQ[n_Integer, xs_List] := Module[{h, t}, If[Length[xs] > 0, h = First[xs]; t = Drop[xs, 1]; If[n < h, HasSumHelperQ[n, t] , n == h \[Or] HasSumHelperQ[n - h, t] \[Or] HasSumHelperQ[n, t] ] , False ] ] WeirdNumberQ[n_Integer] := Module[{divs}, divs = Most[Divisors[n]]; If[Total[divs] > n,  ! HasSumQ[n, divs] , False ] ] r = {}; n = 0; While[ Length[r] < 25, If[WeirdNumberQ[++n], AppendTo[r, n]] ] Print[r]
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Nim
Nim
import algorithm, math, strutils   func divisors(n: int): seq[int] = var smallDivs = @[1] for i in 2..sqrt(n.toFloat).int: if n mod i == 0: let j = n div i smallDivs.add i if i != j: result.add j result.add reversed(smallDivs)   func abundant(n: int; divs: seq[int]): bool {.inline.}= sum(divs) > n   func semiperfect(n: int; divs: seq[int]): bool = if divs.len > 0: let h = divs[0] let t = divs[1..^1] result = if n < h: semiperfect(n, t) else: n == h or semiperfect(n - h, t) or semiperfect(n, t)   func sieve(limit: int): seq[bool] = # False denotes abundant and not semi-perfect. # Only interested in even numbers >= 2. result.setLen(limit) for i in countup(2, limit - 1, 2): if result[i]: continue let divs = divisors(i) if not abundant(i, divs): result[i] = true elif semiperfect(i, divs): for j in countup(i, limit - 1, i): result[j] = true     const Max = 25 let w = sieve(17_000) var list: seq[int]   echo "The first 25 weird numbers are:" var n = 2 while list.len != Max: if not w[n]: list.add n inc n, 2 echo list.join(" ")
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#PicoLisp
PicoLisp
(de Lst "***** * " "* * * * * " "* * **** **** * **** ****" "***** * * * * * * * * * *" "* * * * * * * * ****" "* * * * * * * * * " "* * * * * * * * * * " "* * **** **** **** * **** * " )   (de transform (Lst A B) (make (chain (need (length Lst) " ")) (for (L (chop (car Lst)) L) (ifn (= "*" (pop 'L)) (link " " " " " ") (chain (need 3 A)) (when (sp? (car L)) (link B " " " ") (pop 'L) ) ) ) ) )   (prinl (transform Lst "/" "\\"))   (mapc '((X Y) (mapc '((A B) (prin (if (sp? B) A B)) ) X Y ) (prinl) ) (maplist '((X) (transform X "\\" "/")) Lst) (maplist '((X) (transform X "/" "\\")) (cdr Lst)) )   (bye)
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#PureBasic
PureBasic
If OpenConsole() PrintN(" ////\ ////\ ////| ") PrintN(" //// \ __ //// \ __ |XX|_/ ") PrintN(" //// /| | ////\ ////\//// |//// /| | //// | ////\ ////\ ") PrintN("|XX| |X| ////\X| ////\// //// /||XX| |X| |//// /|| //// _| ////\ //// \ ") PrintN("|XX| |X||XX| |X||XX| |/ |XX| |X||XX| |/ /|XX| |X||//// / |XX| | //// /\ |") PrintN("|XX| |/ |XX| |X||XX| /|XX| |//|XX| \|XX|/// |XX| |/\ |XX| ||XX| |XX\|") PrintN("|XX| /|XX| |X||XX| / |XX| //|XX| /| |//// |XX| ||XX| ||XX| | ") PrintN("|$$| / |$$| |&||$$| | |$$| |&||$$| |&| |$$| /||\\\\/| ||$$| ||$$| |///|") PrintN("|%%| | |%%| |i||%%| | |%%| |/ |%%| |i| |%%| |i|| |%%| ||%%| ||%%| |// |") PrintN("|ii| | |ii| |/ |ii| | |ii| /|ii| |/ /|ii| \/|/ |ii| /|ii| ||ii| |/ / ") PrintN("|::| | \\\\ /|::| | |::| / |::| / |::| / //// / |::| | \\\\ / ") PrintN("|..| | \\\\/ |..|/ \\\\/ |..| / \\\\/ \\\\ / |..|/ \\\\/ ") PrintN(" \\\\| \\\\/ ")   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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++.
#E
E
interp.waitAtTop(when (def html := <http://tycho.usno.navy.mil/cgi-bin/timer.pl>.getText()) -> { def rx`(?s).*>(@time.*? UTC).*` := html println(time) })
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
#D
D
import std.algorithm : sort; import std.array : appender, split; import std.range : take; import std.stdio : File, writefln, writeln; import std.typecons : Tuple; import std.uni : toLower;   //Container for a word and how many times it has been seen alias Pair = Tuple!(string, "k", int, "v");   void main() { int[string] wcnt;   //Read the file line by line foreach (line; File("135-0.txt").byLine) { //Split the words on whitespace foreach (word; line.split) { //Increment the times the word has been seen wcnt[word.toLower.idup]++; } }   //Associative arrays cannot be sort, so put the key/value in an array auto wb = appender!(Pair[]); foreach(k,v; wcnt) { wb.put(Pair(k,v)); } Pair[] sw = wb.data.dup;   //Sort the array, and display the top ten values writeln("Rank Word Frequency"); int rank=1; foreach (word; sw.sort!"a.v>b.v".take(10)) { writefln("%4s  %-10s  %9s", rank++, word.k, word.v); } }
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Haskell
Haskell
import Data.List import Control.Monad import Control.Arrow import Data.Maybe   states=" Ht." shiftS=" t.."   borden bc xs = bs: (map (\x -> bc:(x++[bc])) xs) ++ [bs] where r = length $ head xs bs = replicate (r+2) bc   take3x3 = ap ((.). taken. length) (taken. length. head) `ap` borden '*' where taken n = transpose. map (take n.map (take 3)).map tails   nwState xs | e =='.' && noH>0 && noH<3 = 'H' | otherwise = shiftS !! (fromJust $ elemIndex e states) where e = xs!!1!!1 noH = length $ filter (=='H') $ concat xs   runCircuit = iterate (map(map nwState).take3x3)
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Julia
Julia
# v0.6   using Tk   w = Toplevel("Example")
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Kotlin
Kotlin
import javax.swing.JFrame   fun main(args : Array<String>) { JFrame("Title").apply { setSize(800, 600) defaultCloseOperation = JFrame.EXIT_ON_CLOSE isVisible = true } }
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
#IS-BASIC
IS-BASIC
100 TEXT 80 110 CALL WRITE(12,68,0) 120 PRINT :CALL WRITE(10,70,1) 130 DEF WRITE(LEFTMARGIN,RIGHTMARGIN,JUSTIFIED) 140 STRING S$*254 150 RESTORE 160 PRINT TAB(LEFTMARGIN);CHR$(243); 170 PRINT TAB(RIGHTMARGIN-1);CHR$(251) 180 DO 190 READ IF MISSING EXIT DO:S$ 200 PRINT S$; 210 LOOP 220 IF JUSTIFIED THEN PRINT CHR$(248) ! <- Extra credit :-) 230 PRINT 240 END DEF 250 DATA "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. " 260 DATA "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, " 270 DATA "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."  
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
#J
J
ww =: 75&$: : wrap wrap =: (] turn edges) ,&' ' turn =: LF"_`]`[} edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Raku
Raku
use XML::Writer;   my @students = [ Q[April], Q[Bubbly: I'm > Tam and <= Emily] ], [ Q[Tam O'Shanter], Q[Burns: "When chapman billies leave the street ..."] ], [ Q[Emily], Q[Short & shrift] ] ;   my @lines = map { :Character[:name(.[0]), .[1]] }, @students;   say XML::Writer.serialize( CharacterRemarks => @lines );
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Oz
Oz
declare [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} Parser = {New XMLParser.parser init}   Data = "<Students>" #" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />" #" <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />" #" <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />" #" <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">" #" <Pet Type=\"dog\" Name=\"Rover\" />" #" </Student>" #" <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />" #"</Students>"   fun {IsStudentElement X} case X of element(name:'Student' ...) then true else false end end   fun {GetStudentName element(attributes:As ...)} [NameAttr] = {Filter As fun {$ attribute(name:N ...)} N == 'Name' end} in NameAttr.value end   [StudentsDoc] = {Parser parseVS(Data $)} Students = {Filter StudentsDoc.children IsStudentElement} StudentNames = {Map Students GetStudentName} in {ForAll StudentNames System.showInfo}
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#XBS
XBS
set Array = ["Hello","World"]; log(Array[0]); Array.push("Test"); log(?Array); log(Array[?Array-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.
#Oforth
Oforth
: doors | i j l | 100 false Array newWith dup ->l 100 loop: i [ i 100 i step: j [ l put ( j , j l at not ) ] ] ;  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Perl
Perl
use strict; use feature 'say';   use List::Util 'sum'; use POSIX 'floor'; use Algorithm::Combinatorics 'subsets'; use ntheory <is_prime divisors>;   sub abundant { my($x) = @_; my $s = sum( my @l = is_prime($x) ? 1 : grep { $x != $_ } divisors($x) ); $s > $x ? ($s, sort { $b <=> $a } @l) : (); }   my(@weird,$n); while () { $n++; my ($sum, @div) = abundant($n); next unless $sum; # Weird number must be abundant, skip it if it isn't. next if $sum / $n > 1.1; # There aren't any weird numbers with a sum:number ratio greater than 1.08 or so.   if ($n >= 10430 and (! int $n%70) and is_prime(int $n/70)) { # It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird } else { my $next; my $l = shift @div; my $iter = subsets(\@div); while (my $s = $iter->next) { ++$next and last if sum(@$s) == $n - $l; } next if $next; } push @weird, $n; last if @weird == 25; }   say "The first 25 weird numbers:\n" . join ' ', @weird;
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Python
Python
py = '''\ ##### # # ##### # # #### # # # # # # # # # # # ## # # # # # ###### # # # # # ##### # # # # # # # # # # # # # # # # # ## # # # # # #### # # '''   lines = py.replace('#', '<<<').replace(' ','X').replace('X', ' ').replace('\n', ' Y').replace('< ', '<>').split('Y') for i, l in enumerate(lines): print( ' ' * (len(lines) - i) + l)
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++.
#Erlang
Erlang
-module(scraping). -export([main/0]). -define(Url, "http://tycho.usno.navy.mil/cgi-bin/timer.pl"). -define(Match, "<BR>(.+ UTC)").   main() -> inets:start(), {ok, {_Status, _Header, HTML}} = httpc:request(?Url), {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), io:format("~s~n",[Time]).
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
#Delphi
Delphi
  program Word_frequency;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IOUtils, System.Generics.Collections, System.Generics.Defaults, System.RegularExpressions;   type TWords = TDictionary<string, Integer>;   TFreqPair = TPair<string, Integer>;   TFreq = TArray<TFreqPair>;   function CreateValueCompare: IComparer<TFreqPair>; begin Result := TComparer<TFreqPair>.Construct( function(const Left, Right: TFreqPair): Integer begin Result := Right.Value - Left.Value; end); end;   function WordFrequency(const Text: string): TFreq; var words: TWords; match: TMatch; w: string; begin words := TWords.Create(); match := TRegEx.Match(Text, '\w+'); while match.Success do begin w := match.Value; if words.ContainsKey(w) then words[w] := words[w] + 1 else words.Add(w, 1); match := match.NextMatch(); end;   Result := words.ToArray; words.Free; TArray.Sort<TFreqPair>(Result, CreateValueCompare); end;   var Text: string; rank: integer; Freq: TFreq; w: TFreqPair;   begin Text := TFile.ReadAllText('135-0.txt').ToLower();   Freq := WordFrequency(Text);   Writeln('Rank Word Frequency'); Writeln('==== ==== =========');   for rank := 1 to 10 do begin w := Freq[rank - 1]; Writeln(format('%2d  %6s  %5d', [rank, w.Key, w.Value])); end;   readln; end.  
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Icon_and_Unicon
Icon and Unicon
link graphics   $define EDGE -1 $define EMPTY 0 $define HEAD 1 $define TAIL 2 $define COND 3   global Colours,Width,Height,World,oldWorld   procedure main() # wire world modified from forestfire   Height := 400 # Window height Width := 400 # Window width Rounds := 500 # max Rounds Delay := 5 # Runout Delay   setup_world(read_world()) every round := 1 to Rounds do { show_world() if \runout then delay(Delay) else case Event() of { "q" : break # q = quit "r" : runout := 1 # r = run w/o stepping "s" : WriteImage("Wireworld-"||round) # save } evolve_world() } WDone() end   procedure read_world() #: for demo in place of reading return [ "tH.........", ". .", " ...", ". .", "Ht.. ......"] end   procedure setup_world(L) #: setup the world   Colours := table() # define colours Colours[EDGE] := "grey" Colours[EMPTY] := "black" Colours[HEAD] := "blue" Colours[TAIL] := "red" Colours[COND] := "yellow"   States := table() States["t"] := TAIL States["H"] := HEAD States[" "] := EMPTY States["."] := COND   WOpen("label=Wireworld", "bg=black", "size=" || Width+2 || "," || Height+2) | # add for border stop("Unable to open Window") every !(World := list(Height)) := list(Width,EMPTY) # default every ( World[1,1 to Width] | World[Height,1 to Width] | World[1 to Height,1] | World[1 to Height,Width] ) := EDGE   every r := 1 to *L & c := 1 to *L[r] do { # setup read in program World[r+1, c+1] := States[L[r,c]] } end   procedure show_world() #: show World - drawn changes only every r := 2 to *World-1 & c := 2 to *World[r]-1 do if /oldWorld | oldWorld[r,c] ~= World[r,c] then { WAttrib("fg=" || Colours[tr := World[r,c]]) DrawPoint(r,c) } end   procedure evolve_world() #: evolve world old := oldWorld := list(*World) # freeze copy every old[i := 1 to *World] := copy(World[i]) # deep copy   every r := 2 to *World-1 & c := 2 to *World[r]-1 do World[r,c] := case old[r,c] of { # apply rules # EMPTY : EMPTY HEAD : TAIL TAIL : COND COND : { i := 0 every HEAD = ( old[r-1,c-1 to c+1] | old[r,c-1|c+1] | old[r+1,c-1 to c+1] ) do i +:= 1 if i := 1 | 2 then HEAD } } end
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Liberty_BASIC
Liberty BASIC
nomainwin open "GUI Window" for window as #1 wait  
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Lingo
Lingo
win = window().new("New Window") w = 320 h = 240 firstScreen = _system.deskTopRectList[1] x = firstScreen.width/2 - w/2 y = firstScreen.height/2- h/2 win.rect = rect(x,y,x+w,y+h) -- Director needs a binary movie file (*.dir) for opening new windows. But this -- movie file can be totally empty, and if it's write protected in the filesystem, -- it can be re-used for multiple windows. win.filename = _movie.path & "empty.dir" win.open()
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
#Java
Java
  package rosettacode;   import java.util.StringTokenizer;   public class WordWrap { int defaultLineWidth=80; int defaultSpaceWidth=1; void minNumLinesWrap(String text) { minNumLinesWrap(text,defaultLineWidth); } void minNumLinesWrap(String text,int LineWidth) { StringTokenizer st=new StringTokenizer(text); int SpaceLeft=LineWidth; int SpaceWidth=defaultSpaceWidth; while(st.hasMoreTokens()) { String word=st.nextToken(); if((word.length()+SpaceWidth)>SpaceLeft) { System.out.print("\n"+word+" "); SpaceLeft=LineWidth-word.length(); } else { System.out.print(word+" "); SpaceLeft-=(word.length()+SpaceWidth); } } } public static void main(String[] args) { WordWrap now=new WordWrap(); String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie."; System.out.println("DEFAULT:"); now.minNumLinesWrap(wodehouse); System.out.println("\n\nLINEWIDTH=120"); now.minNumLinesWrap(wodehouse,120); }   }    
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Rascal
Rascal
import Prelude; import lang::xml::DOM;   list[str] charnames = ["April", "Tam O\'Shanter", "Emily"]; list[str] remarks = ["Bubbly: I\'m \> Tam and \<= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"];   public void xmloutput(list[str] n,list[str] r){ if(size(n) != size(r)){ throw "n and r should be of the same size"; } else{ characters = [element(none(),"Character",[attribute(none(),"name",n[i]), charData(r[i])]),charData("\n")| i <- [0..size(n)-1]]; x = document(element(none(),"CharacterRemarks",characters)); return println(xmlPretty(x)); } }
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#REXX
REXX
/*REXX program creates an HTML (XML) list of character names and corresponding remarks. */ charname. = charname.1 = "April" charname.2 = "Tam O'Shanter" charname.3 = "Emily" do i=1 while charname.i\=='' say 'charname' i '=' charname.i end /*i*/; say remark. = remark.1 = "I'm > Tam and <= Emily" remark.2 = "When chapman billies leave the street ..." remark.3 = "Short & shift" do k=1 while remark.k\=='' say ' remark' k '=' remark.k end /*k*/; say items = 0 header = 'CharacterRemarks' header = header'>'   do j=1 while charname.j\=='' _=charname.j if j==1 then call create '<'header call create ' <Character name="' ||, char2xml(_)'">"' ||, char2xml(remark.j)'"</Character>' end /*j*/   if create.0\==0 then call create '</'header   do m=1 for create.0 say create.m /*display the Mth entry to terminal. */ end /*m*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ char2xml: procedure; parse arg $ amper = pos('&', $)\==0 /* & has to be treated special. */ semi = pos(';', $)\==0 /*  ; " " " " " */ #=0 /* [↓] find a free/unused character···*/ if amper then do /* ··· and translate freely. */ do j=0 for 255;  ?=d2c(j); if pos(?, $)==0 then leave end /*j*/ $=translate($, ?, "&"); #= j + 1 end /* [↓] find a free/unused character···*/ if semi then do /* ··· and translate freely. */ do k=# for 255;  ?=d2c(k); if pos(?, $)==0 then leave end /*k*/ $=translate($, ?, ";") end   /*───── Following are most of the characters in the DOS (or DOS Windows) codepage 437 ──────────*/   $=XML_('â',"ETH")  ; $=XML_('ƒ',"fnof")  ; $=XML_('═',"boxH")  ; $=XML_('♥',"hearts") $=XML_('â','#x00e2') ; $=XML_('á',"aacute"); $=XML_('╬',"boxVH")  ; $=XML_('♦',"diams") $=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',"boxHu")  ; $=XML_('♣',"clubs") $=XML_('ä',"auml")  ; $=XML_('í',"iacute"); $=XML_('╨',"boxhU")  ; $=XML_('♠',"spades") $=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',"boxHd")  ; $=XML_('♂',"male") $=XML_('à',"agrave") ; $=XML_('ó',"oacute"); $=XML_('╥',"boxhD")  ; $=XML_('♀',"female") $=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',"boxUr")  ; $=XML_('☼',"#x263c") $=XML_('å',"aring")  ; $=XML_('ú',"uacute"); $=XML_('╘',"boxuR")  ; $=XML_('↕',"UpDownArrow") $=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',"boxdR")  ; $=XML_('¶',"para") $=XML_('ç',"ccedil") ; $=XML_('ñ',"ntilde"); $=XML_('╓',"boxDr")  ; $=XML_('§',"sect") $=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',"boxVh")  ; $=XML_('↑',"uarr") $=XML_('ê',"ecirc")  ; $=XML_('Ñ',"Ntilde"); $=XML_('╪',"boxvH")  ; $=XML_('↑',"uparrow") $=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',"boxul")  ; $=XML_('↑',"ShortUpArrow") $=XML_('ë',"euml")  ; $=XML_('¿',"iquest"); $=XML_('┌',"boxdr")  ; $=XML_('↓',"darr") $=XML_('ë','#x00eb') ; $=XML_('⌐',"bnot")  ; $=XML_('█',"block")  ; $=XML_('↓',"downarrow") $=XML_('è',"egrave") ; $=XML_('¬',"not")  ; $=XML_('▄',"lhblk")  ; $=XML_('↓',"ShortDownArrow") $=XML_('è','#x00e8') ; $=XML_('½',"frac12"); $=XML_('▀',"uhblk")  ; $=XML_('←',"larr") $=XML_('ï',"iuml")  ; $=XML_('½',"half")  ; $=XML_('α',"alpha")  ; $=XML_('←',"leftarrow") $=XML_('ï','#x00ef') ; $=XML_('¼',"frac14"); $=XML_('ß',"beta")  ; $=XML_('←',"ShortLeftArrow") $=XML_('î',"icirc")  ; $=XML_('¡',"iexcl") ; $=XML_('ß',"szlig")  ; $=XML_('1c'x,"rarr") $=XML_('î','#x00ee') ; $=XML_('«',"laqru") ; $=XML_('ß','#x00df')  ; $=XML_('1c'x,"rightarrow") $=XML_('ì',"igrave") ; $=XML_('»',"raqru") ; $=XML_('Γ',"Gamma")  ; $=XML_('1c'x,"ShortRightArrow") $=XML_('ì','#x00ec') ; $=XML_('░',"blk12") ; $=XML_('π',"pi")  ; $=XML_('!',"excl") $=XML_('Ä',"Auml")  ; $=XML_('▒',"blk14") ; $=XML_('Σ',"Sigma")  ; $=XML_('"',"apos") $=XML_('Ä','#x00c4') ; $=XML_('▓',"blk34") ; $=XML_('σ',"sigma")  ; $=XML_('$',"dollar") $=XML_('Å',"Aring")  ; $=XML_('│',"boxv")  ; $=XML_('µ',"mu")  ; $=XML_("'","quot") $=XML_('Å','#x00c5') ; $=XML_('┤',"boxvl") ; $=XML_('τ',"tau")  ; $=XML_('*',"ast") $=XML_('É',"Eacute") ; $=XML_('╡',"boxvL") ; $=XML_('Φ',"phi")  ; $=XML_('/',"sol") $=XML_('É','#x00c9') ; $=XML_('╢',"boxVl") ; $=XML_('Θ',"Theta")  ; $=XML_(':',"colon") $=XML_('æ',"aelig")  ; $=XML_('╖',"boxDl") ; $=XML_('δ',"delta")  ; $=XML_('<',"lt") $=XML_('æ','#x00e6') ; $=XML_('╕',"boxdL") ; $=XML_('∞',"infin")  ; $=XML_('=',"equals") $=XML_('Æ',"AElig")  ; $=XML_('╣',"boxVL") ; $=XML_('φ',"Phi")  ; $=XML_('>',"gt") $=XML_('Æ','#x00c6') ; $=XML_('║',"boxV")  ; $=XML_('ε',"epsilon")  ; $=XML_('?',"quest") $=XML_('ô',"ocirc")  ; $=XML_('╗',"boxDL") ; $=XML_('∩',"cap")  ; $=XML_('_',"commat") $=XML_('ô','#x00f4') ; $=XML_('╝',"boxUL") ; $=XML_('≡',"equiv")  ; $=XML_('[',"lbrack") $=XML_('ö',"ouml")  ; $=XML_('╜',"boxUl") ; $=XML_('±',"plusmn")  ; $=XML_('\',"bsol") $=XML_('ö','#x00f6') ; $=XML_('╛',"boxuL") ; $=XML_('±',"pm")  ; $=XML_(']',"rbrack") $=XML_('ò',"ograve") ; $=XML_('┐',"boxdl") ; $=XML_('±',"PlusMinus") ; $=XML_('^',"Hat") $=XML_('ò','#x00f2') ; $=XML_('└',"boxur") ; $=XML_('≥',"ge")  ; $=XML_('`',"grave") $=XML_('û',"ucirc")  ; $=XML_('┴',"bottom"); $=XML_('≤',"le")  ; $=XML_('{',"lbrace") $=XML_('û','#x00fb') ; $=XML_('┴',"boxhu") ; $=XML_('÷',"div")  ; $=XML_('{',"lcub") $=XML_('ù',"ugrave") ; $=XML_('┬',"boxhd") ; $=XML_('÷',"divide")  ; $=XML_('|',"vert") $=XML_('ù','#x00f9') ; $=XML_('├',"boxvr") ; $=XML_('≈',"approx")  ; $=XML_('|',"verbar") $=XML_('ÿ',"yuml")  ; $=XML_('─',"boxh")  ; $=XML_('∙',"bull")  ; $=XML_('}',"rbrace") $=XML_('ÿ','#x00ff') ; $=XML_('┼',"boxvh") ; $=XML_('°',"deg")  ; $=XML_('}',"rcub") $=XML_('Ö',"Ouml")  ; $=XML_('╞',"boxvR") ; $=XML_('·',"middot")  ; $=XML_('Ç',"Ccedil") $=XML_('Ö','#x00d6') ; $=XML_('╟',"boxVr") ; $=XML_('·',"middledot") ; $=XML_('Ç','#x00c7') $=XML_('Ü',"Uuml")  ; $=XML_('╚',"boxUR") ; $=XML_('·',"centerdot") ; $=XML_('ü',"uuml") $=XML_('Ü','#x00dc') ; $=XML_('╔',"boxDR") ; $=XML_('·',"CenterDot") ; $=XML_('ü','#x00fc') $=XML_('¢',"cent")  ; $=XML_('╩',"boxHU") ; $=XML_('√',"radic")  ; $=XML_('é',"eacute") $=XML_('£',"pound")  ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2")  ; $=XML_('é','#x00e9') $=XML_('¥',"yen")  ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ")  ; $=XML_('â',"acirc")   if amper then $=xml_(?, "amp") /*Was there an ampersand? Translate it*/ if semi then $=xml_(??, "semi") /* " " " semicolon? " "*/ return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ create: items= items + 1 /*bump the count of items in the list. */ create.items= arg(1) /*add item to the CREATE list. */ create.0 = items /*indicate how many items in the list. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ xml_: parse arg _ /*make an XML entity (&xxxx;) */ if pos(_, $)\==0 then return changestr(_, $, "&"arg(2)";") return $
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Perl
Perl
use utf8; use XML::Simple;   my $ref = XMLin('<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students>');   print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}});
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#XLISP
XLISP
[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list   A [2] (define b (make-vector 10 5)) ; vector of 10 elements initialized to 5   B [3] (define c #(1 2 3 4 5 6 7 8 9 10)) ; vector literal   C [4] (vector-ref c 3) ; retrieve a value -- NB. indexed from 0   4 [5] (vector-set! a 5 1) ; set a_5 to 1   1 [6] (define d (make-array 5 6 7)) ; 3-dimensional array of size 5 by 6 by 7   D [7] (array-set! d 1 2 3 10) ; set d_1,2,3 to 10 -- NB. still indexed from 0   10 [8] (array-ref d 1 2 3) ; and get the value of d_1,2,3   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.
#Ol
Ol
  (define (flip doors every) (map (lambda (door num) (mod (+ door (if (eq? (mod num every) 0) 1 0)) 2)) doors (iota (length doors) 1)))   (define doors (let loop ((doors (repeat 0 100)) (n 1)) (if (eq? n 100) doors (loop (flip doors n) (+ n 1)))))   (print "100th doors: " doors)  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Phix
Phix
with javascript_semantics function abundant(integer n, sequence divs) return sum(divs) > n end function function semiperfect(integer n, sequence divs) if length(divs)=0 then return false end if integer h = divs[1]; divs = divs[2..$] return n=h or (n>h and semiperfect(n-h, divs)) or semiperfect(n, divs) end function function sieve(integer limit) -- true denotes abundant and not semi-perfect. -- only interested in even numbers >= 2 sequence wierd := repeat(true,limit) for j=6 to limit by 6 do -- eliminate multiples of 3 wierd[j] = false end for for i=2 to limit by 2 do if wierd[i] then sequence divs := factors(i,-1) if not abundant(i,divs) then wierd[i] = false elsif semiperfect(i,divs) then for j=i to limit by i do wierd[j] = false end for end if end if end for return wierd end function --constant MAX = 25, sieve_limit = 16313 constant MAX = 50, sieve_limit = 26533 sequence wierd := sieve(sieve_limit), res = {} for i=2 to sieve_limit by 2 do if wierd[i] then res &= i if length(res)=MAX then exit end if end if end for printf(1,"%s\n",{join(shorten(res,"weird numbers",5,"%d"))})
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Quackery
Quackery
say " ________ ___ ___ ________ ________ ___ __ _______ ________ ___ ___" cr say "|\ __ \|\ \|\ \|\ __ \|\ ____\|\ \|\ \ |\ ___ \ |\ __ \|\ \ / /|" cr say "\ \ \|\ \ \ \ \ \ \ \|\ \ \ \___|\ \ \/ /|\ \ __/|\ \ \|\ \ \ \/ / /" cr say " \ \ \ \ \ \ \ \ \ \ __ \ \ \ \ \ ___ \ \ \_|/ \ \ _ _\ \ / /" cr say " \ \ \_\ \ \ \_\ \ \ \ \ \ \ \____\ \ \\ \ \ \ \__\_\ \ \\ \ / / /" cr say " \ \_____ \ \_______\ \__\ \__\ \_______\ \__\\ \__\ \_______\ \__\\ _\ / /" cr say " \|___| \ \|_______|\|__|\|__|\|_______|\|__| \|__|\|_______|\|__|\|__| / /" cr say " \ \ \_______________________________________________________/ / /" cr say " \ \____________________________________________________________/ /" cr say " \|____________________________________________________________|/" cr
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Racket
Racket
  #lang racket/gui   ;; Get the language name (define str (cadr (regexp-match #rx"Welcome to (.*?) *v[0-9.]+\n*$" (banner))))   ;; Font to use (define font (make-object font% 12 "MiscFixed" 'decorative 'normal 'bold)) ;; (get-face-list) -> get a list of faces to try in the above   ;; Calculate the needed size (leave space for a drop-down shadow) (define-values [W H] (let ([bdc (make-object bitmap-dc% (make-object bitmap% 1 1 #t))]) (call-with-values (λ() (send* bdc (set-font font) (get-text-extent str font))) (λ(w h _1 _2) (values (+ 2 (inexact->exact (round w))) (+ 2 (inexact->exact (round h))))))))   ;; Draw the text (define bmp (make-bitmap W H #t)) (define dc (send bmp make-dc)) (send* dc (set-font font) (draw-text str 2 0))   ;; Grab the pixels as a string, 3d-ed with "/"s (define scr (let* ([size (* W H 4)] [buf (make-bytes size)]) (send bmp get-argb-pixels 0 0 W H buf) (define scr (make-string (* (add1 W) (add1 H)) #\space)) (for ([i (in-range 0 size 4)] [j (* W H)] #:unless (zero? (bytes-ref buf i))) (string-set! scr j #\@) (for ([k (list j (+ j W -1))] [c "/."] #:when #t [k (list (- k 1) (+ k W) (+ k W -1))] #:when (and (< -1 k (string-length scr)) (member (string-ref scr k) '(#\space #\.)))) (string-set! scr k c))) scr))   ;; Show it, dropping empty lines (let ([lines (for/list ([y H]) (substring scr (* y W) (* (add1 y) W)))]) (define (empty? l) (not (regexp-match #rx"[^ ]" l))) (for ([line (dropf-right (dropf lines empty?) empty?)]) (displayln (string-trim line #:left? #f))))  
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++.
#F.23
F#
  open System open System.Net open System.Text.RegularExpressions   async { use wc = new WebClient() let! html = wc.AsyncDownloadString(Uri("http://tycho.usno.navy.mil/cgi-bin/timer.pl")) return Regex.Match(html, @"<BR>(.+ UTC)").Groups.[1].Value } |> Async.RunSynchronously |> printfn "%s"  
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++.
#Factor
Factor
USING: http.client io sequences ;   "http://tycho.usno.navy.mil/cgi-bin/timer.pl" http-get nip [ "UTC" swap start [ 9 - ] [ 1 - ] bi ] keep subseq print
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
#F.23
F#
  open System.IO open System.Text.RegularExpressions let g=Regex("[A-Za-zÀ-ÿ]+").Matches(File.ReadAllText "135-0.txt") [for n in g do yield n.Value.ToLower()]|>List.countBy(id)|>List.sortBy(fun n->(-(snd n)))|>List.take 10|>List.iter(fun n->printfn "%A" n)  
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#J
J
circ0=:}: ] ;. _1 LF, 0 : 0 tH........ . . ... . . Ht.. ..... )
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Lua
Lua
local iup = require "iuplua"   iup.dialog{ title = "Window"; iup.vbox{ margin = "10x10"; iup.label{title = "A window"} } }:show()   iup.MainLoop()  
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#M2000_Interpreter
M2000 Interpreter
  Module DisplayWindow { Declare MyForm Form Method MyForm,"Show",1 } DisplayWindow  
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
CreateDocument[]
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
#JavaScript
JavaScript
  function wrap (text, limit) { if (text.length > limit) { // find the last space within limit var edge = text.slice(0, limit).lastIndexOf(' '); if (edge > 0) { var line = text.slice(0, edge); var remainder = text.slice(edge + 1); return line + '\n' + wrap(remainder, limit); } } return text; }  
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Ruby
Ruby
require 'rexml/document' include REXML   remarks = { %q(April) => %q(Bubbly: I'm > Tam and <= Emily),  %q(Tam O'Shanter) => %q(Burns: "When chapman billies leave the street ..."), %q(Emily) => %q(Short & shrift), }   doc = Document.new root = doc.add_element("CharacterRemarks")   remarks.each do |name, remark| root.add_element("Character", {'Name' => name}).add_text(remark) end   # output with indentation doc.write($stdout, 2)
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Phix
Phix
with javascript_semantics include builtins/xml.e constant xml = """ <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" /> </Students> """ sequence x = xml_parse(xml) procedure traverse(sequence x) if x[XML_TAGNAME]="Student" then puts(1,xml_get_attribute(x,"Name"),false) puts(1,"\n") else x = x[XML_CONTENTS] if not string(x) then for i=1 to length(x) do traverse(x[i]) end for end if end if end procedure traverse(x[XML_CONTENTS])
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#XPL0
XPL0
include c:\cxpl\codes; char A(10); \creates a static array of 10 bytes, pointed to by "A" char B; \declares a variable for a pointer to a dynamic array [A(3):= 14; B:= Reserve(10); \reserve 10 bytes and point to their starting address B(7):= 28; IntOut(0, A(3)+B(7)); \displays 42 ]
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.
#Onyx
Onyx
$Door dict def 1 1 100 {Door exch false put} for $Toggle {dup Door exch get not Door up put} def $EveryNthDoor {dup 100 {Toggle} for} def $Run {1 1 100 {EveryNthDoor} for} def $ShowDoor {dup `Door no. ' exch cvs cat ` is ' cat exch Door exch get {`open.\n'}{`shut.\n'} ifelse cat print flush} def Run 1 1 100 {ShowDoor} for
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Python
Python
'''Weird numbers'''   from itertools import chain, count, islice, repeat from functools import reduce from math import sqrt from time import time     # weirds :: Gen [Int] def weirds(): '''Non-finite stream of weird numbers. (Abundant, but not semi-perfect) OEIS: A006037 ''' def go(n): ds = descPropDivs(n) d = sum(ds) - n return [n] if 0 < d and not hasSum(d, ds) else [] return concatMap(go)(count(1))     # hasSum :: Int -> [Int] -> Bool def hasSum(n, xs): '''Does any subset of xs sum to n ? (Assuming xs to be sorted in descending order of magnitude)''' def go(n, xs): if xs: h, t = xs[0], xs[1:] if n < h: # Head too big. Forget it. Tail ? return go(n, t) else: # The head IS the target ? # Or the tail contains a sum for the # DIFFERENCE between the head and the target ? # Or the tail contains some OTHER sum for the target ? return n == h or go(n - h, t) or go(n, t) else: return False return go(n, xs)     # descPropDivs :: Int -> [Int] def descPropDivs(n): '''Descending positive divisors of n, excluding n itself.''' root = sqrt(n) intRoot = int(root) blnSqr = root == intRoot lows = [x for x in range(1, 1 + intRoot) if 0 == n % x] return [ n // x for x in ( lows[1:-1] if blnSqr else lows[1:] ) ] + list(reversed(lows))     # --------------------------TEST---------------------------   # main :: IO () def main(): '''Test'''   start = time() n = 50 xs = take(n)(weirds())   print( (tabulated('First ' + str(n) + ' weird numbers:\n')( lambda i: str(1 + i) )(str)(5)( index(xs) )(range(0, n))) ) print( '\nApprox computation time: ' + str(int(1000 * (time() - start))) + ' ms' )     # -------------------------GENERIC-------------------------   # chunksOf :: Int -> [a] -> [[a]] def chunksOf(n): '''A series of lists of length n, subdividing the contents of xs. Where the length of xs is not evenly divible, the final list will be shorter than n.''' return lambda xs: reduce( lambda a, i: a + [xs[i:n + i]], range(0, len(xs), n), [] ) if 0 < n else []     # compose (<<<) :: (b -> c) -> (a -> b) -> a -> c def compose(g): '''Right to left function composition.''' return lambda f: lambda x: g(f(x))     # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list or string over which a function f has been mapped. The list monad can be derived by using an (a -> [b]) function which wraps its output in a list (using an empty list to represent computational failure). ''' return lambda xs: chain.from_iterable(map(f, xs))     # index (!!) :: [a] -> Int -> a def index(xs): '''Item at given (zero-based) index.''' return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) )     # paddedMatrix :: a -> [[a]] -> [[a]] def paddedMatrix(v): ''''A list of rows padded to equal length (where needed) with instances of the value v.''' def go(rows): return paddedRows( len(max(rows, key=len)) )(v)(rows) return lambda rows: go(rows) if rows else []     # paddedRows :: Int -> a -> [[a]] -[[a]] def paddedRows(n): '''A list of rows padded (but never truncated) to length n with copies of value v.''' def go(v, xs): def pad(x): d = n - len(x) return (x + list(repeat(v, d))) if 0 < d else x return list(map(pad, xs)) return lambda v: lambda xs: go(v, xs) if xs else []     # showColumns :: Int -> [String] -> String def showColumns(n): '''A column-wrapped string derived from a list of rows.''' def go(xs): def fit(col): w = len(max(col, key=len))   def pad(x): return x.ljust(4 + w, ' ') return ''.join(map(pad, col))   q, r = divmod(len(xs), n) return unlines(map( fit, transpose(paddedMatrix('')( chunksOf(q + int(bool(r)))( xs ) )) )) return lambda xs: go(xs)     # succ :: Enum a => a -> a def succ(x): '''The successor of a value. For numeric types, (1 +).''' return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) )     # tabulated :: String -> (a -> String) -> # (b -> String) -> # Int -> # (a -> b) -> [a] -> String def tabulated(s): '''Heading -> x display function -> fx display function -> number of columns -> f -> value list -> tabular string.''' def go(xShow, fxShow, intCols, f, xs): w = max(map(compose(len)(xShow), xs)) return s + '\n' + showColumns(intCols)([ xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs ]) return lambda xShow: lambda fxShow: lambda nCols: ( lambda f: lambda xs: go( xShow, fxShow, nCols, f, xs ) )     # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): '''The prefix of xs of length n, or xs itself if n > length xs.''' return lambda xs: ( xs[0:n] if isinstance(xs, list) else list(islice(xs, n)) )     # transpose :: Matrix a -> Matrix a def transpose(m): '''The rows and columns of the argument transposed. (The matrix containers and rows can be lists or tuples).''' if m: inner = type(m[0]) z = zip(*m) return (type(m))( map(inner, z) if tuple != inner else z ) else: return m     # unlines :: [String] -> String def unlines(xs): '''A single string derived by the intercalation of a list of strings with the newline character.''' return '\n'.join(xs)     # until :: (a -> Bool) -> (a -> a) -> a -> a def until(p): '''The result of repeatedly applying f until p holds. The initial seed value is x.''' def go(f, x): v = x while not p(v): v = f(v) return v return lambda f: lambda x: go(f, x)     # MAIN ---------------------------------------------------- if __name__ == '__main__': main()
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Raku
Raku
# must be evenly padded with white-space$ my $text = q:to/END/;   @@@@@ @@ @ @ @ @@@ @ @ @ @@ @ @ @@@ @ @@ @ @@ @@@@@ @ @ @@ @ @ @@@@@ @ @@@@@ @ @ @@ @@ @ @ @ @ @@ @@ @ @@@ @ @@ @@@@   END   say '' for ^5; for $text.lines -> $_ is copy { my @chars = |「-+ ., ;: '"」.comb.pick(*) xx *; s:g [' '] = @chars.shift; print " $_ "; s:g [('@'+)(.)] = @chars.shift ~ $0; .say; } say '' for ^5;
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++.
#Forth
Forth
include unix/socket.fs   : extract-time ( addr len type len -- time len ) dup >r search 0= abort" that time not present!" dup >r begin -1 /string over 1- c@ [char] > = until \ seek back to <BR> at start of line r> - r> + ;   s" tycho.usno.navy.mil" 80 open-socket dup s\" GET /cgi-bin/timer.pl HTTP/1.0\n\n" rot write-socket dup pad 4096 read-socket s\" \r\n\r\n" search 0= abort" can't find headers!" \ skip headers s" UTC" extract-time type cr close-socket
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++.
#FunL
FunL
import io.Source   case Source.fromURL( 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', 'UTF-8' ).getLines().find( ('Eastern' in) ) of Some( time ) -> println( time.substring(4) ) None -> error( 'Easter time not found' )