task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Factor
Factor
  USING: ascii io math.statistics prettyprint sequences splitting ; IN: rosetta-code.word-count   lines " " join " .,?!:;()\"-" split harvest [ >lower ] map sorted-histogram <reversed> 10 head .  
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
#FreeBASIC
FreeBASIC
  #Include "file.bi" type tally as string s as long l end type   Sub quicksort(array() As String,begin As Long,Finish As Long) Dim As Long i=begin,j=finish Dim As String x =array(((I+J)\2)) While I <= J While array(I) < X :I+=1:Wend While array(J) > X :J-=1:Wend If I<=J Then Swap array(I),array(J): I+=1:J-=1 Wend If J >begin Then quicksort(array(),begin,J) If I <Finish Then quicksort(array(),I,Finish) End Sub   Sub tallysort(array() As tally,begin As Long,Finish As long) Dim As Long i=begin,j=finish Dim As tally x =array(((I+J)\2)) While I <= J While array(I).l > X .l:I+=1:Wend While array(J).l < X .l:J-=1:Wend If I<=J Then Swap array(I),array(J): I+=1:J-=1 Wend If J >begin Then tallysort(array(),begin,J) If I <Finish Then tallysort(array(),I,Finish) End Sub     Function loadfile(file As String) As String If Fileexists(file)=0 Then Print file;" not found":Sleep:End Dim As Long f=Freefile Open file For Binary Access Read As #f Dim As String text If Lof(f) > 0 Then text = String(Lof(f), 0) Get #f, , text End If Close #f Return text End Function   Function String_Split(s_in As String,chars As String,result() As String) As Long Dim As Long ctr,ctr2,k,n,LC=Len(chars) Dim As boolean tally(Len(s_in)) #macro check_instring() n=0 While n<Lc If chars[n]=s_in[k] Then tally(k)=true If (ctr2-1) Then ctr+=1 ctr2=0 Exit While End If n+=1 Wend #endmacro   #macro splice() If tally(k) Then If (ctr2-1) Then ctr+=1:result(ctr)=Mid(s_in,k+2-ctr2,ctr2-1) ctr2=0 End If #endmacro '================== LOOP TWICE ======================= For k =0 To Len(s_in)-1 ctr2+=1:check_instring() Next k If ctr=0 Then If Len(s_in) Andalso Instr(chars,Chr(s_in[0])) Then ctr=1': End If If ctr Then Redim result(1 To ctr): ctr=0:ctr2=0 Else Return 0 For k =0 To Len(s_in)-1 ctr2+=1:splice() Next k '===================== Last one ======================== If ctr2>0 Then Redim Preserve result(1 To ctr+1) result(ctr+1)=Mid(s_in,k+1-ctr2,ctr2) End If   Return Ubound(result) End Function   Redim As String s() redim as tally t() dim as string p1,p2,deliminators dim as long count,jmp dim as double tm=timer   Var L=loadfile("rosettalesmiserables.txt") L=lcase(L) 'get deliminators for n as long=1 to 96 p1+=chr(n) next for n as long=123 to 255 p2+=chr(n) next   deliminators=p1+p2   string_split(L,deliminators,s())   quicksort(s(),lbound(s),ubound(s))   For n As Long=lbound(s) To ubound(s)-1 if s(n+1)=s(n) then jmp+=1 if s(n+1)<>s(n) then count+=1 redim preserve t(1 to count) t(count).s=s(n) t(count).l=jmp jmp=0 end if Next   tallysort(t(),lbound(t),ubound(t))'sort by frequency print "frequency","word" print for n as long=lbound(t) to lbound(t)+9 print t(n).l,t(n).s next   Print print "time for operation ";timer-tm;" seconds" sleep  
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.
#Java
Java
<!DOCTYPE html><html><head><meta charset="UTF-8"> <title>Wireworld</title> <script src="wireworld.js"></script></head><body> <input type='file' accept='text/plain' onchange='openFile( event )' /> <br /></body></html>
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.
#mIRC_Scripting_Language
mIRC Scripting Language
alias CreateMyWindow { .window -Cp +d @WindowName 600 480 }
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.
#Nanoquery
Nanoquery
w = new(Nanoquery.Util.Windows.Window).setSize(300,300).setTitle("Nanoquery").show()
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import javax.swing.JFrame import javax.swing.JLabel import java.awt.BorderLayout import java.awt.Font import java.awt.Color   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ parse arg showText . select when showText.length = 0 then addText = isTrue when 'YES'.abbrev(showText.upper) then addText = isTrue when showText = '.' then addText = isTrue otherwise addText = isFalse end title = 'Rosetta Code - Window Creation' createFrame(title, addText)   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method createFrame(title, addText = boolean 0) public static do fenester = JFrame(title) fenester.setSize(600, 200) fenester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) if addText then decorate(fenester) fenester.setVisible(isTrue)   catch ex = Exception ex.printStackTrace() end   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method decorate(fenester = JFrame, textStr = 'This page intentionally left blank.') private static returns JFrame textlbl = JLabel(textStr) textfont = Font(Font.SERIF, Font.BOLD, 20) textlbl.setHorizontalAlignment(JLabel.CENTER) textlbl.setFont(textfont) textlbl.setForeground(Color.ORANGE) fenester.add(textlbl, BorderLayout.CENTER)   return fenester   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method isTrue() public static returns boolean return (1 == 1) -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method isFalse() public static returns boolean return \(1 == 1)  
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#jq
jq
# Simple greedy algorithm. # Note: very long words are not truncated. # input: a string # output: an array of strings def wrap_text(width): reduce splits("\\s+") as $word ([""]; .[length-1] as $current | ($word|length) as $wl | (if $current == "" then 0 else 1 end) as $pad | if $wl + $pad + ($current|length) <= width then .[-1] += ($pad * " ") + $word else . + [ $word] end );
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
using TextWrap   text = """Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour."""   println("# Wrapped at 80 chars") print_wrapped(text, width=80) println("\n\n# Wrapped at 70 chars") print_wrapped(text, width=70)
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.
#Rust
Rust
extern crate xml;   use std::collections::HashMap; use std::str;   use xml::writer::{EmitterConfig, XmlEvent};   fn characters_to_xml(characters: HashMap<String, String>) -> String { let mut output: Vec<u8> = Vec::new(); let mut writer = EmitterConfig::new() .perform_indent(true) .create_writer(&mut output);   writer .write(XmlEvent::start_element("CharacterRemarks")) .unwrap();   for (character, line) in &characters { let element = XmlEvent::start_element("Character").attr("name", character); writer.write(element).unwrap(); writer.write(XmlEvent::characters(line)).unwrap(); writer.write(XmlEvent::end_element()).unwrap(); }   writer.write(XmlEvent::end_element()).unwrap(); str::from_utf8(&output).unwrap().to_string() }   #[cfg(test)] mod tests { use super::characters_to_xml; use std::collections::HashMap;   #[test] fn test_xml_output() { let mut input = HashMap::new(); input.insert( "April".to_string(), "Bubbly: I'm > Tam and <= Emily".to_string(), ); input.insert( "Tam O'Shanter".to_string(), "Burns: \"When chapman billies leave the street ...\"".to_string(), ); input.insert("Emily".to_string(), "Short & shrift".to_string());   let output = characters_to_xml(input);   println!("{}", output); assert!(output.contains( "<Character name=\"Tam O&apos;Shanter\">Burns: \"When chapman \ billies leave the street ...\"</Character>" )); assert!(output .contains("<Character name=\"April\">Bubbly: I'm > Tam and &lt;= Emily</Character>")); assert!(output.contains("<Character name=\"Emily\">Short &amp; shrift</Character>")); } }
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.
#Scala
Scala
val names = List("April", "Tam O'Shanter", "Emily")   val remarks = List("Bubbly: I'm > Tam and <= Emily", """Burns: "When chapman billies leave the street ..."""", "Short & shrift")   def characterRemarks(names: List[String], remarks: List[String]) = <CharacterRemarks> { names zip remarks map { case (name, remark) => <Character name={name}>{remark}</Character> } } </CharacterRemarks>   characterRemarks(names, remarks)  
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#PHP
PHP
<?php $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>'; $xml = new XMLReader(); $xml->xml( $data ); while ( $xml->read() ) if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' ) echo $xml->getAttribute('Name') . "\n"; ?>
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)
#Yabasic
Yabasic
dim a(10) // create a numeric array with 11 elements, from 0 to 10 // Indexed at your preference (0 to 9 or 1 to 10) print arraysize(a(), 1) // this function return the element's higher number of an array   a(7) = 12.3 // access to an element of the array redim a(20) // alias of 'dim'. Grouth size of array   // Yabasic not allow direct downsize an array, but ...   dim a$(20) // create a textual array with 21 elements   print arraysize(a$(), 1)   void = token("1,2,3,4,5,6,7,8,9,10", a$(), ",") // populate it. Begun with element 1 (not 0).   print arraysize(a$(), 1) // hey! the size is down   print a$(5) // show the content of an element of the array   void = token("", a$()) // "erase" the array content AND redim it to 0 size   print arraysize(a$(), 1)   redim a$(10) // resize the array   print arraysize(a$(), 1)   print a$(5) // show the content of an element of the array. Now is empty
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.
#ooRexx
ooRexx
doors = .array~new(100) -- array containing all of the doors do i = 1 to doors~size -- initialize with a collection of closed doors doors[i] = .door~new(i) end   do inc = 1 to doors~size do d = inc to doors~size by inc doors[d]~toggle end end say "The open doors after 100 passes:" do door over doors if door~isopen then say door end   ::class door -- simple class to represent a door ::method init -- initialize an instance of a door expose id state -- instance variables of a door use strict arg id -- set the id state = .false -- initial state is closed   ::method toggle -- toggle the state of the door expose state state = \state   ::method isopen -- test if the door is open expose state return state   ::method string -- return a string value for a door expose state id if state then return "Door" id "is open" else return "Door" id "is closed"   ::method state -- return door state as a descriptive string expose state if state then return "open" else return "closed"
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
#Quackery
Quackery
[ stack ] is target ( --> s ) [ stack ] is success ( --> s ) [ stack ] is makeable ( --> s )   [ bit makeable take 2dup & 0 != dip [ | makeable put ] ] is made ( n --> b )   [ ' [ 0 ] swap dup target put properdivisors 0 over witheach + target share > not iff [ target release 2drop false ] done true success put 0 makeable put witheach [ over witheach [ over dip [ + dup target share = iff [ false success replace drop conclude ] done dup target share < iff [ dup made not iff join else drop ] else drop ] ] success share not if conclude drop ] drop target release makeable release success take ] is weird ( n --> b )   [] 0 [ 1+ dup weird if [ tuck join swap ] over size 25 = until ] drop echo
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
#Racket
Racket
#lang racket   (require math/number-theory)   (define (abundant? n proper-divisors) (> (apply + proper-divisors) n))   (define (semi-perfect? n proper-divisors) (let recur ((ds proper-divisors) (n n)) (or (zero? n) (and (positive? n) (pair? ds) (or (recur (cdr ds) n) (recur (cdr ds) (- n (car ds))))))))   (define (weird? n) (let ((proper-divisors (drop-right (divisors n) 1))) ;; divisors includes n (and (abundant? n proper-divisors) (not (semi-perfect? n proper-divisors)))))   (module+ main (let recur ((i 0) (n 1) (acc null)) (cond [(= i 25) (reverse acc)] [(weird? n) (recur (add1 i) (add1 n) (cons n acc))] [else (recur i (add1 n) acc)])))   (module+ test (require rackunit) (check-true (weird? 70)) (check-false (weird? 12)))
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
#Raven
Raven
[ " ##### #### # # #### # #" " # # # # # # # ## #" " # # # # # # ### # # #" " ##### ###### # # ### # # #" " # # # # # # # # ##" " # # # # # #### # #" ] as $str   "/" as $r1 ">" as $r2   #$str each "%s\n" print   $str each as $line $line r/#/@@@/g r/ /X/g r/X/ /g r/@ /@!/g r/@$/@!/g as $l1 $l1 "@" split $r1 join "!" split $r2 join print "\n" print  
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
#REXX
REXX
/*REXX program that displays a "REXX" 3D "ASCII art" as a logo. */ signal . /* Uses left-hand shadows, slightly raised view. 0=5~2?A?2?A? @)E)3@)B)1)2)8()2)1)2)8()2) @]~")2@]0`)0@)%)6{)%)0@)%)6{)%) #E)1#A@0}2)4;2(1}2)4;2( #3??3@0#2??@1}2)2;2(3}2)2;2( #2@5@)@2@0#2@A}2)0;2(5}2)0;2( #2@?"@)@2@0#2@?7}2){2(7}2){2( #2@6)@2@0#2@3)7}2)(2(9}2)(2( #2@??@2@0#2@?_)7}5(B}5( #F@0#8@8}3(D}3( #3%3?(1#3?_@7;3)C;3) #2@0}2)5#2@C;5)A;5) #2@1}2)4#2@B;2()2)8;2()2) #2@2}2)3#2@?"4;2(}2)6;2(}2) #2@3}2)2#2@5)2;2(1}2)4;2(1}2) #2@4}2)1#2@?%)0;2(3}2)2;2(3}2) 0]@2@5}2)1]@A@0)[2(5}2)1)[2(5}2) 1)@%@6}%)1)@`@1V%(7}%)1V%(7}%) */;.:a=sigL+1;signal ..;..:u='_';do j=a to sigl-1 _=sourceline(j);_=_('(',"/");_=_('[',"//");_=_('{',"///") _=_(';',"////");_=_(')',"\");_=_(']',"\\");_=_('}',"\\\");_=_('"',"__") _=_('%',"___");_=_('?',left('',4,u));_=_('`',left('',11,u));_=_('~',left('', ,13,u));_=_('=',left('',16,u));_=_('#','|\\|');_=translate(_,"|"u,'@"') do k=0 for 16;x=d2x(k,1);_=_(x,left('',k+1));end;say ' '_;end;exit;_:return, changestr(arg(1),_,arg(2))
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#Gambas
Gambas
Public Sub Main() Dim sWeb, sTemp, sOutput As String 'Variables   Shell "wget -O /tmp/web http://tycho.usno.navy.mil/cgi-bin/timer.pl" Wait 'Use 'wget' to save the web file in /tmp/   sWeb = File.Load("/tmp/web") 'Open file and store in sWeb   For Each sTemp In Split(sWeb, gb.NewLine) 'Split the file by NewLines.. If InStr(sTemp, "UTC") Then 'If the line contains "UTC" then.. sOutPut = sTemp 'Extract the line into sOutput Break 'Get out of here End If Next   Print Mid(sOutput, 5) 'Print the result without the '<BR>' tag   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
#Frink
Frink
d = new dict for w = select[wordList[read[normalizeUnicode["https://www.gutenberg.org/files/135/135-0.txt", "UTF-8"]]], %r/[[:alnum:]]/ ] d.increment[lc[w], 1]   println[join["\n", first[reverse[sort[array[d], {|a,b| a@1 <=> b@1}]], 10]]]
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn WordFrequency( textStr as CFStringRef, caseSensitive as Boolean, ascendingOrder as Boolean ) as CFStringRef '~'1 CFStringRef wrd CFDictionaryRef dict   // Depending on the value of the caseSensitive Boolean function parameter above, lowercase incoming text if caseSensitive == NO then textStr = fn StringLowercaseString( textStr )   // Trim non-alphabetic characters from string, and separate individual words with a space CFStringRef tempStr = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( textStr, fn CharacterSetInvertedSet( fn CharacterSetLetterSet ) ), @" " )   // Prepare separators to parse string into array CFMutableCharacterSetRef separators = fn MutableCharacterSetInit   // Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on. MutableCharacterSetFormUnionWithCharacterSet( separators, fn CharacterSetPunctuationSet )   // A character set containing all the whitespace and newline characters including characters in Unicode General Category Z*, U+000A U+000D, and U+0085. MutableCharacterSetFormUnionWithCharacterSet( separators, fn CharacterSetWhitespaceAndNewlineSet )   // Create array of separated words CFArrayRef tempArr = fn StringComponentsSeparatedByCharactersInSet( tempStr, separators )   // Create a counted set with each word and its frequency CountedSetRef freqencies = fn CountedSetWithArray( tempArr )   // Enumerate each word-frequency pair in the counted set... EnumeratorRef enumRef = fn CountedSetObjectEnumerator( freqencies )   // .. and use it to create array of words in counted set CFArrayRef array = fn EnumeratorAllObjects( enumRef )   // Create an empty mutable array CFMutableArrayRef wordArr = fn MutableArrayWithCapacity( 0 )   // Create word counter NSInteger totalWords = 0 // Enumerate each unique word, get its frequency, create its own key/value pair dictionary, add each dictionary into master array for wrd in array totalWords++ // Create dictionary with frequency and matching word dict = @{ @"count":fn NumberWithUnsignedInteger( fn CountedSetCountForObject( freqencies, wrd ) ), @"object":wrd } // Add each dictionary to the master mutable array, checking for a valid word by length if ( fn StringLength( wrd ) != 0 ) MutableArrayAddObject( wordArr, dict ) end if next   // Store the total words as a global application property AppSetProperty( @"totalWords", fn StringWithFormat( @"%d", totalWords - 1 ) )   // Sort the array in ascending or descending order as determined by the ascendingOrder Boolean function input parameter SortDescriptorRef descriptors = fn SortDescriptorWithKey( @"count", ascendingOrder ) CFArrayRef sortedArray = fn ArraySortedArrayUsingDescriptors( wordArr, @[descriptors] )   // Create an empty mutable string CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )   // Use each dictionary in sorted array to build the formatted output string NSInteger count = 1 for dict in sortedArray MutableStringAppendString( mutStr, fn StringWithFormat( @"%-7d %-7lu %@\n", count, fn StringIntegerValue( fn DictionaryValueForKey( dict, @"count" ) ), fn DictionaryValueForKey( dict, @"object" ) ) ) count++ next   // Create an immutable output string from mutable the string CFStringRef resultStr = fn StringWithFormat( @"%@", mutStr ) end fn = resultStr     local fn ParseTextFromWebsite( webSite as CFStringRef ) // Convert incoming string to URL CFURLRef textURL = fn URLWithString( webSite ) // Read contents of URL into a string CFStringRef textStr = fn StringWithContentsOfURL( textURL, NSUTF8StringEncoding, NULL )   // Start timer CFAbsoluteTime startTime = fn CFAbsoluteTimeGetCurrent // Calculate frequency of words in text and sort by occurrence CFStringRef frequencyStr = fn WordFrequency( textStr, NO, NO ) // Log results and post post processing time NSLogClear NSLog( @"%@", frequencyStr ) NSLog( @"Total unique words in document: %@", fn AppProperty( @"totalWords" ) ) // Stop timer and log elapsed processing time NSLog( @"Elapsed time: %f milliseconds.", ( fn CFAbsoluteTimeGetCurrent - startTime ) * 1000.0 ) end fn   dispatchglobal // Pass url for Les Misérables on Project Gutenberg and parse in background fn ParseTextFromWebsite( @"https://www.gutenberg.org/files/135/135-0.txt" ) dispatchend   HandleEvents  
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.
#JavaScript
JavaScript
<!DOCTYPE html><html><head><meta charset="UTF-8"> <title>Wireworld</title> <script src="wireworld.js"></script></head><body> <input type='file' accept='text/plain' onchange='openFile( event )' /> <br /></body></html>
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.
#jq
jq
def lines: split("\n")|length;   def cols: split("\n")[0]|length + 1; # allow for the newline   # Is there an "H" at [x,y] relative to position i, assuming the width is w? # Input is an array; 72 is "H" def isH(x; y; i; w): if .[i+ w*y + x] == 72 then 1 else 0 end;   def neighborhood(i;w): isH(-1; -1; i; w) + isH(0; -1; i; w) + isH(1; -1; i; w) + isH(-1; 0; i; w) + isH(1; 0; i; w) + isH(-1; 1; i; w) + isH(0; 1; i; w) + isH(1; 1; i; w) ;   # The basic rules: # Input: a world # Output: the next state of .[i] def evolve(i; width) : # "Ht. " | explode => [ 72, 116, 46, 32 ] .[i] as $c | if $c == 32 then $c # " " => " " elif $c == 116 then 46 # "t" => "." elif $c == 72 then 116 # "H" => "t" elif $c == 46 then # "." # updates are "simultaneous" i.e. relative to $world neighborhood(i; width) as $sum | (if [1,2]|index($sum) then 72 else . end) # "H" else $c end ;   # [world, lines, cols] | next(w) => [world, lines, cols] def next: .[0] as $world | .[1] as $lines | .[2] as $w | reduce range(0; $world|length) as $i ($world; $world | evolve($i; $w) as $next | if .[$i] == $next then . else .[$i] = $next end ) | [., $lines, $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.
#Nim
Nim
import gintro/[glib, gobject, gtk, gio]   proc activate(app: Application) = ## Activate the application. let window = newApplicationWindow(app) window.setTitle("Window for Rosetta") window.setSizeRequest(640, 480) window.showAll()   let app = newApplication(Application, "Rosetta.Window") discard app.connect("activate", activate) discard app.run()
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.
#Objeck
Objeck
  use Gtk2;   bundle Default { class GtkHello { function : Main(args : String[]) ~ Nil { window := GtkWindow->New(); delete_callback := Events->DeleteEvent(GtkWidget) ~ Nil; window->SignalConnect(Signal->Destroy, window->As(GtkWidget), delete_callback); window->SetTitle("Title"); window->Show(); Appliction->Main(); } } }  
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
#Klingphix
Klingphix
:wordwrap %long !long  %ps 0 !ps   split len [ drop pop swap len $ps + !ps $ps $long > [ len !ps nl ] if print " " print $ps 1 + !ps ] for drop ;     "tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH. boQchugh Hoch, mu'ghom Dun mojlaH. tlhIngan maH! Qapla'! DaH tlhIngan Hol mu'ghom'a' Dalegh. qawHaqvam chenmoHlu'DI' 'oHvaD wIqIpe'DIya ponglu'. 'ach jInmolvamvaD Saghbe'law' tlhIngan Hol, DIS 2005 'oH mevmoHlu'. 'ach DIS 2006 jar wa'maHcha'DIch Wikia jInmolDaq vIHta'. Hov lengvaD chenmoHlu' tlhIngan Hol'e' 'ej DaH 'oH ghojtaH ghot law'. Qapbej Holvam wIcha'meH, qawHaqvam chenmoHlu'. taHjaj wo', taHjaj Hol! Sov qawHaq tlhab 'oH 'ej ghItlhmey DIqonmeH tlhIngan Hol wIlo'. ghItlhmey chenmoHlaH 'ej choHlaH tlhIngan Hol jatlhlaHbogh Hoch ghotpu''e'. wej tIn Sov qawHaqvam, 'ach ghurlI' 'e' wItul. DaH 229 ghItlhmey ngaS. vay' Daghel DaneHchugh qoj vay' Dachup DaneHchugh, vaj tachDaq maghom."   dup   72 wordwrap nl nl 100 wordwrap nl nl   "End " input
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.
#SenseTalk
SenseTalk
put ("April", "Tam O'Shanter", "Emily") into names put ("Bubbly: I'm > Tam and <= Emily", <<Burns: "When chapman billies leave the street ...">>, "Short & shrift") into remarks put (_tag: "CharacterRemarks") as tree into document repeat for each item name in names insert (_tag: "Character", name: name, _children: item the counter of remarks) as tree into document's _children end repeat put document
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.
#Sidef
Sidef
require('XML::Mini::Document');   var students = [ ["April", "Bubbly: I'm > Tam and <= Emily"], ["Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""], ["Emily", "Short & shrift"] ];   var doc = %s'XML::Mini::Document'.new; var root = doc.getRoot; var studs = root.createChild("CharacterRemarks");   students.each { |s| var stud = studs.createChild("Character"); stud.attribute("name", s[0]); stud.text(s[1]); };   print doc.toString;
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
#PicoLisp
PicoLisp
(load "@lib/xm.l")   (mapcar '((L) (attr L 'Name)) (body (in "file.xml" (xml))) )
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)
#Z80_Assembly
Z80 Assembly
Array: ;an array located in RAM. Its values can be updated freely. byte 0,0,0,0,0 byte 0,0,0,0,0 byte 0,0,0,0,0 byte 0,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.
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE VARIABLE lopen AS LOGICAL NO-UNDO EXTENT 100. DEFINE VARIABLE idoor AS INTEGER NO-UNDO. DEFINE VARIABLE ipass AS INTEGER NO-UNDO. DEFINE VARIABLE cresult AS CHARACTER NO-UNDO.   DO ipass = 1 TO 100: idoor = 0. DO WHILE idoor <= 100: idoor = idoor + ipass. IF idoor <= 100 THEN lopen[ idoor ] = NOT lopen[ idoor ]. END. END.   DO idoor = 1 TO 100: cresult = cresult + STRING( lopen[ idoor ], "1 /0 " ). IF idoor MODULO 10 = 0 THEN cresult = cresult + "~r":U. END.   MESSAGE cresult VIEW-AS ALERT-BOX.  
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
#Raku
Raku
sub abundant (\x) { my @l = x.is-prime ?? 1 !! flat 1, (2 .. x.sqrt.floor).map: -> \d { my \y = x div d; next if y * d !== x; d !== y ?? (d, y) !! d }; (my $s = @l.sum) > x ?? ($s, |@l.sort(-*)) !! (); }   my @weird = (2, 4, {|($_ + 4, $_ + 6)} ... *).map: -> $n { my ($sum, @div) = $n.&abundant; 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 ($n %% 70) and ($n div 70).is-prime { # It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird } else { my $next; my $l = @div.shift; ++$next and last if $_.sum == $n - $l for @div.combinations; next if $next; } $n }   put "The first 25 weird numbers:\n", @weird[^25];
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
#Ruby
Ruby
text = <<EOS #### # # # # # # # #### # # ### # # # # # # # # # # # # # # # # # # # ### ### # # # EOS   def banner3D_1(text, shift=-1) txt = text.each_line.map{|line| line.gsub('#','__/').gsub(' ',' ')} offset = Array.new(txt.size){|i| " " * shift.abs * i} offset.reverse! if shift < 0 puts offset.zip(txt).map(&:join) end banner3D_1(text)   puts # Other display: def banner3D_2(text, shift=-2) txt = text.each_line.map{|line| line.chomp + ' '} offset = txt.each_index.map{|i| " " * shift.abs * i} offset.reverse! if shift < 0 txt.each_with_index do |line,i| line2 = offset[i] + line.gsub(' ',' ').gsub('#','///').gsub('/ ','/\\') puts line2, line2.tr('/\\\\','\\\\/') end end banner3D_2(text)   puts # Another display: def banner3D_3(text) txt = text.each_line.map(&:rstrip) offset = [*0...txt.size].reverse area = Hash.new(' ') box = [%w(/ / / \\), %w(\\ \\ \\ /)] txt.each_with_index do |line,i| line.each_char.with_index do |c,j| next if c==' ' x = offset[i] + 2*j box[0].each_with_index{|c,k| area[[x+k,i ]] = c} box[1].each_with_index{|c,k| area[[x+k,i+1]] = c} end end (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax) puts (ymin..ymax).map{|y| (xmin..xmax).map{|x| area[[x,y]]}.join} end   banner3D_3 <<EOS #### # # # # # # # # # # #### # # #### # # # # # # # # # # # # # # # # # # # # # # # # # # # ### #### # # # EOS
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++.
#Go
Go
package main   import ( "bytes" "encoding/xml" "fmt" "io" "net/http" "regexp" "time" )   func main() { resp, err := http.Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl") if err != nil { fmt.Println(err) // connection or request fail return } defer resp.Body.Close() var us string var ux int utc := []byte("UTC") for p := xml.NewDecoder(resp.Body); ; { t, err := p.RawToken() switch err { case nil: case io.EOF: fmt.Println("UTC not found") return default: fmt.Println(err) // read or parse fail return } if ub, ok := t.(xml.CharData); ok { if ux = bytes.Index(ub, utc); ux != -1 { // success: found a line with the string "UTC" us = string([]byte(ub)) break } } } // first thing to try: parsing the expected date format if t, err := time.Parse("Jan. 2, 15:04:05 UTC", us[:ux+3]); err == nil { fmt.Println("parsed UTC:", t.Format("January 2, 15:04:05")) return } // fallback: search for anything looking like a time and print that tx := regexp.MustCompile("[0-2]?[0-9]:[0-5][0-9]:[0-6][0-9]") if justTime := tx.FindString(us); justTime > "" { fmt.Println("found UTC:", justTime) return } // last resort: just print the whole element containing "UTC" and hope // there is a human readable time in there somewhere. fmt.Println(us) }
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
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "regexp" "sort" "strings" )   type keyval struct { key string val int }   func main() { reg := regexp.MustCompile(`\p{Ll}+`) bs, err := ioutil.ReadFile("135-0.txt") if err != nil { log.Fatal(err) } text := strings.ToLower(string(bs)) matches := reg.FindAllString(text, -1) groups := make(map[string]int) for _, match := range matches { groups[match]++ } var keyvals []keyval for k, v := range groups { keyvals = append(keyvals, keyval{k, v}) } sort.Slice(keyvals, func(i, j int) bool { return keyvals[i].val > keyvals[j].val }) fmt.Println("Rank Word Frequency") fmt.Println("==== ==== =========") for rank := 1; rank <= 10; rank++ { word := keyvals[rank-1].key freq := keyvals[rank-1].val fmt.Printf("%2d  %-4s  %5d\n", rank, word, freq) } }
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Julia
Julia
function surround2D(b, i, j) h, w = size(b) [b[x,y] for x in i-1:i+1, y in j-1:j+1 if (0 < x <= h && 0 < y <= w)] end   surroundhas1or2(b, i, j) = 0 < sum(map(x->Char(x)=='H', surround2D(b, i, j))) <= 2 ? 'H' : '.'   function boardstep!(currentboard, nextboard) x, y = size(currentboard) for j in 1:y, i in 1:x ch = Char(currentboard[i, j]) if ch == ' ' continue else nextboard[i, j] = (ch == 'H') ? 't' : (ch == 't' ? '.' : surroundhas1or2(currentboard, i, j)) end end end   const b1 = " " * " tH " * " . .... " * " .. " * " " const mat = reshape(map(x->UInt8(x[1]), split(b1, "")), (9, 5))' const mat2 = copy(mat)   function printboard(mat) for i in 1:size(mat)[1] println("\t", join([Char(c) for c in mat[i,:]], "")) end end   println("Starting Wireworld board:") printboard(mat) for step in 1:8 boardstep!(mat, mat2) println(" Step $step:") printboard(mat2) mat .= mat2 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.
#Liberty_BASIC
Liberty BASIC
  WindowWidth = 840 WindowHeight = 600   dim p$( 40, 25), q$( 40, 25)   empty$ = " " ' white tail$ = "t" ' yellow head$ = "H" ' black conductor$ = "." ' red   jScr = 0   nomainwin   menu #m, "File", "Load", [load], "Quit", [quit]   open "wire world" for graphics_nf_nsb as #m #m "trapclose [quit]" 'timer 1000, [tmr] wait   end   [quit] close #m end   [load] 'timer 0 filedialog "Open WireWorld File", "*.ww", file$ open file$ for input as #in y =0 while not( eof( #in)) line input #in, lijn$ ' print "|"; lijn$; "|" for x =0 to len( lijn$) -1 p$( x, y) =mid$( lijn$, x +1, 1)   select case p$( x, y) case " " clr$ ="white" case "t" clr$ ="yellow" case "H" clr$ ="black" case "." clr$ ="red" end select   #m "goto " ; 4 +x *20; " "; 4 +y *20 #m "backcolor "; clr$ #m "down" #m "boxfilled "; 4 +x *20 +19; " "; 4 +y *20 +19 #m "up ; flush" next x y =y +1 wend close #in 'notice "Ready to run." timer 1000, [tmr] wait   [tmr] timer 0 scan   for x =0 to 40 ' copy temp array /current array for y =0 to 25 q$( x, y) =p$( x, y) next y next x   for y =0 to 25 for x =0 to 40 select case q$( x, y) case head$ ' heads ( black) become tails ( yellow) p$( x, y ) =tail$ clr$ ="yellow"   case tail$ ' tails ( yellow) become conductors ( red) p$( x, y ) =conductor$ clr$ ="red"   case conductor$ ' hCnt =0   xL =x -1: if xL < 0 then xL =40 ' wrap-round edges at all four sides xR =x +1: if xR >40 then xR = 0 yA =y -1: if yA < 0 then yA =25 yB =y +1: if yB >40 then yB = 0   if q$( xL, y ) =head$ then hCnt =hCnt +1 ' Moore environment- 6 neighbours if q$( xL, yA) =head$ then hCnt =hCnt +1 ' count all neighbours currently heads if q$( xL, yB) =head$ then hCnt =hCnt +1   if q$( xR, y ) =head$ then hCnt =hCnt +1 if q$( xR, yA) =head$ then hCnt =hCnt +1 if q$( xR, yB) =head$ then hCnt =hCnt +1   if q$( x, yA) =head$ then hCnt =hCnt +1 if q$( x, yB) =head$ then hCnt =hCnt +1   if ( hCnt =1) or ( hCnt =2) then ' conductor ( red) becomes head ( yellow) in this case only p$( x, y ) =head$ ' otherwise stays conductor ( red). clr$ ="black" else p$( x, y ) =conductor$ clr$ ="red" end if   case else clr$ ="white" end select   #m "goto " ; 4 +x *20; " "; 4 +y *20 #m "backcolor "; clr$ #m "down" #m "boxfilled "; 4 +x *20 +19; " "; 4 +y *20 +19 #m "up" next x next y #m "flush" #m "getbmp scr 0 0 400 300"   'bmpsave "scr", "R:\scrJHF" +right$( "000" +str$( jScr), 3) +".bmp" jScr =jScr+1 if jScr >20 then wait timer 1000, [tmr] 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.
#Objective-C
Objective-C
#include <Foundation/Foundation.h> #include <AppKit/AppKit.h>   @interface Win : NSWindow { } - (void)applicationDidFinishLaunching: (NSNotification *)notification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; @end     @implementation Win : NSWindow -(instancetype) init { if ((self = [super initWithContentRect: NSMakeRect(0, 0, 800, 600) styleMask: (NSTitledWindowMask | NSClosableWindowMask) backing: NSBackingStoreBuffered defer: NO])) {   [self setTitle: @"A Window"]; [self center]; } return self; }   - (void)applicationDidFinishLaunching: (NSNotification *)notification { [self orderFront: self]; }   - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification { return YES; } @end   int main() { @autoreleasepool {   [NSApplication sharedApplication]; Win *mywin = [[Win alloc] init]; [NSApp setDelegate: mywin]; [NSApp runModalForWindow: mywin];   } return EXIT_SUCCESS; }
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
#Kotlin
Kotlin
// version 1.1.3   val text = "In olden times when wishing still helped one, there lived a king " + "whose daughters were all beautiful, but the youngest was so beautiful " + "that the sun itself, which has seen so much, was astonished whenever " + "it shone in her face. Close by the king's castle lay a great dark " + "forest, and under an old lime tree in the forest was a well, and when " + "the day was very warm, the king's child went out into the forest and " + "sat down by the side of the cool fountain, and when she was bored she " + "took a golden ball, and threw it up on high and caught it, and this " + "ball was her favorite plaything."   fun greedyWordwrap(text: String, lineWidth: Int): String { val words = text.split(' ') val sb = StringBuilder(words[0]) var spaceLeft = lineWidth - words[0].length for (word in words.drop(1)) { val len = word.length if (len + 1 > spaceLeft) { sb.append("\n").append(word) spaceLeft = lineWidth - len } else { sb.append(" ").append(word) spaceLeft -= (len + 1) } } return sb.toString() }   fun main(args: Array<String>) { println("Greedy algorithm - wrapped at 72:") println(greedyWordwrap(text, 72)) println("\nGreedy algorithm - wrapped at 80:") println(greedyWordwrap(text, 80)) }
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.
#Slate
Slate
lobby define: #remarks -> ( {'April' -> 'Bubbly: I\'m > Tam and <= Emily'. 'Tam O\'Shanter' -> 'Burns: "When chapman billies leave the street ..."'. 'Emily' -> 'Short & shrift'. } as: Dictionary).   define: #writer -> (Xml Writer newOn: '' new writer). writer inTag: 'CharacterRemarks' do: [| :w | lobby remarks keysAndValuesDo: [| :name :remark | w inTag: 'Character' do: [| :w | w ; remark] &attributes: {'name' -> name}]. ].   inform: writer contents
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.
#Tcl
Tcl
proc xquote string { list [string map "' &apos; \\\" &quot; < &gt; > &lt; & &amp;" $string] } proc < {name attl args} { set res <$name foreach {att val} $attl { append res " $att='$val'" } if {[llength $args]} { append res > set sep "" foreach a $args { append res $sep $a set sep \n } append res </$name> } else {append res />} return $res } set cmd {< CharacterRemarks {}} foreach {name comment} { April "Bubbly: I'm > Tam and <= Emily" "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" Emily "Short & shrift" } { append cmd " \[< Character {Name [xquote $name]} [xquote $comment]\]" } puts [eval $cmd]
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
#Pike
Pike
  string in = "<Students>\n" " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" " <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" " <Pet Type=\"dog\" Name=\"Rover\" />\n" " </Student>\n" " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" "</Students>\n";   object s = Parser.XML.Tree.simple_parse_input(in);   array collect = ({}); s->walk_inorder(lambda(object node) { if (node->get_tag_name() == "Student") collect += ({ node->get_attributes()->Name }); }); write("%{%s\n%}", collect);
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)
#zkl
zkl
var array=List(); // array of size 0 array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5 array[3]=4; array[3] //-->4 array+9; //append a 9 to the end, same as array.append(9)
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.
#OxygenBasic
OxygenBasic
def doors 100 int door[doors],i ,j, c string cr,tab,pr ' for i=1 to doors for j=i to doors step i door[j]=1-door[j] if door[j] then c++ else c-- next next ' cr=chr(13) chr(10) pr="Doors Open: " c cr cr ' for i=1 to doors if door[i] then pr+=i cr next print pr
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
#REXX
REXX
/*REXX program finds and displays N weird numbers in a vertical format (with index).*/ parse arg n cols . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/ if cols=='' | cols=="," then cols= 10 /* " " " " " " */ w= 10 /*width of a number in any column. */ if cols>0 then say ' index │'center(' weird numbers', 1 + cols*(w+1) ) if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─') idx= 1; $= /*index for the output list; $: 1 line*/ weirds= 0 /*the count of weird numbers (so far).*/ do j=2 by 2 until weirds==n /*examine even integers 'til have 'nuff*/ if \weird(j) then iterate /*Not a weird number? Then skip it. */ weirds= weirds + 1 /*bump the count of weird numbers. */ c= commas(j) /*maybe add commas to the number. */ $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/ if weirds//cols\==0 then iterate /*have we populated a line of output? */ say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */ idx= idx + cols /*bump the index count for the output*/ end /*j*/   if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─') say say 'Found ' commas(weirds) ' weird numbers' exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do ic=length(_)-3 to 1 by -3; _=insert(',', _, ic); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ DaS: procedure; parse arg x 1 z 1,b; a= 1 /*get X,Z,B (the 1st arg); init A list.*/ r= 0; q= 1 /* [↓] ══integer square root══ ___ */ do while q<=z; q=q*4; end /*R: an integer which will be √ X */ do while q>1; q=q%4; _= z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/ sig= a /*initialize the sigma so far. ___ */ do j=2 to r - (r*r==x) /*divide by some integers up to √ X */ if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α and ß. */ sig= sig +j +x%j /*bump the sigma (the sum of divisors).*/ end end /*j*/ /* [↑]  % is the REXX integer division*/ /* [↓] adjust for a square. ___*/ if j*j==x then return sig+j a j b /*Was X a square? If so, add √ X */ return sig a b /*return the divisors (both lists). */ /*──────────────────────────────────────────────────────────────────────────────────────*/ weird: procedure; parse arg x . /*obtain a # to be tested for weirdness*/ if x<70 | x//3==0 then return 0 /*test if X is too low or multiple of 3*/ parse value DaS(x) with sigma divs /*obtain sigma and the proper divisors.*/ if sigma<=x then return 0 /*X isn't abundant (sigma too small).*/ #= words(divs) /*count the number of divisors for X. */ if #<3 then return 0 /*Not enough divisors? " " */ if #>15 then return 0 /*number of divs > 15? It's not weird.*/ a.= /*initialize the A. stemmed array.*/ do i=1 for #; _= word(divs, i) /*obtain one of the divisors of X. */ @.i= _; a._= . /*assign proper divs──►@ array; also id*/ end /*i*/ df= sigma - x /*calculate difference between Σ and X.*/ if a.df==. then return 0 /*Any divisor is equal to DF? Not weird*/ c= 0 /*zero combo counter; calc. power of 2.*/ do p=1 for 2**#-2; c= c + 1 /*convert P──►binary with leading zeros*/ yy.c= strip( x2b( d2x(p) ), 'L', 0) /*store this particular combination. */ end /*p*/ /* [↓] decreasing partitions is faster*/ do part=c by -1 for c; s= 0 /*test of a partition add to the arg X.*/ _= yy.part; L= length(_) /*obtain one method of partitioning. */ do cp=L by -1 for L /*obtain a sum of a partition. */ if substr(_,cp,1) then do; s= s + @.cp /*1 bit? Then add ──►S*/ if s==x then return 0 /*Sum equal? Not weird*/ if s==df then return 0 /*Sum = DF? " " */ if s>x then iterate /*Sum too big? Try next*/ end end /*cp*/ end /*part*/; return 1 /*no sum equal to X, so X is 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
#Rust
Rust
pub fn char_from_id(id: u8) -> char { [' ', '#', '/', '_', 'L', '|', '\n'][id as usize] }   const ID_BITS: u8 = 3;   pub fn decode(code: &[u8]) -> String { let mut ret = String::new(); let mut carry = 0; let mut carry_bits = 0; for &b in code { let mut bit_pos = ID_BITS - carry_bits; let mut cur = b >> bit_pos; let mask = (1 << bit_pos) - 1; let id = carry | (b & mask) << carry_bits; ret.push(char_from_id(id)); while bit_pos + ID_BITS < 8 { ret.push(char_from_id(cur & ((1 << ID_BITS) - 1))); cur >>= ID_BITS; bit_pos += ID_BITS; } carry = cur; carry_bits = 8 - bit_pos; } ret }   fn main() { let code = [ 72, 146, 36, 0, 0, 0, 0, 0, 0, 0, 128, 196, 74, 182, 41, 1, 0, 0, 0, 0, 0, 0, 160, 196, 77, 0, 52, 1, 18, 0, 9, 144, 36, 9, 146, 36, 113, 147, 36, 9, 160, 4, 80, 130, 100, 155, 160, 41, 145, 155, 108, 74, 128, 38, 64, 19, 41, 73, 2, 160, 137, 155, 0, 84, 130, 38, 64, 19, 112, 155, 18, 160, 137, 155, 0, 160, 18, 42, 73, 18, 36, 73, 2, 128, 74, 76, 1, 0, 40, 128, 219, 38, 104, 219, 4, 0, 160, 0 ];   println!("{}", decode(&code)); }
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
#Scala
Scala
def ASCII3D = {   val name = """ * ** ** * * * * * * * * * * * * * * * * * * * *** * *** * * * * * * * * * * * * * * ** ** * * *** * * * * """   // Create Array   def getMaxSize(s: String): (Int, Int) = { var width = 0 var height = 0   val nameArray = s.split("\n") height = nameArray.size nameArray foreach { i => width = (i.size max width) }   (width, height) }   val size = getMaxSize(name) var arr = Array.fill(size._2 + 1, (size._1 * 3) + (size._2 + 1))(' ')   // // Map astrisk to 3D cube // val cubeTop = """///\""" //" val cubeBottom = """\\\/""" //"   val nameArray = name.split("\n")   for (j <- (0 until nameArray.size)) { for (i <- (0 until nameArray(j).size)) { if (nameArray(j)(i) == '*') { val indent = nameArray.size - j arr(j) = arr(j) patch ((i * 3 + indent), cubeTop, cubeTop.size) arr(j + 1) = arr(j + 1) patch ((i * 3 + indent), cubeBottom, cubeBottom.size) } } }   // // Map Array to String // var name3D = ""   for (j <- (0 until arr.size)) { for (i <- (0 until arr(j).size)) { name3D += arr(j)(i) } name3D += "\n" } name3D }   println(ASCII3D)
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++.
#Groovy
Groovy
def time = "unknown" def text = new URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl').eachLine { line -> def matcher = (line =~ "<BR>(.+) UTC") if (matcher.find()) { time = matcher[0][1] } } println "UTC Time was '$time'"
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++.
#Haskell
Haskell
import Data.List import Network.HTTP (simpleHTTP, getResponseBody, getRequest)   tyd = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"   readUTC = simpleHTTP (getRequest tyd)>>= fmap ((!!2).head.dropWhile ("UTC"`notElem`).map words.lines). getResponseBody>>=putStrLn
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
#Groovy
Groovy
def topWordCounts = { String content, int n -> def mapCounts = [:] content.toLowerCase().split(/\W+/).each { mapCounts[it] = (mapCounts[it] ?: 0) + 1 } def top = (mapCounts.sort { a, b -> b.value <=> a.value }.collect{ it })[0..<n] println "Rank Word Frequency\n==== ==== =========" (0..<n).each { printf ("%4d %-4s %9d\n", it+1, top[it].key, top[it].value) } }
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.
#Logo
Logo
to wireworld :filename :speed ;speed in n times per second, approximated Make "speed 60/:speed wireworldread :filename Make "bufferfield (mdarray (list :height :width) 0) for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :bufferfield mditem (list :i :j) :field]] pu ht Make "gen 0 while ["true] [ ;The user will have to halt it :P  ;clean seth 90 setxy 0 20  ;label :gen sety 0 for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :field mditem (list :i :j) :bufferfield]] for [i 0 :height-1] [ for [j 0 :width-1] [ if (mditem (list :i :j) :field)=[] [setpixel [255 255 255]] ;blank if (mditem (list :i :j) :field)=1 [setpixel [0 0 0] if wn :j :i 2 [mdsetitem (list :i :j) :bufferfield 2]] ;wire if (mditem (list :i :j) :field)=2 [setpixel [0 0 255] mdsetitem (list :i :j) :bufferfield 3] ;head if (mditem (list :i :j) :field)=3 [setpixel [255 0 0] mdsetitem (list :i :j) :bufferfield 1] ;tail setx xcor+1 ] setxy 0 ycor-1 ] Make "gen :gen+1 wait :speed ] end   to wireworldread :filename local [line] openread :filename setread :filename Make "width 0 Make "height 0 ; first pass, take dimensions while [not eofp] [ Make "line readword if (count :line)>:width [Make "width count :line] Make "height :height+1 ] ; second pass, load data setreadpos 0 Make "field (mdarray (list :height :width) 0) for [i 0 :height-1] [ Make "line readword foreach :line [ if ?=char 32 [mdsetitem (list :i #-1) :field []] if ?=". [mdsetitem (list :i #-1) :field 1] if ?="H [mdsetitem (list :i #-1) :field 2] if ?="t [mdsetitem (list :i #-1) :field 3] ] ] setread [] close :filename end   to wn :x :y :thing ;WireNeighbourhood Make "neighbours 0 if (mditem (list :y-1 :x) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y-1 :x+1) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y :x+1) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y+1 :x+1) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y+1 :x) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y+1 :x-1) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y :x-1) :field)=:thing [Make "neighbours :neighbours+1] if (mditem (list :y-1 :x-1) :field)=:thing [Make "neighbours :neighbours+1] ifelse OR :neighbours=1 :neighbours=2 [op "true] [op "false] 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.
#OCaml
OCaml
let () = let top = Tk.openTk() in Wm.title_set top "An Empty Window"; Wm.geometry_set top "240x180"; Tk.mainLoop (); ;;
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#OpenEdge_ABL.2FProgress_4GL
OpenEdge ABL/Progress 4GL
    DEFINE VAR C-Win AS WIDGET-HANDLE NO-UNDO.   CREATE WINDOW C-Win ASSIGN HIDDEN = YES TITLE = "OpenEdge Window Display" HEIGHT = 10.67 WIDTH = 95.4 MAX-HEIGHT = 16 MAX-WIDTH = 95.4 VIRTUAL-HEIGHT = 16 VIRTUAL-WIDTH = 95.4 RESIZE = yes SCROLL-BARS = no STATUS-AREA = no BGCOLOR = ? FGCOLOR = ? KEEP-FRAME-Z-ORDER = yes THREE-D = yes MESSAGE-AREA = no SENSITIVE = yes.   VIEW C-Win.   ON WINDOW-CLOSE OF C-Win /* <insert window title> */ DO: /* This event will close the window and terminate the procedure. */ APPLY "CLOSE":U TO THIS-PROCEDURE. RETURN NO-APPLY. END.   WAIT-FOR CLOSE OF THIS-PROCEDURE.    
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
#Lambdatalk
Lambdatalk
  {def text Personne n’a sans doute oublié le terrible coup de vent de nord-est qui se déchaîna au milieu de l’équinoxe de cette année, et pendant lequel le baromètre tomba à sept cent dix millimètres. Ce fut un ouragan, sans intermittence, qui dura du 18 au 26 mars. Les ravages qu’il produisit furent immenses en Amérique, en Europe, en Asie, sur une zone large de dix-huit cents milles, qui se dessinait obliquement à l’équateur, depuis le trente-cinquième parallèle nord jusqu’au quarantième parallèle sud ! (L’île mystérieuse / Jules Verne)} -> text  
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lasso
Lasso
define wordwrap( text::string, row_length::integer = 75 ) => { return regexp(`(?is)(.{1,` + #row_length + `})(?:$|\W)+`, '$1<br />\n', #text, true) -> replaceall }   local(text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat ornare lectus, dignissim iaculis libero consequat sed. Proin quis magna in arcu sagittis consequat sed ac risus. Ut a pharetra dui. Phasellus molestie, mauris eget scelerisque laoreet, diam dolor vulputate nulla, in porta sem sem sit amet lacus.')   wordwrap(#text, 40) '<hr />' wordwrap(#text) '<hr />' wordwrap(#text, 90)
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.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT STRUCTURE xmloutput DATA '<CharacterRemarks>' DATA * ' <Character name="' names +'">' remarks +'</Character>' DATA = '</CharacterRemarks>' ENDSTRUCTURE BUILD X_TABLE entitysubst=" >> &gt; << &lt; & &amp; " ERROR/STOP CREATE ("dest",seq-o,-std-) ACCESS d: WRITE/ERASE/STRUCTURE "dest" num,str str="xmloutput" names=* DATA April DATA Tam O'Shanter DATA Emily remarks=* DATA Bubbly: I'm > Tam and <= Emily DATA Burns: "When chapman billies leave the street ..." DATA Short & shrift remarks=EXCHANGE(remarks,entitysubst) WRITE/NEXT d ENDACCESS d  
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.
#VBScript
VBScript
  Set objXMLDoc = CreateObject("msxml2.domdocument")   Set objRoot = objXMLDoc.createElement("CharacterRemarks") objXMLDoc.appendChild objRoot   Call CreateNode("April","Bubbly: I'm > Tam and <= Emily") Call CreateNode("Tam O'Shanter","Burns: ""When chapman billies leave the street ...""") Call CreateNode("Emily","Short & shrift")   objXMLDoc.save("C:\Temp\Test.xml")   Function CreateNode(attrib_value,node_value) Set objNode = objXMLDoc.createElement("Character") objNode.setAttribute "name", attrib_value objNode.text = node_value objRoot.appendChild objNode End Function  
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
#PowerShell
PowerShell
  [xml]$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="&#x00C9;mily" /> </Students> '@   foreach ($node in $xml.DocumentElement.ChildNodes) {$node.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
#PureBasic
PureBasic
Define studentNames.String, src$   src$ = "<Students>" src$ + "<Student Name='April' Gender='F' DateOfBirth='1989-01-02' />" src$ + "<Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />" src$ + "<Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />" src$ + "<Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>" src$ + "<Pet Type='dog' Name='Rover' />" src$ + "</Student>" src$ + "<Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />" src$ + "</Students>"   ;This procedure is generalized to match any attribute of any normal element's node name ;i.e. get_values(MainXMLNode(0),"Pet","Type",@petName.String) and displaying petName\s ;would display "dog". Procedure get_values(*cur_node, nodeName$, attribute$, *valueResults.String) ;If nodeName$ and attribute$ are matched then the value ;will be added to the string structure pointed to by *valueResults . Protected result$   While *cur_node If XMLNodeType(*cur_node) = #PB_XML_Normal   result$ = GetXMLNodeName(*cur_node) If result$ = nodeName$ If ExamineXMLAttributes(*cur_node) While NextXMLAttribute(*cur_node) If XMLAttributeName(*cur_node) = attribute$ If *valueResults <> #Null *valueResults\s + XMLAttributeValue(*cur_node) + Chr(13) ;value + carriage-return EndIf EndIf Wend EndIf EndIf   EndIf   get_values(ChildXMLNode(*cur_node), nodeName$, attribute$, *valueResults) *cur_node = NextXMLNode(*cur_node) Wend EndProcedure   CatchXML(0,@src$,Len(src$))   If IsXML(0) get_values(MainXMLNode(0), "Student", "Name",@studentNames) MessageRequester("Student Names", studentNames\s) FreeXML(0) EndIf
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)
#zonnon
zonnon
  var a: array 10 of integer; da: array * of cardinal;  
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.
#Oz
Oz
declare NumDoors = 100 NumPasses = 100   fun {NewDoor} closed end   fun {Toggle Door} case Door of closed then open [] open then closed end end   fun {Pass Doors I} {List.mapInd Doors fun {$ Index Door} if Index mod I == 0 then {Toggle Door} else Door end end} end   Doors0 = {MakeList NumDoors} {ForAll Doors0 NewDoor}   DoorsN = {FoldL {List.number 1 NumPasses 1} Pass Doors0} in %% print open doors {List.forAllInd DoorsN proc {$ Index Door} if Door == open then {System.showInfo "Door "#Index#" is open."} end end }
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
#Ruby
Ruby
def divisors(n) divs = [1] divs2 = []   i = 2 while i * i <= n if n % i == 0 then j = (n / i).to_i divs.append(i) if i != j then divs2.append(j) end end   i = i + 1 end   divs2 += divs.reverse return divs2 end   def abundant(n, divs) return divs.sum > n end   def semiperfect(n, divs) if divs.length > 0 then h = divs[0] t = divs[1..-1] if n < h then return semiperfect(n, t) else return n == h || semiperfect(n - h, t) || semiperfect(n, t) end else return false end end   def sieve(limit) w = Array.new(limit, false) i = 2 while i < limit if not w[i] then divs = divisors(i) if not abundant(i, divs) then w[i] = true elsif semiperfect(i, divs) then j = i while j < limit w[j] = true j = j + i end end end i = i + 2 end return w end   def main w = sieve(17000) count = 0 max = 25 print "The first %d weird numbers:\n" % [max] n = 2 while count < max if not w[n] then print n, " " count = count + 1 end n = n + 2 end print "\n" 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
#Seed7
Seed7
$include "seed7_05.s7i";   const array string: name is [] ( " *** * ***** ", "* * * ", "* *** *** **** * ", "* * * * * * * * ", " *** * * * * * * * ", " * ***** ***** * * * ", " * * * * * * ", " * * * * * * ", " *** *** *** **** * ");   const proc: main is func local var integer: index is 0; var string: help is ""; var string: line is ""; var string: previousLine is ""; var integer: pos is 0; begin for index range 1 to length(name) do help := replace(name[index], " ", " "); line := "" lpad length(name) - index <& replace(replace(help, "*", "///"), "/ ", "/\\"); if previousLine = "" then writeln(line); else for pos range 1 to length(line) do if line[pos] <> ' ' then write(line[pos]); else write(previousLine[pos]); end if; end for; writeln; end if; previousLine := "" lpad length(name) - index <& replace(replace(help, "*", "\\\\\\"), "\\ ", "\\/"); end for; writeln(previousLine); end func;
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
#Sidef
Sidef
var text = <<'EOT';   *** * * * ** * * * * * * *** ** *** * **** * * * * * * * ***** * * * * * * * * * * * * * *** * **** *** * EOT   func banner3D(text, shift=-1) { var txt = text.lines.map{|line| line.gsub('*','__/').gsub(' ',' ')}; var offset = txt.len.of {|i| " " * (shift.abs * i)}; shift < 0 && offset.reverse!; (offset »+« txt).join("\n"); };   say banner3D(text);
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++.
#Icon_and_Unicon
Icon and Unicon
procedure main() m := open(url := "http://tycho.usno.navy.mil/cgi-bin/timer.pl","m") | stop("Unable to open ",url) every (p := "") ||:= |read(m) # read the page into a single string close(m)   map(p) ? ( tab(find("<br>")), ="<br>", write("UTC time=",p[&pos:find(" utc")])) # scrape and show 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++.
#J
J
require 'web/gethttp'   _8{. ' UTC' taketo gethttp 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' 04:32:44
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
#Haskell
Haskell
module Main where   import Control.Category -- (>>>) import Data.Char -- toLower, isSpace import Data.List -- sortBy, (Foldable(foldl')), filter -- ' import Data.Ord -- Down import System.IO -- stdin, ReadMode, openFile, hClose import System.Environment -- getArgs   -- containers import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.IntMap.Strict as IM   -- text import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T   frequencies :: Ord a => [a] -> Map a Integer frequencies = foldl' (\m k -> M.insertWith (+) k 1 m) M.empty -- ' {-# SPECIALIZE frequencies :: [Text] -> Map Text Integer #-}   main :: IO () main = do args <- getArgs (n,hand,filep) <- case length args of 0 -> return (10,stdin,False) 1 -> return (read $ head args,stdin,False) _ -> let (ns:fp:_) = args in fmap (\h -> (read ns,h,True)) (openFile fp ReadMode) T.hGetContents hand >>= (T.map toLower >>> T.split isSpace >>> filter (not <<< T.null) >>> frequencies >>> M.toList >>> sortBy (comparing (Down <<< snd)) -- sort the opposite way >>> take n >>> print) when filep (hClose hand)
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.
#Lua
Lua
  local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'}, {'.', ' ', ' ', ' ', '.'}, {' ', ' ', ' ', '.', '.', '.'}, {'.', ' ', ' ', ' ', '.'}, {'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}}   function step(map) local next = {} for i = 1, #map do next[i] = {} for j = 1, #map[i] do next[i][j] = map[i][j] if map[i][j] == "H" then next[i][j] = "t" elseif map[i][j] == "t" then next[i][j] = "." elseif map[i][j] == "." then local count = ((map[i-1] or {})[j-1] == "H" and 1 or 0) + ((map[i-1] or {})[j] == "H" and 1 or 0) + ((map[i-1] or {})[j+1] == "H" and 1 or 0) + ((map[i] or {})[j-1] == "H" and 1 or 0) + ((map[i] or {})[j+1] == "H" and 1 or 0) + ((map[i+1] or {})[j-1] == "H" and 1 or 0) + ((map[i+1] or {})[j] == "H" and 1 or 0) + ((map[i+1] or {})[j+1] == "H" and 1 or 0) if count == 1 or count == 2 then next[i][j] = "H" else next[i][j] = "." end end end end return next end   if not not love then local time, frameTime, size = 0, 0.25, 20 local colors = {["."] = {255, 200, 0}, ["t"] = {255, 0, 0}, ["H"] = {0, 0, 255}} function love.update(dt) time = time + dt if time > frameTime then time = time - frameTime map = step(map) end end   function love.draw() for i = 1, #map do for j = 1, #map[i] do love.graphics.setColor(colors[map[i][j]] or {0, 0, 0}) love.graphics.rectangle("fill", j*size, i*size, size, size) end end end else for iter = 1, 10 do print("\nstep "..iter.."\n") for i = 1, #map do for j = 1, #map[i] do io.write(map[i][j]) end io.write("\n") end map = step(map) end 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.
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define proc {OnClose} {Application.exit 0} end   %% Descripe the GUI in a declarative style. GUIDescription = td(label(text:"Hello World!") action:OnClose %% Exit app when window closes. )   %% Create a window object from the description and show it. Window = {QTk.build GUIDescription} {Window show} 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.
#Pascal
Pascal
Program WindowCreation_SDL;   {$linklib SDL}   uses SDL, SysUtils;   var screen: PSDL_Surface;   begin SDL_Init(SDL_INIT_VIDEO); screen := SDL_SetVideoMode( 800, 600, 16, (SDL_SWSURFACE or SDL_HWPALETTE) ); sleep(2000); SDL_Quit; end.
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#LFE
LFE
  (defun wrap-text (text) (wrap-text text 78))   (defun wrap-text (text max-len) (string:join (make-wrapped-lines (string:tokens text " ") max-len) "\n"))   (defun make-wrapped-lines (((cons word rest) max-len) (let ((`#(,_ ,_ ,last-line ,lines) (assemble-lines max-len word rest))) (lists:reverse (cons last-line lines)))))   (defun assemble-lines (max-len word rest) (lists:foldl #'assemble-line/2 `#(,max-len ,(length word) ,word ()) rest))   (defun assemble-line ((word `#(,max ,line-len ,line ,acc)) (when (> (+ (length word) line-len) max)) `#(,max ,(length word) ,word ,(cons line acc))) ((word `#(,max ,line-len ,line ,acc)) `#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))  
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.
#Vedit_macro_language
Vedit macro language
// Replace special characters with entities: Replace("&", "&amp;", BEGIN+ALL+NOERR) // this must be the first replace! Replace("<", "&lt;", BEGIN+ALL+NOERR) Replace(">", "&gt;", BEGIN+ALL+NOERR) Replace("'", "&apos;", BEGIN+ALL+NOERR) Replace('"', "&quot;", BEGIN+ALL+NOERR)   // Insert XML marking BOF IT("<CharacterRemarks>") IN Repeat(ALL) { Search("^.", REGEXP+ERRBREAK) IT(' <Character name="') Replace('|T', '">') EOL IT('</Character>') } EOF IT("</CharacterRemarks>") IN
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
#Python
Python
import xml.dom.minidom   doc = """<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>"""   doc = xml.dom.minidom.parseString(doc)   for i in doc.getElementsByTagName("Student"): print i.getAttribute("Name")
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)
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM a(5) 20 LET a(2)=128 30 PRINT a(2)
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.
#PARI.2FGP
PARI/GP
  v=vector(d=100);/*set 100 closed doors*/ for(i=1,d,forstep(j=i,d,i,v[j]=1-v[j])); for(i=1,d,if(v[i],print("Door ",i," is open.")))  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Sidef
Sidef
func is_pseudoperfect(n, d = n.divisors.slice(0, -2), s = d.sum, m = d.end) {   return false if (m < 0)   while (d[m] > n) { s -= d[m--] }   return true if (n == s) return true if (d[m] == n)   __FUNC__(n-d[m], d, s-d[m], m-1) || __FUNC__(n, d, s-d[m], m-1) }   func is_weird(n) { (n.sigma > 2*n) && !is_pseudoperfect(n) }   var w = (1..Inf -> lazy.grep(is_weird).first(25)) say "The first 25 weird numbers:\n#{w.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
#SQL
SQL
SELECT ' SSS\ ' AS s, ' QQQ\ ' AS q, 'L\ ' AS l FROM dual UNION ALL SELECT 'S \|', 'Q Q\ ', 'L | ' FROM dual UNION ALL SELECT '\SSS ', 'Q Q |', 'L | ' FROM dual UNION ALL SELECT ' \ S\', 'Q Q Q |', 'L | ' from dual union all select ' SSS |', '\QQQ\\|', 'LLLL\' from dual union all select ' \__\/', ' \_Q_/ ', '\___\' from dual union all select ' ', ' \\ ', ' ' from dual;
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++.
#Java
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection;     public class WebTime{ public static void main(String[] args){ try{ URL address = new URL( "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); URLConnection conn = address.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while(!(line = in.readLine()).contains("UTC")); System.out.println(line.substring(4)); }catch(IOException e){ System.err.println("error connecting to server."); e.printStackTrace(); } } }
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
#J
J
10{.\:~(#;{.)/.~;:tolower((e.&(a.-.Alpha_j_,' '))`(,:&' '))}1!:1<jpath'~/downloads/books/LesMis.txt' ┌─────┬────┐ │41093│the │ ├─────┼────┤ │19954│of │ ├─────┼────┤ │14943│and │ ├─────┼────┤ │14558│a │ ├─────┼────┤ │13953│to │ ├─────┼────┤ │11219│in │ ├─────┼────┤ │9649 │he │ ├─────┼────┤ │8622 │was │ ├─────┼────┤ │7924 │that│ ├─────┼────┤ │6661 │it │ └─────┴────┘
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
#Java
Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;   public class WordCount { public static void main(String[] args) throws IOException { Path path = Paths.get("135-0.txt"); byte[] bytes = Files.readAllBytes(path); String text = new String(bytes); text = text.toLowerCase();   Pattern r = Pattern.compile("\\p{javaLowerCase}+"); Matcher matcher = r.matcher(text); Map<String, Integer> freq = new HashMap<>(); while (matcher.find()) { String word = matcher.group(); Integer current = freq.getOrDefault(word, 0); freq.put(word, current + 1); }   List<Map.Entry<String, Integer>> entries = freq.entrySet() .stream() .sorted((i1, i2) -> Integer.compare(i2.getValue(), i1.getValue())) .limit(10) .collect(Collectors.toList());   System.out.println("Rank Word Frequency"); System.out.println("==== ==== ========="); int rank = 1; for (Map.Entry<String, Integer> entry : entries) { String word = entry.getKey(); Integer count = entry.getValue(); System.out.printf("%2d  %-4s  %5d\n", rank++, word, count); } } }
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{data = ArrayPad[PadRight[Characters /@ StringSplit["tH......... . . ... . . Ht.. ......", "\n"]] /. {" " -> 0, "t" -> 2, "H" -> 1, "." -> 3}, 1]}, Dynamic@ArrayPlot[ data = CellularAutomaton[{{{_, _, _}, {_, 0, _}, {_, _, _}} -> 0, {{_, _, _}, {_, 1, _}, {_, _, _}} -> 2, {{_, _, _}, {_, 2, _}, {_, _, _}} -> 3, {{a_, b_, c_}, {d_, 3, e_}, {f_, g_, h_}} :> Switch[Count[{a, b, c, d, e, f, g, h}, 1], 1, 1, 2, 1, _, 3]}, data], ColorRules -> {1 -> Yellow, 2 -> Red}]]
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.
#Perl
Perl
use Tk;   MainWindow->new(); 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.
#Phix
Phix
-- demo\rosetta\Window_creation.exw with javascript_semantics include pGUI.e IupOpen() IupShow(IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200"),"TITLE=Hello")) if platform()!=JS then IupMainLoop() IupClose() end if
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
#Lingo
Lingo
-- in some movie script   ---------------------------------------- -- Wraps specified text into lines of specified width (in px), returns lines as list of strings -- @param {string} str -- @param {integer} pixelWidth -- @param {propList} [style] -- @return {list} ---------------------------------------- on hardWrapText (str, pixelWidth, style) if voidP(style) then style = [:] lines = []   -- create a new field member m = new(#field) m.text = str m.rect = rect(0,0,pixelWidth,0)   -- assign style props (if not specified, defaults are used) repeat with i = 1 to style.count m.setProp(style.getPropAt(i), style[i]) end repeat   -- create an invisible temporary sprite s = channel(1).makeScriptedSprite(m) s.loc = point(0,0) s.visible = false _movie.updateStage()   -- get the wrapped lines charPos = 0 repeat with y = 0 to s.height-1 n = s.pointToChar(point(pixelWidth-1, y)) if n<>charPos then lines.add(str.char[charPos+1..n]) charPos = n end if end repeat   channel(1).removeScriptedSprite() return lines end
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lua
Lua
function splittokens(s) local res = {} for w in s:gmatch("%S+") do res[#res+1] = w end return res end   function textwrap(text, linewidth) if not linewidth then linewidth = 75 end   local spaceleft = linewidth local res = {} local line = {}   for _, word in ipairs(splittokens(text)) do if #word + 1 > spaceleft then table.insert(res, table.concat(line, ' ')) line = {word} spaceleft = linewidth - #word else table.insert(line, word) spaceleft = spaceleft - (#word + 1) end end   table.insert(res, table.concat(line, ' ')) return table.concat(res, '\n') end   local example1 = [[ Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. 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. ]]   print(textwrap(example1)) print() print(textwrap(example1, 60))
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.
#Visual_Basic_.NET
Visual Basic .NET
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I'm > Tam and <= Emily") charRemarks.Add("Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""") charRemarks.Add("Emily", "Short & shrift")   Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks>   Console.WriteLine(xml) End Sub End Module
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
#R
R
library(XML) #Read in XML string str <- readLines(tc <- textConnection('<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>')) close(tc) str
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
#Racket
Racket
  #lang racket (require xml xml/path)   (define input #<<END <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> END )   (define students (xml->xexpr (document-element (read-xml (open-input-string input)))))   (se-path*/list '(Student #:Name) students)  
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.
#Pascal
Pascal
Program OneHundredDoors;   var doors : Array[1..100] of Boolean; i, j : Integer;   begin for i := 1 to 100 do doors[i] := False; for i := 1 to 100 do begin j := i; while j <= 100 do begin doors[j] := not doors[j]; j := j + i end end; for i := 1 to 100 do begin Write(i, ' '); if doors[i] then WriteLn('open') else WriteLn('closed'); end end.
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Dim resu As New List(Of Integer)   Function TestAbundant(n As Integer, ByRef divs As List(Of Integer)) As Boolean divs = New List(Of Integer) Dim sum As Integer = -n : For i As Integer = Math.Sqrt(n) To 1 Step -1 If n Mod i = 0 Then divs.Add(i) : Dim j As Integer = n / i : divs.Insert(0, j) : sum += i + j Next : divs(0) = sum - divs(0) : Return divs(0) > 0 End Function   Function subList(src As List(Of Integer), Optional first As Integer = Integer.MinValue) As List(Of Integer) subList = src.ToList : subList.RemoveAt(1) End Function   Function semiperfect(divs As List(Of Integer)) As Boolean If divs.Count < 2 Then Return False Select Case divs.First.CompareTo(divs(1)) Case 0 : Return True Case -1 : Return semiperfect(subList(divs)) Case 1 : Dim t As List(Of Integer) = subList(divs) : t(0) -= divs(1) If semiperfect(t) Then Return True Else t(0) = divs.First : Return semiperfect(t) End Select : Return False ' execution can't get here, just for compiler warning End Function   Function Since(et As TimeSpan) As String ' big ugly routine to prettify the elasped time If et > New TimeSpan(2000000) Then Dim s As String = " " & et.ToString(), p As Integer = s.IndexOf(":"), q As Integer = s.IndexOf(".") If q < p Then s = s.Insert(q, "Days") : s = s.Replace("Days.", "Days, ") p = s.IndexOf(":") : s = s.Insert(p, "h") : s = s.Replace("h:", "h ") p = s.IndexOf(":") : s = s.Insert(p, "m") : s = s.Replace("m:", "m ") s = s.Replace(" 0", " ").Replace(" 0h", " ").Replace(" 0m", " ") & "s" Return s.TrimStart() Else If et > New TimeSpan(1500) Then Return et.TotalMilliseconds.ToString() & "ms" Else If et > New TimeSpan(15) Then Return (et.TotalMilliseconds * 1000.0).ToString() & "µs" Else Return (et.TotalMilliseconds * 1000000.0).ToString() & "ns" End If End If End If End Function   Sub Main(args As String()) Dim sw As New Stopwatch, st As Integer = 2, stp As Integer = 1020, count As Integer = 0 Dim max As Integer = 25, halted As Boolean = False If args.Length > 0 Then _ Dim t As Integer = Integer.MaxValue : If Integer.TryParse(args(0), t) Then max = If(t > 0, t, Integer.MaxValue) If max = Integer.MaxValue Then Console.WriteLine("Calculating weird numbers, press a key to halt.") stp *= 10 Else Console.WriteLine("The first {0} weird numbers:", max) End If If max < 25 Then stp = 140 sw.Start() Do : Parallel.ForEach(Enumerable.Range(st, stp), Sub(n) Dim divs As List(Of Integer) = Nothing If TestAbundant(n, divs) AndAlso Not semiperfect(divs) Then SyncLock resu : resu.Add(n) : End SyncLock End If End Sub) If resu.Count > 0 Then resu.Sort() If count + resu.Count > max Then resu = resu.Take(max - count).ToList End If Console.Write(String.Join(" ", resu) & " ") count += resu.Count : resu.Clear() End If If Console.KeyAvailable Then Console.ReadKey() : halted = True : Exit Do st += stp Loop Until count >= max sw.Stop() If max < Integer.MaxValue Then Console.WriteLine(vbLf & "Computation time was {0}.", Since(sw.Elapsed)) If halted Then Console.WriteLine("Halted at number {0}.", count) Else Console.WriteLine(vbLf & "Computation time was {0} for the first {1} weird numbers.", Since(sw.Elapsed), count) End If End Sub End Module
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Tcl
Tcl
package require Tcl 8.5   proc mergeLine {upper lower} { foreach u [split $upper ""] l [split $lower ""] { lappend result [expr {$l in {" " ""} ? $u : $l}] } return [join $result ""] } proc printLines lines { set n [llength $lines] foreach line $lines { set indent [string repeat " " $n] lappend upper $indent[string map {"/ " "/\\"} [ string map {" " " " "*" "///"} "$line "]] lappend lower $indent[string map {"\\ " "\\/"} [ string map {" " " " "*" "\\\\\\"} "$line "]] incr n -1 } # Now do some line merging to strengthen the visual effect set p [string repeat " " [string length [lindex $upper 0]]] foreach u $upper l $lower { puts [mergeLine $p $u] set p $l } puts $p }   set lines { {***** *} { * *} { * *** *} { * * *} { * * *} { * *** *} } printLines $lines
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++.
#JavaScript
JavaScript
var req = new XMLHttpRequest(); req.onload = function () { var re = /[JFMASOND].+ UTC/; //beginning of month name to 'UTC' console.log(this.responseText.match(re)[0]); }; req.open('GET', 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', true); req.send();
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++.
#jq
jq
#!/bin/bash curl -Ss 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' |\ jq -R -r 'if index(" UTC") then .[4:] else empty 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
#jq
jq
  < 135-0.txt jq -nR --argjson n 10 ' def bow(stream): reduce stream as $word ({}; .[($word|tostring)] += 1);   bow(inputs | gsub("[^-a-zA-Z]"; " ") | splits(" *") | ascii_downcase | select(test("^[a-z][-a-z]*$"))) | to_entries | sort_by(.value) | .[- $n :] | reverse | from_entries '  
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
#Julia
Julia
  using FreqTables   txt = read("les-mis.txt", String) words = split(replace(txt, r"\P{L}"i => " ")) table = sort(freqtable(words); rev=true) println(table[1:10])
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Nim
Nim
import strutils, os   var world, world2 = """ +-----------+ |tH.........| |. . | | ... | |. . | |Ht.. ......| +-----------+"""   let h = world.splitLines.len let w = world.splitLines[0].len   template isH(x, y): int = int(s[i + w * y + x] == 'H')   proc next(o: var string, s: string, w: int) = for i, c in s: o[i] = case c of ' ': ' ' of 't': '.' of 'H': 't' of '.': if (isH(-1, -1) + isH(0, -1) + isH(1, -1) + isH(-1, 0) + isH(1, 0) + isH(-1, 1) + isH(0, 1) + isH(1, 1) ) in 1..2: 'H' else: '.' else: c   while true: echo world stdout.write "\x1b[",h,"A" stdout.write "\x1b[",w,"D" sleep 100   world2.next(world, w) swap world, world2
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.
#OCaml
OCaml
let w = [| " ......tH "; " . ...... "; " ...Ht... . "; " .... "; " . ..... "; " .... "; " tH...... . "; " . ...... "; " ...Ht... "; |]   let is_head w x y = try if w.(x).[y] = 'H' then 1 else 0 with _ -> 0   let neighborhood_heads w x y = let n = ref 0 in for _x = pred x to succ x do for _y = pred y to succ y do n := !n + (is_head w _x _y) done; done; (!n)   let step w = let n = Array.init (Array.length w) (fun i -> String.copy w.(i)) in let width = Array.length w and height = String.length w.(0) in for x = 0 to pred width do for y = 0 to pred height do n.(x).[y] <- ( match w.(x).[y] with | ' ' -> ' ' | 'H' -> 't' | 't' -> '.' | '.' -> (match neighborhood_heads w x y with | 1 | 2 -> 'H' | _ -> '.') | _ -> assert false) done; done; (n)   let print = (Array.iter print_endline)   let () = let rec aux w = Unix.sleep 1; let n = step w in print n; aux n in aux 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.
#PicoLisp
PicoLisp
(load "@lib/openGl.l")   (glutInit) (glutCreateWindow "Goodbye, World!") (keyboardFunc '(() (bye))) (glutMainLoop)
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.
#PowerShell
PowerShell
New-Window -Show
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Processing
Processing
  size(1000,1000);  
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ leading space from begin of paragraph stay as is a$={ 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. } const crlf$=chr$(13)+chr$(10) a$=replace$(crlf$, " ", a$)+crlf$ const justify=0 const flushright=1 const centered=2 const flushleft=3 \\ set layer font Font "Tahoma" Form 80, 50 Print "Font:";Fontname$ Print "Font size:";Mode;"pt" Print "Bold:";Bold Print "Italic:";Italic \\ set left margin for Report Cursor 10, 8 ' pos 10 row 8 (11 9 - it is 0 based) m=Italic Italic 1 Report centered, trim$(A$), Width-10-10 Italic m   Print @(0,79),"Press any key"; wait$=key$ Refresh 5000 charwidth=scale.x div width For i=2000 to scale.x-charwidth step 150 \\ clear screen with 14pt fonts   Mode 12.75 \\ by default use justify, word wrap Report a$, i \\ we can calculate only using a negative parameter Report a$, i, -10000 k=ReportLines \\ print any line in differnet color Dim a(2) a(0)=11, 15 ' 0 to 15 are vb6 colors, we can use html colors #aabbcc, #ff2211 For j=1 to k { Pen a(j mod 2) { Report a$, i, 1 line j } } Refresh 5000 wait$=key$ Next i   Report a$, scale.x/2, -1000 k=ReportLines Document Doc$ Report a$, scale.x/2, k as Doc$ \\ Print document without expanding spaces Print $(4), ' 4=proportional printing using columns, on line online, word wrap, expand to fit in columns For i=1 to k { Print "*";Paragraph$(Doc$, i);"*" } Print $(0), ' restore to non proportional printing For i=1 to k { Print i, size.x(Paragraph$(Doc$, i), Fontname$, Mode), size.y(Paragraph$(Doc$, i), Fontname$, Mode) } \\ scale.x unit in twips Report a$, scale.x/2 \\ width unit in characters Report a$, width/2 Print @(width div 2), Report flushright, a$, width/2 Cursor 0, Row I=Italic Double Italic 1 Report centered, a$ Italic I Double Normal } Checkit