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/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Sidef
Sidef
func plot(x, y, c) { c && printf("plot %d %d %.1f\n", x, y, c); }   func fpart(x) { x - int(x); }   func rfpart(x) { 1 - fpart(x); }   func drawLine(x0, y0, x1, y1) {   var p = plot; if (abs(y1 - y0) > abs(x1 - x0)) { p = {|arg| plot(arg[1, 0, 2]) }; (x0, y0, x1, y1) = (y0, x0, y1, x1); }   if (x0 > x1) { (x0, x1, y0, y1) = (x1, x0, y1, y0); }   var dx = (x1 - x0); var dy = (y1 - y0); var gradient = (dy / dx);   var xends = []; var intery;   # handle the endpoints for x,y in [[x0, y0], [x1, y1]] { var xend = int(x + 0.5); var yend = (y + gradient*(xend-x)); var xgap = rfpart(x + 0.5);   var x_pixel = xend; var y_pixel = yend.int; xends << x_pixel;   p.call(x_pixel, y_pixel , rfpart(yend) * xgap); p.call(x_pixel, y_pixel+1, fpart(yend) * xgap); defined(intery) && next;   # first y-intersection for the main loop intery = (yend + gradient); }   # main loop range(xends[0]+1, xends[1]-1).each { |x| p.call(x, intery.int, rfpart(intery)); p.call(x, intery.int+1, fpart(intery)); intery += gradient; } }   drawLine(0, 1, 10, 2);
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Kotlin
Kotlin
// version 1.1.3   import javax.xml.parsers.DocumentBuilderFactory import javax.xml.transform.dom.DOMSource import java.io.StringWriter import javax.xml.transform.stream.StreamResult import javax.xml.transform.TransformerFactory   fun main(args: Array<String>) { val names = listOf("April", "Tam O'Shanter", "Emily")   val remarks = listOf( "Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift" )   val dbFactory = DocumentBuilderFactory.newInstance() val dBuilder = dbFactory.newDocumentBuilder() val doc = dBuilder.newDocument() val root = doc.createElement("CharacterRemarks") // create root node doc.appendChild(root)   // now create Character elements for (i in 0 until names.size) { val character = doc.createElement("Character") character.setAttribute("name", names[i]) val remark = doc.createTextNode(remarks[i]) character.appendChild(remark) root.appendChild(character) }   val source = DOMSource(doc) val sw = StringWriter() val result = StreamResult(sw) val tFactory = TransformerFactory.newInstance() tFactory.newTransformer().apply { setOutputProperty("omit-xml-declaration", "yes") setOutputProperty("indent", "yes") setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4") transform(source, result) } println(sw) }  
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
#JavaScript
JavaScript
  var xmlstr = '<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>';   if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(xmlstr,"text/xml"); } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(xmlstr); }   var students=xmlDoc.getElementsByTagName('Student'); for(var e=0; e<=students.length-1; e++) { console.log(students[e].attributes.Name.value); }  
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)
#UNIX_Shell
UNIX Shell
alist=( item1 item2 item3 ) # creates a 3 item array called "alist" declare -a list2 # declare an empty list called "list2" declare -a list3[0] # empty list called "list3"; the subscript is ignored   # create a 4 item list, with a specific order list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const proc: main is func local const array float: numbers is [] (1.0, 2.0, 3.0, 1.0e11); var float: aFloat is 0.0; var file: aFile is STD_NULL; begin aFile := open("filename", "w"); for aFloat range numbers do writeln(aFile, aFloat sci 3 exp 2 <& " " <& sqrt(aFloat) sci 5 exp 2); end for; close(aFile); end func;
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Sidef
Sidef
func writedat(filename, x, y, x_precision=3, y_precision=5) { var fh = File(filename).open_w   for a,b in (x ~Z y) { fh.printf("%.*g\t%.*g\n", x_precision, a, y_precision, b) }   fh.close }   var x = [1, 2, 3, 1e11] var y = x.map{.sqrt}   writedat('sqrt.dat', x, y)
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.
#Myrddin
Myrddin
  use std   const main = { var isopen : bool[100]   std.slfill(isopen[:], false) for var i = 0; i < isopen.len; i++ for var j = i; j < isopen.len; j += i + 1 isopen[j] = !isopen[j] ;; ;;   for var i = 0; i < isopen.len; i++ if isopen[i] std.put("door {} is open\n", i + 1) ;; ;; }  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <numeric> #include <vector>   std::vector<int> divisors(int n) { std::vector<int> divs = { 1 }; std::vector<int> divs2;   for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.push_back(i); if (i != j) { divs2.push_back(j); } } }   std::copy(divs.cbegin(), divs.cend(), std::back_inserter(divs2)); return divs2; }   bool abundant(int n, const std::vector<int> &divs) { return std::accumulate(divs.cbegin(), divs.cend(), 0) > n; }   template<typename IT> bool semiperfect(int n, const IT &it, const IT &end) { if (it != end) { auto h = *it; auto t = std::next(it); if (n < h) { return semiperfect(n, t, end); } else { return n == h || semiperfect(n - h, t, end) || semiperfect(n, t, end); } } else { return false; } }   template<typename C> bool semiperfect(int n, const C &c) { return semiperfect(n, std::cbegin(c), std::cend(c)); }   std::vector<bool> sieve(int limit) { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 std::vector<bool> w(limit); for (int i = 2; i < limit; i += 2) { if (w[i]) continue; auto divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (int j = i; j < limit; j += i) { w[j] = true; } } } return w; }   int main() { auto w = sieve(17000); int count = 0; int max = 25; std::cout << "The first 25 weird numbers:"; for (int n = 2; count < max; n += 2) { if (!w[n]) { std::cout << n << ' '; count++; } } std::cout << '\n'; return 0; }
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
#J
J
require 'vrml.ijs' NB. Due to Andrew Nikitin view 5#.^:_1]21-~a.i.'j*ez`C3\toy.G)' NB. Due to Oleg Kobchenko ________________________ |\ \ \ \ \ | \_____\_____\_____\_____\ | | | | |\ \ |\| | | | \_____\ | \_____|_____|_____| | | | | | | | |\| | \| | |\| | \_____| \_____| | \_____| | | | |\| | | \_____| ______ | | | |\ \ |\| | | \_____\_________|_\_____| | |\ \ \ \ | \| \_____\_____\_____\ | | | | | |___| \| | | | \_____|_____|_____|  
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
#Java
Java
public class F5{ char[]z={' ',' ','_','/',}; long[][]f={ {87381,87381,87381,87381,87381,87381,87381,}, {349525,375733,742837,742837,375733,349525,349525,}, {742741,768853,742837,742837,768853,349525,349525,}, {349525,375733,742741,742741,375733,349525,349525,}, {349621,375733,742837,742837,375733,349525,349525,}, {349525,375637,768949,742741,375733,349525,349525,}, {351157,374101,768949,374101,374101,349525,349525,}, {349525,375733,742837,742837,375733,349621,351157,}, {742741,768853,742837,742837,742837,349525,349525,}, {181,85,181,181,181,85,85,}, {1461,1365,1461,1461,1461,1461,2901,}, {742741,744277,767317,744277,742837,349525,349525,}, {181,181,181,181,181,85,85,}, {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,}, {349525,768853,742837,742837,742837,349525,349525,}, {349525,375637,742837,742837,375637,349525,349525,}, {349525,768853,742837,742837,768853,742741,742741,}, {349525,375733,742837,742837,375733,349621,349621,}, {349525,744373,767317,742741,742741,349525,349525,}, {349525,375733,767317,351157,768853,349525,349525,}, {374101,768949,374101,374101,351157,349525,349525,}, {349525,742837,742837,742837,375733,349525,349525,}, {5592405,11883957,11883957,5987157,5616981,5592405,5592405,}, {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,}, {349525,742837,375637,742837,742837,349525,349525,}, {349525,742837,742837,742837,375733,349621,375637,}, {349525,768949,351061,374101,768949,349525,349525,}, {375637,742837,768949,742837,742837,349525,349525,}, {768853,742837,768853,742837,768853,349525,349525,}, {375733,742741,742741,742741,375733,349525,349525,}, {192213,185709,185709,185709,192213,87381,87381,}, {1817525,1791317,1817429,1791317,1817525,1398101,1398101,}, {768949,742741,768853,742741,742741,349525,349525,}, {375733,742741,744373,742837,375733,349525,349525,}, {742837,742837,768949,742837,742837,349525,349525,}, {48053,23381,23381,23381,48053,21845,21845,}, {349621,349621,349621,742837,375637,349525,349525,}, {742837,744277,767317,744277,742837,349525,349525,}, {742741,742741,742741,742741,768949,349525,349525,}, {11883957,12278709,11908533,11883957,11883957,5592405,5592405,}, {11883957,12277173,11908533,11885493,11883957,5592405,5592405,}, {375637,742837,742837,742837,375637,349525,349525,}, {768853,742837,768853,742741,742741,349525,349525,}, {6010197,11885397,11909973,11885397,6010293,5592405,5592405,}, {768853,742837,768853,742837,742837,349525,349525,}, {375733,742741,375637,349621,768853,349525,349525,}, {12303285,5616981,5616981,5616981,5616981,5592405,5592405,}, {742837,742837,742837,742837,375637,349525,349525,}, {11883957,11883957,11883957,5987157,5616981,5592405,5592405,}, {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,}, {11883957,5987157,5616981,5987157,11883957,5592405,5592405,}, {11883957,5987157,5616981,5616981,5616981,5592405,5592405,}, {12303285,5593941,5616981,5985621,12303285,5592405,5592405,},}; public static void main(String[]a){ new F5(a.length>0?a[0]:"Java");} private F5(String s){ StringBuilder[]o=new StringBuilder[7]; for(int i=0;i<7;i++)o[i]=new StringBuilder(); for(int i=0,l=s.length();i<l;i++){ int c=s.charAt(i); if(65<=c&&c<=90)c-=39; else if(97<=c&&c<=122)c-=97; else c=-1; long[]d=f[++c]; for(int j=0;j<7;j++){ StringBuilder b=new StringBuilder(); long v=d[j]; while(v>0){ b.append(z[(int)(v&3)]); v>>=2;} o[j].append(b.reverse().toString());}} for(int i=0;i<7;i++){ for(int j=0;j<7-i;j++) System.out.print(' '); System.out.println(o[i]);}}}  
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#Ada
Ada
with AWS.Client, AWS.Response, AWS.Resources, AWS.Messages; with Ada.Text_IO, Ada.Strings.Fixed; use Ada, AWS, AWS.Resources, AWS.Messages;   procedure Get_UTC_Time is   Page  : Response.Data; File  : Resources.File_Type; Buffer  : String (1 .. 1024); Position, Last : Natural := 0; S  : Messages.Status_Code; begin Page := Client.Get ("http://tycho.usno.navy.mil/cgi-bin/timer.pl"); S  := Response.Status_Code (Page); if S not in Success then Text_IO.Put_Line ("Unable to retrieve data => Status Code :" & Image (S) & " Reason :" & Reason_Phrase (S)); return; end if;   Response.Message_Body (Page, File); while not End_Of_File (File) loop Resources.Get_Line (File, Buffer, Last); Position := Strings.Fixed.Index (Source => Buffer (Buffer'First .. Last), Pattern => "UTC"); if Position > 0 then Text_IO.Put_Line (Buffer (5 .. Position + 2)); return; end if; end loop; end Get_UTC_Time;
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Perl
Perl
#!perl use strict; use warnings; use Tk;   my $mw; my $win; my $lab;   # How to open a window. sub openWin { if( $win ) { $win->deiconify; $win->wm('state', 'normal'); } else { eval { $win->destroy } if $win; $win = $mw->Toplevel; $win->Label(-text => "This is the window being manipulated") ->pack(-fill => 'both', -expand => 1); $lab->configure(-text => "The window object is:\n$win"); } }   # How to close a window sub closeWin { return unless $win; $win->destroy; $lab->configure(-text => ''); undef $win; }   # How to minimize a window sub minimizeWin { return unless $win; $win->iconify; }   # How to maximize a window sub maximizeWin { return unless $win; $win->wm('state', 'zoomed'); eval { $win->wmAttribute(-zoomed => 1) }; # Hack for X11 }   # How to move a window sub moveWin { return unless $win; my ($x, $y) = $win->geometry() =~ /\+(\d+)\+(\d+)\z/ or die; $_ += 10 for $x, $y; $win->geometry("+$x+$y"); }   # How to resize a window sub resizeWin { return unless $win; my ($w, $h) = $win->geometry() =~ /^(\d+)x(\d+)/ or die; $_ += 10 for $w, $h; $win->geometry($w . "x" . $h); }   $mw = MainWindow->new; for my $label0 ($mw->Label(-text => 'Window handle:')) { $lab = $mw->Label(-text => ''); $label0->grid($lab); }   my @binit = ('Open/Restore' => \&openWin, Close => \&closeWin, Minimize => \&minimizeWin, Maximize => \&maximizeWin, Move => \&moveWin, Resize => \&resizeWin);   while( my ($text, $callback) = splice @binit, 0, 2 ) { $mw->Button(-text => $text, -command => $callback)->grid('-'); }   MainLoop();   __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
#Arturo
Arturo
findFrequency: function [file, count][ freqs: #[] r: {/[[:alpha:]]+/} loop flatten map split.lines read file 'l -> match lower l r 'word [ if not? key? freqs word -> freqs\[word]: 0 freqs\[word]: freqs\[word] + 1 ] freqs: sort.values.descending freqs result: new [] loop 0..dec count 'x [ 'result ++ @[@[get keys freqs x, get values freqs x]] ] return result ]   loop findFrequency "https://www.gutenberg.org/files/135/135-0.txt" 10 'pair [ print pair ]
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.
#C.23
C#
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string>   #include <unistd.h> // for usleep   enum cell_type { none, wire, head, tail };   // ***************** // * display class * // *****************   // this is just a small wrapper for the ggi interface   class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); }   void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; };   display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); }   visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); }   ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) // we need 4 colors! ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC);   size_x = mode.virt.x; size_y = mode.virt.y;   for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); }   void display::flush() { // set the current display frame to the one we have drawn to ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));   // flush the current visual ggiFlush(visual);   // try to set a different frame for drawing (errors are ignored; if // setting the new frame fails, the current one will be drawn upon, // with the only adverse effect being some flickering). ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); }   void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); }   void display::putpixel(int x, int y, cell_type cell) { // this draws a logical pixel (i.e. a rectangle of size pixel_size_x // times pixel_size_y), not a physical pixel ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); }   // ***************** // * the wireworld * // *****************   // initialized to an empty wireworld class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; };   void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } }   void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); }   void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { // std::cout << i->second; if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } }   ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, // background: black { 0x8000, 0x8000, 0x8000 }, // wire: white { 0xffff, 0xffff, 0x0000 }, // electron head: yellow { 0xffff, 0x0000, 0x0000 }}; // electron tail: red   int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5;   if (argc < 2) { std::cerr << "No file name given!\n"; return 1; }   // assume that the first argument is the name of a file to parse std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; // no need to explicitly set this, so do nothing } } ++line_number; }   display d(display_x, display_y, pixel_x, pixel_y, colors);   w.draw(d);   while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   function iswief( byval p as uinteger ) as boolean if not isprime(p) then return 0 dim as integer q = 1, p2 = p^2 while p>1 q=(2*q) mod p2 p = p - 1 wend if q=1 then return 1 else return 0 end function   for i as uinteger = 1 to 5000 if iswief(i) then print i next i
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Go
Go
package main   import ( "fmt" "math/big" "rcu" )   func main() { primes := rcu.Primes(5000) zero := new(big.Int) one := big.NewInt(1) num := new(big.Int) fmt.Println("Wieferich primes < 5,000:") for _, p := range primes { num.Set(one) num.Lsh(num, uint(p-1)) num.Sub(num, one) den := big.NewInt(int64(p * p)) if num.Rem(num, den).Cmp(zero) == 0 { fmt.Println(rcu.Commatize(p)) } } }
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#M2000_Interpreter
M2000 Interpreter
  \\ M2000 froms (windows) based on a flat, empty with no title bar, vb6 window and a user control. \\ title bar is a user control in M2000 form \\ On linux, wine application run M2000 interpreter traslating vb6 calls to window system. Module SquareAndText2Window { Const black=0, white=15 Declare form1 form \\ defaultwindow title is the name of variable,here is: form1 Rem With form1, "Title", "A title for this window" Method form1,"move", 2000,3000,10000,8000 ' in twips layer form1 { Cls white Font "Verdana" Rem Window 12 , 10000,8000; ' hide modr 13 using a REM before Rem Mode 12 ' 12 in pt Cls white, 2 ' fill white, set third raw for top of scrolling frame Pen black Move 1000,2000 ' absolute coordinated in twips - use Step for relative coordinates \\ polygon use relative coordinates in twips polygon white, 1000,0,0,-1000,-1000,0,0,-1000 \\ write text using graphic coordinates Move 1000, 3000 : Legend "Hello World", "Arial", 12 \\ write text using layer as console (font Verdana) Print @(15,5),"Goodbye Wolrd" \\ 9120 7920 if we use window 12,10000, 8000 (cut exactly for console use) \\ 10000 8000 if we use Mode 12 \\ scale.y include window height (including header) \\ the layer extend bellow Print scale.x, scale.y } \\ show form1 modal (continue to next line when we close the window) Method form1,"Show", 1 \\ closing meand hide in M2000 wait 1000 ' in msec Method form1,"move", random(2000, 10000),random(3000, 8000) \\ now show again Method form1,"Show", 1 \\ now we close the form, releasing resources Declare form1 Nothing } SquareAndText2Window  
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["GUIKit`"] ref = GUIRun[Widget["Panel", { Widget[ "ImageLabel", {"data" -> Script[ExportString[Graphics[Rectangle[{0, 0}, {1, 1}]], "GIF"]]}], Widget["Label", { "text" -> "Hello World!"}]} ]]
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#REXX
REXX
/*REXX program finds and displays Wilson primes: a prime P such that P**2 divides:*/ /*────────────────── (n-1)! * (P-n)! - (-1)**n where n is 1 ──◄ 11, and P < 18.*/ parse arg oLO oHI hip . /*obtain optional argument from the CL.*/ if oLO=='' | oLO=="," then oLO= 1 /*Not specified? Then use the default.*/ if oHI=='' | oHI=="," then oHI= 11 /* " " " " " " */ if hip=='' | hip=="," then hip= 11000 /* " " " " " " */ call genP /*build array of semaphores for primes.*/ !!.= . /*define the default for factorials. */ bignum= !(hip) /*calculate a ginormous factorial prod.*/ parse value bignum 'E0' with ex 'E' ex . /*obtain possible exponent of factorial*/ numeric digits (max(9, ex+2) ) /*calculate max # of dec. digits needed*/ call facts hip /*go & calculate a number of factorials*/ title= ' Wilson primes P of order ' oLO " ──► " oHI', where P < ' commas(hip) w= length(title) + 1 /*width of columns of possible numbers.*/ say ' order │'center(title, w ) say '───────┼'center("" , w, '─') do n=oLO to oHI; nf= !(n-1) /*precalculate a factorial product. */ z= -1**n /* " " plus or minus (+1│-1).*/ if n==1 then lim= 103 /*limit to known primes for 1st order. */ else lim= # /* " " all " " orders ≥ 2.*/ $= /*$: a line (output) of Wilson primes.*/ do j=1 for lim; p= @.j /*search through some generated primes.*/ if (nf*!(p-n)-z)//sq.j\==0 then iterate /*expression ~ q.j ? No, then skip it.*/ /* ◄■■■■■■■ the filter.*/ $= $ ' ' commas(p) /*add a commatized prime ──► $ list.*/ end /*p*/   if $=='' then $= ' (none found within the range specified)' say center(n, 7)'│' substr($, 2) /*display what Wilson primes we found. */ end /*n*/ say '───────┴'center("" , w, '─') exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: arg x; if !!.x\==. then return !!.x; a=1; do f=1 for x; a=a*f; end; return a commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? facts:  !!.= 1; x= 1; do f=1 for hip; x= x * f;  !!.f= x; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */  !.=0;  !.2=1; !.3=1; !.5=1; !.7=1;  !.11=1 /* " " " " semaphores. */ sq.1=4; sq.2=9; sq.3= 25; sq.4= 49; #= 5; sq.#= @.#**2 /*squares of low primes.*/ do j=@.#+2 by 2 for max(0, hip%2-@.#%2-1) /*find odd primes from here on. */ parse var j '' -1 _; if _==5 then iterate /*J ÷ 5? (right digit).*/ if j//3==0 then iterate; if j//7==0 then iterate /*" " 3? Is J ÷ by 7? */ do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= #+1; @.#= j; sq.#= j*j;  !.j= 1 /*bump # of Ps; assign next P; P²; P# */ end /*j*/; return
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.
#Delphi
Delphi
    // The project file (Project1.dpr) program Project1;   uses Forms, // Include file with Window class declaration (see below) Unit0 in 'Unit1.pas' {Form1};   {$R *.res}   begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.     // The Window class declaration unit Unit1;   interface   uses Forms;   type TForm1 = class(TForm) end;   var Form1: TForm1;   implementation   {$R *.dfm} // The window definition resource (see below)   end.   // A textual rendition of the Window (form) definition file (Unit1.dfm) object Form1: TForm1 Left = 469 Top = 142 Width = 800 Height = 600 Caption = 'Form1' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Shell Dlg 2' Font.Style = [] OldCreateOrder = False Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 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.
#Dragon
Dragon
select "GUI"   window = newWindow("Window") window.setSize(400,600) window.setVisible()    
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Racket
Racket
#lang racket ;; --------------------------------------------------------------------------------------------------- (module+ main (display-puzzle (create-word-search)) (newline) (parameterize ((current-min-words 50)) (display-puzzle (create-word-search #:n-rows 20 #:n-cols 20))))   ;; --------------------------------------------------------------------------------------------------- (define current-min-words (make-parameter 25))   ;; --------------------------------------------------------------------------------------------------- (define (all-words pzl) (filter-map (good-word? pzl) (file->lines "data/unixdict.txt")))   (define (good-word? pzl) (let ((m (puzzle-max-word-size pzl))) (λ (w) (and (<= 3 (string-length w) m) (regexp-match #px"^[A-Za-z]*$" w) (string-downcase w)))))   (struct puzzle (n-rows n-cols cells solutions) #:transparent)   (define puzzle-max-word-size (match-lambda [(puzzle n-rows n-cols _ _) (max n-rows n-cols)]))   (define dirs '((-1 -1 ↖) (-1 0 ↑) (-1 1 ↗) (0 -1 ←) (0 1 →) (1 -1 ↙) (1 0 ↓) (1 1 ↘)))   ;; --------------------------------------------------------------------------------------------------- (define (display-puzzle pzl) (displayln (puzzle->string pzl)))   (define (puzzle->string pzl) (match-let* (((and pzl (puzzle n-rows n-cols cells (and solutions (app length size)))) pzl) (column-numbers (cons "" (range n-cols))) (render-row (λ (r) (cons r (map (λ (c) (hash-ref cells (cons r c) #\_)) (range n-cols))))) (the-grid (add-between (map (curry map (curry ~a #:width 3)) (cons column-numbers (map render-row (range n-rows)))) "\n")) (solutions§ (solutions->string (sort solutions string<? #:key car)))) (string-join (flatten (list the-grid "\n\n" solutions§)) "")))   (define (solutions->string solutions) (let* ((l1 (compose string-length car)) (format-solution-to-max-word-size (format-solution (l1 (argmax l1 solutions))))) (let recur ((solutions solutions) (need-newline? #f) (acc null)) (if (null? solutions) (reverse (if need-newline? (cons "\n" acc) acc)) (let* ((spacer (if need-newline? "\n" " ")) (solution (format "~a~a" (format-solution-to-max-word-size (car solutions)) spacer))) (recur (cdr solutions) (not need-newline?) (cons solution acc)))))))   (define (format-solution max-word-size) (match-lambda [(list word row col dir) (string-append (~a word #:width (+ max-word-size 1)) (~a (format "(~a,~a ~a)" row col dir) #:width 9))]))   ;; --------------------------------------------------------------------------------------------------- (define (create-word-search #:msg (msg "Rosetta Code") #:n-rows (n-rows 10) #:n-cols (n-cols 10)) (let* ((pzl (puzzle n-rows n-cols (hash) null)) (MSG (sanitise-message msg)) (n-holes (- (* n-rows n-cols) (string-length MSG)))) (place-message (place-words pzl (shuffle (all-words pzl)) (current-min-words) n-holes) MSG)))   (define (sanitise-message msg) (regexp-replace* #rx"[^A-Z]" (string-upcase msg) ""))   (define (place-words pzl words needed-words holes) (let inner ((pzl pzl) (words words) (needed-words needed-words) (holes holes)) (cond [(and (not (positive? needed-words)) (zero? holes)) pzl] [(null? words) (eprintf "no solution... retrying (~a words remaining)~%" needed-words) (inner pzl (shuffle words) needed-words)] [else (let/ec no-fit (let*-values (([word words...] (values (car words) (cdr words))) ([solution cells′ holes′] (fit-word word pzl holes (λ () (no-fit (inner pzl words... needed-words holes))))) ([solutions′] (cons solution (puzzle-solutions pzl))) ([pzl′] (struct-copy puzzle pzl (solutions solutions′) (cells cells′)))) (inner pzl′ words... (sub1 needed-words) holes′)))])))   (define (fit-word word pzl holes fail) (match-let* (((puzzle n-rows n-cols cells _) pzl) (rows (shuffle (range n-rows))) (cols (shuffle (range n-cols))) (fits? (let ((l (string-length word))) (λ (maxz z0 dz) (< -1 (+ z0 (* dz l)) maxz))))) (let/ec return (for* ((dr-dc-↗ (shuffle dirs)) (r0 rows) (dr (in-value (car dr-dc-↗))) #:when (fits? n-rows r0 dr) (c0 cols) (dc (in-value (cadr dr-dc-↗))) #:when (fits? n-cols c0 dc) (↗ (in-value (caddr dr-dc-↗)))) (let/ec retry/ec (attempt-word-fit pzl word r0 c0 dr dc ↗ holes return retry/ec))) (fail))))   (define (attempt-word-fit pzl word r0 c0 dr dc ↗ holes return retry) (let-values (([cells′ available-cells′] (for/fold ((cells′ (puzzle-cells pzl)) (holes′ holes)) ((w word) (i (in-naturals))) (define k (cons (+ r0 (* dr i)) (+ c0 (* dc i)))) (cond [(not (hash-has-key? cells′ k)) (if (zero? holes′) (retry) (values (hash-set cells′ k w) (sub1 holes′)))] [(char=? (hash-ref cells′ k) w) (values cells′ holes′)] [else (retry)])))) (return (list word r0 c0 ↗) cells′ available-cells′)))   ;; --------------------------------------------------------------------------------------------------- (define (place-message pzl MSG) (match-define (puzzle n-rows n-cols cells _) pzl) (struct-copy puzzle pzl (cells (let loop ((r 0) (c 0) (cells cells) (msg (string->list MSG))) (cond [(or (null? msg) (= r n-rows)) cells] [(= c n-cols) (loop (add1 r) 0 cells msg)] [(hash-has-key? cells (cons r c)) (loop r (add1 c) cells msg)] [else (loop r (add1 c) (hash-set cells (cons r c) (car msg)) (cdr msg))])))))  
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
#D
D
void main() { immutable frog = "In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything.";   import std.stdio, std.string; foreach (width; [72, 80]) writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width)); }
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Racket
Racket
use Terminal::Boxer;   my %*SUB-MAIN-OPTS = :named-anywhere;   unit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);   my $must-have = $wheel.comb[4].lc;   my $has = $wheel.comb».lc.Bag;   my %words; $dict.IO.slurp.words».lc.map: { next if not .contains($must-have) or .chars < $min; %words{.chars}.push: $_ if .comb.Bag ⊆ $has; };   say "Using $dict, minimum $min letters.";   print rs-box :3col, :3cw, :indent("\t"), $wheel.comb».uc;   say "{sum %words.values».elems} words found";   printf "%d letters:  %s\n", .key, .value.sort.join(', ') for %words.sort;
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Swift
Swift
import Darwin // apply pixel of color at x,y with an OVER blend to the bitmap public func pixel(color: Color, x: Int, y: Int) { let idx = x + y * self.width if idx >= 0 && idx < self.bitmap.count { self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color) } }   // return the fractional part of a Double func fpart(_ x: Double) -> Double { return modf(x).1 }   // reciprocal of the fractional part of a Double func rfpart(_ x: Double) -> Double { return 1 - fpart(x) }   // draw a 1px wide line using Xiolin Wu's antialiased line algorithm public func smoothLine(_ p0: Point, _ p1: Point) { var x0 = p0.x, x1 = p1.x, y0 = p0.y, y1 = p1.y //swapable ptrs let steep = abs(y1 - y0) > abs(x1 - x0) if steep { swap(&x0, &y0) swap(&x1, &y1) } if x0 > x1 { swap(&x0, &x1) swap(&y0, &y1) } let dX = x1 - x0 let dY = y1 - y0   var gradient: Double if dX == 0.0 { gradient = 1.0 } else { gradient = dY / dX }   // handle endpoint 1 var xend = round(x0) var yend = y0 + gradient * (xend - x0) var xgap = self.rfpart(x0 + 0.5) let xpxl1 = Int(xend) let ypxl1 = Int(yend)   // first y-intersection for the main loop var intery = yend + gradient   if steep { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl1, y: xpxl1) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl1 + 1, y: xpxl1) } else { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl1, y: ypxl1) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl1, y: ypxl1 + 1) }   xend = round(x1) yend = y1 + gradient * (xend - x1) xgap = self.fpart(x1 + 0.5) let xpxl2 = Int(xend) let ypxl2 = Int(yend)   // handle second endpoint if steep { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl2, y: xpxl2) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl2 + 1, y: xpxl2) } else { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl2, y: ypxl2) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl2, y: ypxl2 + 1) }   // main loop if steep { for x in xpxl1+1..<xpxl2 { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: Int(intery), y: x) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: Int(intery) + 1, y:x) intery += gradient } } else { for x in xpxl1+1..<xpxl2 { self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: x, y: Int(intery)) self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: x, y: Int(intery) + 1) intery += gradient } } }  
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.
#Lasso
Lasso
define character2xml(names::array, remarks::array) => {   fail_if(#names -> size != #remarks -> size, -1, 'Input arrays not of same size')   local( domimpl = xml_domimplementation, doctype = #domimpl -> createdocumenttype( 'svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd' ), character_xml = #domimpl -> createdocument( 'http://www.w3.org/2000/svg', 'svg:svg', #docType ), csnode = #character_xml -> createelement('CharacterRemarks'), charnode )   #character_xml -> appendChild(#csnode)   loop(#names -> size) => { #charnode = #character_xml -> createelement('Character') #charnode -> setAttribute('name', #names -> get(loop_count)) #charnode -> nodeValue = encode_xml(#remarks -> get(loop_count)) #csnode -> appendChild(#charnode) } return #character_xml   }   character2xml( array(`April`, `Tam O'Shanter`, `Emily`), array(`Bubbly: I'm > Tam and <= Emily`, `Burns: "When chapman billies leave the street ..."`, `Short & shrift`) )
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Lua
Lua
require("LuaXML")   function addNode(parent, nodeName, key, value, content) local node = xml.new(nodeName) table.insert(node, content) parent:append(node)[key] = value end   root = xml.new("CharacterRemarks") addNode(root, "Character", "name", "April", "Bubbly: I'm > Tam and <= Emily") addNode(root, "Character", "name", "Tam O'Shanter", 'Burns: "When chapman billies leave the street ..."') addNode(root, "Character", "name", "Emily", "Short & shrift") print(root)
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
#Julia
Julia
using LightXML   let docstr = """<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 = parse_string(docstr) xroot = root(doc) for elem in xroot["Student"] println(attribute(elem, "Name")) end end
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Kotlin
Kotlin
// version 1.1.3   import javax.xml.parsers.DocumentBuilderFactory import org.xml.sax.InputSource import java.io.StringReader import org.w3c.dom.Node import org.w3c.dom.Element   val 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> """   fun main(args: Array<String>) { val dbFactory = DocumentBuilderFactory.newInstance() val dBuilder = dbFactory.newDocumentBuilder() val xmlInput = InputSource(StringReader(xml)) val doc = dBuilder.parse(xmlInput) val nList = doc.getElementsByTagName("Student") for (i in 0 until nList.length) { val node = nList.item(i) if (node.nodeType == Node.ELEMENT_NODE) { val element = node as Element val name = element.getAttribute("Name") println(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)
#.E0.AE.89.E0.AE.AF.E0.AE.BF.E0.AE.B0.E0.AF.8D.2FUyir
உயிர்/Uyir
  இருபரிமாணணி வகை எண் அணி {3, 3}; இருபரிமாணணி2 வகை எண் அணி {3} அணி {3}; என்_எண்கள் வகை எண் {#5.2} அணி {5} = {3.14, 2.83, 5.32, 10.66, 14}; சொற்கள் வகை சரம் {25} அணி {100}; உயரங்கள் = அணி {10, 45, 87, 29, 53}; பெயர்கள் = அணி {"இராஜன்", "சுதன்", "தானி"}; தேதிகள் = அணி {{5, "மாசி", 2010}, {16, "புரட்டாசி", 1982}, {22, "ஆவணி", 1470}}; செவ்வகணி = அணி { அணி {10, 22, 43}, அணி {31, 58, 192}, அணி {46, 73, 65} }; முக்கோண்ணி = அணி { அணி {1}, அணி {2, 3}, அணி {4, 5, 6}, அணி {7, 8, 9, 1, 2} };  
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Smalltalk
Smalltalk
x := #( 1 2 3 1e11 ). y := x collect:#sqrt. xprecision := 3. yprecision := 5.   'sqrt.dat' asFilename writingFileDo:[:fileStream | x with:y do:[:xI :yI | '%.*g\t%.*g\n' printf:{ xprecision . xI . yprecision . yI } on:fileStream ] ]
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#SPL
SPL
x = [1, 2, 3, 10^11] y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791] xprecision = 3 yprecision = 5 > i, 1..4 s1 = #.str(x[i],"g"+xprecision) s2 = #.str(y[i],"g"+yprecision) #.writeline("file.txt",s1+#.tab+s2) <
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.
#MySQL
MySQL
  DROP PROCEDURE IF EXISTS one_hundred_doors;   DELIMITER |   CREATE PROCEDURE one_hundred_doors (n INT) BEGIN DROP TEMPORARY TABLE IF EXISTS doors; CREATE TEMPORARY TABLE doors ( id INTEGER NOT NULL, open BOOLEAN DEFAULT FALSE, PRIMARY KEY (id) );   SET @i = 1; create_doors: LOOP INSERT INTO doors (id, open) values (@i, FALSE); SET @i = @i + 1; IF @i > n THEN LEAVE create_doors; END IF; END LOOP create_doors;   SET @i = 1; toggle_doors: LOOP UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0; SET @i = @i + 1; IF @i > n THEN LEAVE toggle_doors; END IF; END LOOP toggle_doors;   SELECT id FROM doors WHERE open; END|   DELIMITER ;   CALL one_hundred_doors(100);  
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#Crystal
Crystal
def divisors(n : Int32) : Array(Int32) divs = [1] divs2 = [] of Int32   i = 2 while i * i < n if n % i == 0 j = n // i divs << i divs2 << j if i != j end   i += 1 end   i = divs.size - 1   # TODO: Use reverse while i >= 0 divs2 << divs[i] i -= 1 end   divs2 end   def abundant(n : Int32, divs : Array(Int32)) : Bool divs.sum > n end   def semiperfect(n : Int32, divs : Array(Int32)) : Bool if divs.size > 0 h = divs[0] t = divs[1..]   return n < h ? semiperfect(n, t) : n == h || semiperfect(n - h, t) || semiperfect(n, t) end   return false end   def sieve(limit : Int32) : Array(Bool) # false denotes abundant and not semi-perfect. # Only interested in even numbers >= 2   w = Array(Bool).new(limit, false) # An array filled with 'false'   i = 2 while i < limit if !w[i] divs = divisors i   if !abundant(i, divs) w[i] = true elsif semiperfect(i, divs) j = i while j < limit w[j] = true j += i end end end   i += 2 end   w end   def main w = sieve 17000 count = 0 max = 25   print "The first 25 weird numbers are: "   n = 2 while count < max if !w[n] print "#{n} " count += 1 end   n += 2 end   puts "\n" end   require "benchmark" puts Benchmark.measure { 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
#jq
jq
def jq: "\(" # # # # ### # # # # # # # # # # # # #### # ### # # ")";   def banner3D: jq | split("\n") | map( gsub("#"; "╔╗") | gsub(" "; " ") ) | [[range(length;0;-1) | " " * .], . ] | transpose[] | join("") ;   banner3D
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
#Julia
Julia
println(replace(raw""" xxxxx x x x x x x x x x x x x x x xxx x x x x x x x x x x x x x x xx xx xx x x x x xx """, "x" => "_/"))  
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++.
#ALGOL_68
ALGOL 68
STRING domain="tycho.usno.navy.mil", page="cgi-bin/timer.pl";   STRING # search for the needle in the haystack # needle = "UTC", hay stack = "http://"+domain+"/"+page,   re success="^HTTP/[0-9.]* 200", re result description="^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*", re doctype ="\s\s<![Dd][Oo][Cc][Tt][Yy][Pp][Ee] [^>]+>\s+";   PROC raise error = (STRING msg)VOID: ( put(stand error, (msg, new line)); stop);   PROC is html page = (REF STRING page) BOOL: ( BOOL out=grep in string(re success, page, NIL, NIL) = 0; IF INT start, end; grep in string(re result description, page, start, end) = 0 THEN page:=page[end+1:]; IF grep in string(re doctype, page, start, end) = 0 THEN page:=page[start+2:] ELSE raise error("unknown format retrieving page") FI ELSE raise error("unknown error retrieving page") FI; out );   STRING reply; INT rc = http content (reply, domain, haystack, 0); IF rc = 0 AND is html page (reply) THEN STRING line; FILE freply; associate(freply, reply); on logical file end(freply, (REF FILE freply)BOOL: (done; SKIP)); DO get(freply,(line, new line)); IF string in string(needle, NIL, line) THEN print((line, new line)) FI OD; done: SKIP ELSE raise error (strerror (rc)) FI
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Phix
Phix
-- demo\rosetta\Window_management.exw include pGUI.e Ihandle dlg function doFull(Ihandle /*ih*/) IupSetAttribute(dlg,"FULLSCREEN","YES") return IUP_DEFAULT end function function doMax(Ihandle /*ih*/) IupSetAttribute(dlg,"PLACEMENT","MAXIMIZED") -- this is a work-around to get the dialog minimised (on win platform) IupSetAttribute(dlg,"VISIBLE","YES") return IUP_DEFAULT end function function doMin(Ihandle /*ih*/) IupSetAttribute(dlg,"PLACEMENT","MINIMIZED") -- this is a work-around to get the dialog minimised (on win platform) IupSetAttribute(dlg,"VISIBLE","YES") return IUP_DEFAULT end function function doRestore(Ihandle /*ih*/) IupSetAttribute(dlg,"OPACITY","255") IupSetAttribute(dlg,"FULLSCREEN","NO") IupSetAttribute(dlg,"PLACEMENT","NORMAL") IupSetAttribute(dlg,"VISIBLE","YES") return IUP_DEFAULT end function function doDim(Ihandle /*ih*/) IupSetAttribute(dlg,"OPACITY","60") return IUP_DEFAULT end function function doShow(Ihandle /*ih*/) IupSetAttribute(dlg,"OPACITY","255") return IUP_DEFAULT end function function doMove(Ihandle /*ih*/) integer {x,y} = IupGetIntInt(dlg,"SCREENPOSITION") integer shift = iff(IupGetInt(NULL,"SHIFTKEY")?-10,+10) IupShowXY(dlg,x+shift,y+shift) return IUP_DEFAULT end function procedure main() IupOpen() Ihandle hbox = IupHbox({IupButton("restore", Icallback("doRestore")), IupButton("full screen",Icallback("doFull")), IupButton("maximize", Icallback("doMax")), IupButton("minimize", Icallback("doMin")), IupButton("dim", Icallback("doDim")), IupButton("show", Icallback("doShow")), IupButton("move", Icallback("doMove"))}) IupSetAttribute(hbox,"MARGIN", "10x10") IupSetAttribute(hbox,"PADDING", "5x5") dlg = IupDialog(hbox) IupSetAttribute(dlg,"OPACITY","255") IupShowXY(dlg,IUP_CENTER,IUP_CENTER) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#AutoHotkey
AutoHotkey
URLDownloadToFile, http://www.gutenberg.org/files/135/135-0.txt, % A_temp "\tempfile.txt" FileRead, H, % A_temp "\tempfile.txt" FileDelete,  % A_temp "\tempfile.txt" words := [] while pos := RegExMatch(H, "\b[[:alpha:]]+\b", m, A_Index=1?1:pos+StrLen(m)) words[m] := words[m] ? words[m] + 1 : 1 for word, count in words list .= count "`t" word "`r`n" Sort, list, RN loop, parse, list, `n, `r { result .= A_LoopField "`r`n" if A_Index = 10 break } MsgBox % "Freq`tWord`n" result return
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.
#C.2B.2B
C++
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string>   #include <unistd.h> // for usleep   enum cell_type { none, wire, head, tail };   // ***************** // * display class * // *****************   // this is just a small wrapper for the ggi interface   class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); }   void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; };   display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); }   visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); }   ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) // we need 4 colors! ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC);   size_x = mode.virt.x; size_y = mode.virt.y;   for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); }   void display::flush() { // set the current display frame to the one we have drawn to ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));   // flush the current visual ggiFlush(visual);   // try to set a different frame for drawing (errors are ignored; if // setting the new frame fails, the current one will be drawn upon, // with the only adverse effect being some flickering). ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); }   void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); }   void display::putpixel(int x, int y, cell_type cell) { // this draws a logical pixel (i.e. a rectangle of size pixel_size_x // times pixel_size_y), not a physical pixel ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); }   // ***************** // * the wireworld * // *****************   // initialized to an empty wireworld class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; };   void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } }   void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); }   void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { // std::cout << i->second; if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } }   ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, // background: black { 0x8000, 0x8000, 0x8000 }, // wire: white { 0xffff, 0xffff, 0x0000 }, // electron head: yellow { 0xffff, 0x0000, 0x0000 }}; // electron tail: red   int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5;   if (argc < 2) { std::cerr << "No file name given!\n"; return 1; }   // assume that the first argument is the name of a file to parse std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; // no need to explicitly set this, so do nothing } } ++line_number; }   display d(display_x, display_y, pixel_x, pixel_y, colors);   w.draw(d);   while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Haskell
Haskell
isPrime :: Integer -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Integer root = toInteger $ floor $ sqrt $ fromIntegral n   isWieferichPrime :: Integer -> Bool isWieferichPrime n = isPrime n && mod ( 2 ^ ( n - 1 ) - 1 ) ( n ^ 2 ) == 0   solution :: [Integer] solution = filter isWieferichPrime [2 .. 5000]   main :: IO ( ) main = do putStrLn "Wieferich primes less than 5000:" print solution
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Java
Java
import java.util.*;   public class WieferichPrimes { public static void main(String[] args) { final int limit = 5000; System.out.printf("Wieferich primes less than %d:\n", limit); for (Integer p : wieferichPrimes(limit)) System.out.println(p); }   private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; }   private static long modpow(long base, long exp, long mod) { if (mod == 1) return 0; long result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; }   private static List<Integer> wieferichPrimes(int limit) { boolean[] sieve = primeSieve(limit); List<Integer> result = new ArrayList<>(); for (int p = 2; p < limit; ++p) { if (sieve[p] && modpow(2, p - 1, p * p) == 1) result.add(p); } return result; } }
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Nim
Nim
import x11/[xlib,xutil,x]   const windowWidth = 1000 windowHeight = 600 borderWidth = 5 eventMask = ButtonPressMask or KeyPressMask or ExposureMask   var display: PDisplay window: Window deleteMessage: Atom graphicsContext: GC   proc init() = display = XOpenDisplay(nil) if display == nil: quit "Failed to open display"   let screen = XDefaultScreen(display) rootWindow = XRootWindow(display, screen) foregroundColor = XBlackPixel(display, screen) backgroundColor = XWhitePixel(display, screen)   window = XCreateSimpleWindow(display, rootWindow, -1, -1, windowWidth, windowHeight, borderWidth, foregroundColor, backgroundColor)   discard XSetStandardProperties(display, window, "X11 Example", "window", 0, nil, 0, nil)   discard XSelectInput(display, window, eventMask) discard XMapWindow(display, window)   deleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", false.XBool) discard XSetWMProtocols(display, window, deleteMessage.addr, 1)   graphicsContext = XDefaultGC(display, screen)     proc drawWindow() = const text = "Hello, Nim programmers." discard XDrawString(display, window, graphicsContext, 10, 50, text, text.len) discard XFillRectangle(display, window, graphicsContext, 20, 20, 10, 10)     proc mainLoop() = ## Process events until the quit event is received var event: XEvent while true: discard XNextEvent(display, event.addr) case event.theType of Expose: drawWindow() of ClientMessage: if cast[Atom](event.xclient.data.l[0]) == deleteMessage: break of KeyPress: let key = XLookupKeysym(cast[PXKeyEvent](event.addr), 0) if key != 0: echo "Key ", key, " pressed" of ButtonPressMask: echo "Mouse button ", event.xbutton.button, " pressed at ", event.xbutton.x, ",", event.xbutton.y else: discard     proc main() = init() mainLoop() discard XDestroyWindow(display, window) discard XCloseDisplay(display)     main()
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#OCaml
OCaml
ocaml -I +Xlib Xlib.cma script.ml
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Ruby
Ruby
require "prime"   module Modulo refine Integer do def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m } end end   using Modulo primes = Prime.each(11000).to_a   (1..11).each do |n| res = primes.select do |pr| prpr = pr*pr ((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)**n) % (prpr) == 0 end puts "#{n.to_s.rjust(2)}: #{res.inspect}" end  
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Rust
Rust
// [dependencies] // rug = "1.13.0"   use rug::Integer;   fn generate_primes(limit: usize) -> Vec<usize> { let mut sieve = vec![true; limit >> 1]; let mut p = 3; let mut sq = p * p; while sq < limit { if sieve[p >> 1] { let mut q = sq; while q < limit { sieve[q >> 1] = false; q += p << 1; } } sq += (p + 1) << 2; p += 2; } let mut primes = Vec::new(); if limit > 2 { primes.push(2); } for i in 1..sieve.len() { if sieve[i] { primes.push((i << 1) + 1); } } primes }   fn factorials(limit: usize) -> Vec<Integer> { let mut f = vec![Integer::from(1)]; let mut factorial = Integer::from(1); f.reserve(limit); for i in 1..limit { factorial *= i as u64; f.push(factorial.clone()); } f }   fn main() { let limit = 11000; let f = factorials(limit); let primes = generate_primes(limit); println!(" n | Wilson primes\n--------------------"); let mut s = -1; for n in 1..=11 { print!("{:2} |", n); for p in &primes { if *p >= n { let mut num = Integer::from(&f[n - 1] * &f[*p - n]); num -= s; if num % ((p * p) as u64) == 0 { print!(" {}", p); } } } println!(); s = -s; } }
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Sidef
Sidef
func is_wilson_prime(p, n = 1) { var m = p*p (factorialmod(n-1, m) * factorialmod(p-n, m) - (-1)**n) % m == 0 }   var primes = 1.1e4.primes   say " n: Wilson primes\n────────────────────"   for n in (1..11) { printf("%3d: %s\n", n, primes.grep {|p| is_wilson_prime(p, n) }) }
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.
#E
E
when (currentVat.morphInto("awt")) -> { def w := <swing:makeJFrame>("Window") w.setContentPane(<swing:makeJLabel>("Contents")) w.pack() w.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.
#Eiffel
Eiffel
class APPLICATION inherit EV_APPLICATION create make_and_launch feature {NONE} -- Initialization make_and_launch -- Initialize and launch application do default_create create first_window first_window.show launch end feature {NONE} -- Implementation first_window: MAIN_WINDOW -- Main window. end
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
my $rows = 10; my $cols = 10;   my $message = q:to/END/; .....R.... ......O... .......S.. ........E. T........T .A........ ..C....... ...O...... ....D..... .....E.... END   my %dir = '→' => (1,0), '↘' => (1,1), '↓' => (0,1), '↙' => (-1,1), '←' => (-1,0), '↖' => (-1,-1), '↑' => (0,-1), '↗' => (1,-1) ;   my @ws = $message.comb(/<print>/);   my $path = './unixdict.txt'; # or wherever   my @words = $path.IO.slurp.words.grep( { $_ !~~ /<-[a..z]>/ and 2 < .chars < 11 } ).pick(*); my %index; my %used;   while @ws.first( * eq '.') {   # find an unfilled cell my $i = @ws.grep( * eq '.', :k ).pick;   # translate the index to x / y coordinates my ($x, $y) = $i % $cols, floor($i / $rows);   # find a word that fits my $word = find($x, $y);   # Meh, reached an impasse, easier to just throw it all # away and start over rather than trying to backtrack. restart, next unless $word;   %used{"$word"}++;   # Keeps trying to place an already used word, choices # must be limited, start over restart, next if %used{$word} > 15;   # Already used this word, try again next if %index{$word.key};   # Add word to used word index %index ,= $word;   # place the word into the grid place($x, $y, $word);   }   display();   sub display { put flat " ", 'ABCDEFGHIJ'.comb; .put for (^10).map: { ($_).fmt("  %2d"), @ws[$_ * $cols .. ($_ + 1) * $cols - 1] } put "\n Words used:"; my $max = 1 + %index.keys.max( *.chars ).chars; for %index.sort { printf "%{$max}s %4s %s ", .key, .value.key, .value.value; print "\n" if $++ % 2; } say "\n" }   sub restart { @ws = $message.comb(/<print>/); %index = (); %used = (); }   sub place ($x is copy, $y is copy, $w) { my @word = $w.key.comb; my $dir = %dir{$w.value.value}; @ws[$y * $rows + $x] = @word.shift; while @word { ($x, $y) »+=« $dir; @ws[$y * $rows + $x] = @word.shift; } }   sub find ($x, $y) { my @trials = %dir.keys.map: -> $dir { my $space = '.'; my ($c, $r) = $x, $y; loop { ($c, $r) »+=« %dir{$dir}; last if 9 < $r|$c; last if 0 > $r|$c; my $l = @ws[$r * $rows + $c]; last if $l ~~ /<:Lu>/; $space ~= $l; } next if $space.chars < 3; [$space.trans( '.' => ' ' ), ("{'ABCDEFGHIJ'.comb[$x]} {$y}" => $dir)] };   for @words.pick(*) -> $word { for @trials -> $space { next if $word.chars > $space[0].chars; return ($word => $space[1]) if compare($space[0].comb, $word.comb) } } }   sub compare (@s, @w) { for ^@w { next if @s[$_] eq ' '; return False if @s[$_] ne @w[$_] } True }
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Dyalect
Dyalect
let loremIpsum = <[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu nibh.]>   func wrap(text, lineWidth) { String.Concat(values: wrapWords(text.Split('\s', '\r', '\n'), lineWidth)) } and wrapWords(words, lineWidth) { var currentWidth = 0   for word in words { if currentWidth != 0 { if currentWidth + word.Length() < lineWidth { currentWidth += 1 yield " " } else { currentWidth = 0 yield "\n" } } currentWidth += word.Length() yield word } } and printWrap(at) { print("Wrap at \(at):") print(wrap(loremIpsum, at)) print() }   printWrap(at: 72) printWrap(at: 80)
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elena
Elena
import extensions; import system'routines; import extensions'text;   string 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.";   extension wrapOp { wrap(int lineWidth) { int currentWidth := 0;   ^ TokenEnumerator .new(self) .selectBy:(word) { currentWidth += word.Length; if (currentWidth > lineWidth) { currentWidth := word.Length + 1;   ^ newLine + word + " " } else { currentWidth += 1;   ^ word + " " } } .summarize(new StringWriter()) } }   public program() { console.printLine(new StringWriter("-", 72)); console.printLine(text.wrap(72)); console.printLine(new StringWriter("-", 80)); console.printLine(text.wrap(80)); }
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
use Terminal::Boxer;   my %*SUB-MAIN-OPTS = :named-anywhere;   unit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);   my $must-have = $wheel.comb[4].lc;   my $has = $wheel.comb».lc.Bag;   my %words; $dict.IO.slurp.words».lc.map: { next if not .contains($must-have) or .chars < $min; %words{.chars}.push: $_ if .comb.Bag ⊆ $has; };   say "Using $dict, minimum $min letters.";   print rs-box :3col, :3cw, :indent("\t"), $wheel.comb».uc;   say "{sum %words.values».elems} words found";   printf "%d letters:  %s\n", .key, .value.sort.join(', ') for %words.sort;
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Tcl
Tcl
package require Tcl 8.5 package require Tk   proc ::tcl::mathfunc::ipart x {expr {int($x)}} proc ::tcl::mathfunc::fpart x {expr {$x - int($x)}} proc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}}   proc drawAntialiasedLine {image colour p1 p2} { lassign $p1 x1 y1 lassign $p2 x2 y2   set steep [expr {abs($y2 - $y1) > abs($x2 - $x1)}] if {$steep} { lassign [list $x1 $y1] y1 x1 lassign [list $x2 $y2] y2 x2 } if {$x1 > $x2} { lassign [list $x1 $x2] x2 x1 lassign [list $y1 $y2] y2 y1 } set deltax [expr {$x2 - $x1}] set deltay [expr {abs($y2 - $y1)}] set gradient [expr {1.0 * $deltay / $deltax}]   # handle the first endpoint set xend [expr {round($x1)}] set yend [expr {$y1 + $gradient * ($xend - $x1)}] set xgap [expr {rfpart($x1 + 0.5)}] set xpxl1 $xend set ypxl1 [expr {ipart($yend)}] plot $image $colour $steep $xpxl1 $ypxl1 [expr {rfpart($yend)*$xgap}] plot $image $colour $steep $xpxl1 [expr {$ypxl1+1}] [expr {fpart($yend)*$xgap}] set itery [expr {$yend + $gradient}]   # handle the second endpoint set xend [expr {round($x2)}] set yend [expr {$y2 + $gradient * ($xend - $x2)}] set xgap [expr {rfpart($x2 + 0.5)}] set xpxl2 $xend set ypxl2 [expr {ipart($yend)}] plot $image $colour $steep $xpxl2 $ypxl2 [expr {rfpart($yend)*$xgap}] plot $image $colour $steep $xpxl2 [expr {$ypxl2+1}] [expr {fpart($yend)*$xgap}]   for {set x [expr {$xpxl1 + 1}]} {$x < $xpxl2} {incr x} { plot $image $colour $steep $x [expr {ipart($itery)}] [expr {rfpart($itery)}] plot $image $colour $steep $x [expr {ipart($itery) + 1}] [expr {fpart($itery)}] set itery [expr {$itery + $gradient}] } }   proc plot {image colour steep x y c} { set point [expr {$steep ? [list $y $x] : [list $x $y]}] set newColour [antialias $colour [getPixel $image $point] $c] setPixel $image $newColour $point }   proc antialias {newColour oldColour c} { # get the new colour r,g,b if {[scan $newColour "#%2x%2x%2x%c" nr ng gb -] != 3} { scan [colour2rgb $newColour] "#%2x%2x%2x" nr ng nb }   # get the current colour r,g,b scan $oldColour "#%2x%2x%2x" cr cg cb   # blend the colours in the ratio defined by "c" foreach new [list $nr $ng $nb] curr [list $cr $cg $cb] { append blend [format {%02x} [expr {round($new*$c + $curr*(1.0-$c))}]] } return #$blend }   proc colour2rgb {color_name} { foreach part [winfo rgb . $color_name] { append colour [format %02x [expr {$part >> 8}]] } return #$colour }   set img [newImage 500 500] fill $img blue for {set a 10} {$a < 500} {incr a 60} { drawAntialiasedLine $img yellow {10 10} [list 490 $a] drawAntialiasedLine $img yellow {10 10} [list $a 490] } toplevel .wu label .wu.l -image $img pack .wu.l
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
c = {"April", "Tam O'Shanter","Emily"}; r = {"Bubbly:I'm > Tam and <= Emily" , StringReplace["Burns:\"When chapman billies leave the street ...\"", "\"" -> ""], "Short & shrift"}; ExportString[ XMLElement[ "CharacterRemarks", {}, {XMLElement["Character", {"name" -> c[[1]]}, {r[[1]]}], XMLElement["Character", {"name" -> c[[2]]}, {r[[2]]}], XMLElement["Character", {"name" -> c[[3]]}, {r[[3]]}] }], "XML", "AttributeQuoting" -> "\""]
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.
#MATLAB
MATLAB
RootXML = com.mathworks.xml.XMLUtils.createDocument('CharacterRemarks'); docRootNode = RootXML.getDocumentElement; thisElement = RootXML.createElement('Character'); thisElement.setAttribute('Name','April') thisElement.setTextContent('Bubbly: I''m > Tam and <= Emily'); docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Character'); thisElement.setAttribute('Name','Tam O''Shanter') thisElement.setTextContent('Burns: "When chapman billies leave the street ..."'); docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Character'); thisElement.setAttribute('Name','Emily') thisElement.setTextContent('Short & shrift'); docRootNode.appendChild(thisElement);
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
#Lasso
Lasso
// makes extracting attribute values easier define xml_attrmap(in::xml_namedNodeMap_attr) => { local(out = map) with attr in #in do #out->insert(#attr->name = #attr->value) return #out }   local( text = '<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 = xml(#text) )   local( students = #xml -> extract('//Student'), names = array ) with student in #students do { #names -> insert(xml_attrmap(#student -> attributes) -> find('Name')) } #names -> join('<br />')  
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)
#Vala
Vala
  int[] array = new int[10];   array[0] = 1; array[1] = 3;   stdout.printf("%d\n", array[0]);  
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Standard_ML
Standard ML
fun writeDat (filename, x, y, xprec, yprec) = let val os = TextIO.openOut filename fun write_line (a, b) = TextIO.output (os, Real.fmt (StringCvt.GEN (SOME xprec)) a ^ "\t" ^ Real.fmt (StringCvt.GEN (SOME yprec)) b ^ "\n") in ListPair.appEq write_line (x, y); TextIO.closeOut os end;
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Stata
Stata
* Create the dataset clear mat x=1\2\3\1e11 svmat double x ren *1 * gen y=sqrt(x) format %10.1g x format %10.5g y   * Save as text file export delim file.txt, delim(" ") novar datafmt replace
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.
#Nanoquery
Nanoquery
// allocate a boolean array with all closed doors (false) // we need 101 since there will technically be a door 0 doors = {false} * 101   // loop through all the step lengths (1-100) for step in range(1, 100) // loop through all the doors, stepping by step for door in range(0, len(doors) - 1, step) // change the state of the current door doors[door] = !doors[door] end for end for   // loop through and print the doors that are open, skipping door 0 for i in range(1, len(doors) - 1) // if the door is open, display it if doors[i] println "Door " + i + " is open." end if end for
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#D
D
import std.algorithm; import std.array; import std.stdio;   int[] divisors(int n) { int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs2 ~= divs.reverse; return divs2; }   bool abundant(int n, int[] divs) { return divs.sum() > n; }   bool semiperfect(int n, int[] divs) { // This algorithm is O(2^N) for N == divs.length when number is not semiperfect. // Comparing with (divs.sum < n) instead (divs.length==0) removes unnecessary // recursive binary tree branches. auto s = divs.sum; if(s == n) return true; else if ( s<n ) return false; else { auto h = divs[0]; auto t = divs[1..$]; if (n < h) { return semiperfect(n, t); } else { return n == h // Supossin h is part of the sum || semiperfect(n - h, t) // Supossin h is not part of the sum || semiperfect(n, t); } } }   bool[] sieve(int limit) { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 auto w = uninitializedArray!(bool[])(limit); w[] = false; for (int i = 2; i < limit; i += 2) { if (w[i]) continue; auto divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (int j = i; j < limit; j += i) { w[j] = true; } } } return w; }   void main() { auto w = sieve(17_000); int count = 0; int max = 25; writeln("The first 25 weird numbers:"); for (int n = 2; count < max; n += 2) { if (!w[n]) { write(n, ' '); count++; } } writeln; }
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
#Kotlin
Kotlin
// version 1.1   class Ascii3D(s: String) { val z = charArrayOf(' ', ' ', '_', '/')   val f = arrayOf( longArrayOf(87381, 87381, 87381, 87381, 87381, 87381, 87381), longArrayOf(349525, 375733, 742837, 742837, 375733, 349525, 349525), longArrayOf(742741, 768853, 742837, 742837, 768853, 349525, 349525), longArrayOf(349525, 375733, 742741, 742741, 375733, 349525, 349525), longArrayOf(349621, 375733, 742837, 742837, 375733, 349525, 349525), longArrayOf(349525, 375637, 768949, 742741, 375733, 349525, 349525), longArrayOf(351157, 374101, 768949, 374101, 374101, 349525, 349525), longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 351157), longArrayOf(742741, 768853, 742837, 742837, 742837, 349525, 349525), longArrayOf(181, 85, 181, 181, 181, 85, 85), longArrayOf(1461, 1365, 1461, 1461, 1461, 1461, 2901), longArrayOf(742741, 744277, 767317, 744277, 742837, 349525, 349525), longArrayOf(181, 181, 181, 181, 181, 85, 85), longArrayOf(1431655765, 3149249365L, 3042661813L, 3042661813L, 3042661813L, 1431655765, 1431655765), longArrayOf(349525, 768853, 742837, 742837, 742837, 349525, 349525), longArrayOf(349525, 375637, 742837, 742837, 375637, 349525, 349525), longArrayOf(349525, 768853, 742837, 742837, 768853, 742741, 742741), longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 349621), longArrayOf(349525, 744373, 767317, 742741, 742741, 349525, 349525), longArrayOf(349525, 375733, 767317, 351157, 768853, 349525, 349525), longArrayOf(374101, 768949, 374101, 374101, 351157, 349525, 349525), longArrayOf(349525, 742837, 742837, 742837, 375733, 349525, 349525), longArrayOf(5592405, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405), longArrayOf(366503875925L, 778827027893L, 778827027893L, 392374737749L, 368114513237L, 366503875925L, 366503875925L), longArrayOf(349525, 742837, 375637, 742837, 742837, 349525, 349525), longArrayOf(349525, 742837, 742837, 742837, 375733, 349621, 375637), longArrayOf(349525, 768949, 351061, 374101, 768949, 349525, 349525), longArrayOf(375637, 742837, 768949, 742837, 742837, 349525, 349525), longArrayOf(768853, 742837, 768853, 742837, 768853, 349525, 349525), longArrayOf(375733, 742741, 742741, 742741, 375733, 349525, 349525), longArrayOf(192213, 185709, 185709, 185709, 192213, 87381, 87381), longArrayOf(1817525, 1791317, 1817429, 1791317, 1817525, 1398101, 1398101), longArrayOf(768949, 742741, 768853, 742741, 742741, 349525, 349525), longArrayOf(375733, 742741, 744373, 742837, 375733, 349525, 349525), longArrayOf(742837, 742837, 768949, 742837, 742837, 349525, 349525), longArrayOf(48053, 23381, 23381, 23381, 48053, 21845, 21845), longArrayOf(349621, 349621, 349621, 742837, 375637, 349525, 349525), longArrayOf(742837, 744277, 767317, 744277, 742837, 349525, 349525), longArrayOf(742741, 742741, 742741, 742741, 768949, 349525, 349525), longArrayOf(11883957, 12278709, 11908533, 11883957, 11883957, 5592405, 5592405), longArrayOf(11883957, 12277173, 11908533, 11885493, 11883957, 5592405, 5592405), longArrayOf(375637, 742837, 742837, 742837, 375637, 349525, 349525), longArrayOf(768853, 742837, 768853, 742741, 742741, 349525, 349525), longArrayOf(6010197, 11885397, 11909973, 11885397, 6010293, 5592405, 5592405), longArrayOf(768853, 742837, 768853, 742837, 742837, 349525, 349525), longArrayOf(375733, 742741, 375637, 349621, 768853, 349525, 349525), longArrayOf(12303285, 5616981, 5616981, 5616981, 5616981, 5592405, 5592405), longArrayOf(742837, 742837, 742837, 742837, 375637, 349525, 349525), longArrayOf(11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405), longArrayOf(3042268597L, 3042268597L, 3042661813L, 1532713813, 1437971797, 1431655765, 1431655765), longArrayOf(11883957, 5987157, 5616981, 5987157, 11883957, 5592405, 5592405), longArrayOf(11883957, 5987157, 5616981, 5616981, 5616981, 5592405, 5592405), longArrayOf(12303285, 5593941, 5616981, 5985621, 12303285, 5592405, 5592405) )   init { val o = Array(7) { StringBuilder() } for (i in 0 until s.length) { var c = s[i].toInt() if (c in 65..90) { c -= 39 } else if (c in 97..122) { c -= 97 } else { c = -1 } val d = f[++c] for (j in 0 until 7) { val b = StringBuilder() var v = d[j] while (v > 0) { b.append(z[(v and 3).toInt()]) v = v shr 2 } o[j].append(b.reverse().toString()) } } for (i in 0 until 7) { for (j in 0 until 7 - i) print(' ') println(o[i]) } } }   fun main(args: Array<String>) { Ascii3D("KOTLIN") Ascii3D("with thanks") Ascii3D("to the author") Ascii3D("of the") Ascii3D("Java entry") }
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++.
#App_Inventor
App Inventor
  when ScrapeButton.Click do set ScrapeWeb.Url to SourceTextBox.Text call ScrapeWeb.Get   when ScrapeWeb.GotText url,responseCode,responseType,responseContent do initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text) initialize local Right to "" in set Right to select list item (list: get Left, index: 2) set ResultLabel.Text to select list item (list: split at first (text:get Right, at: PostTextBox.Text), index: 1)  
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation"   on firstDateonWebPage(URLText) set |⌘| to current application set pageURL to |⌘|'s class "NSURL"'s URLWithString:(URLText) -- Fetch the page HTML as data. -- The Xcode documentation advises against using dataWithContentsOfURL: over a network, -- but I'm guessing this applies to downloading large files rather than a Web page's HTML. -- If in doubt, the HTML can be fetched as text instead and converted to data in house. set HTMLData to |⌘|'s class "NSData"'s dataWithContentsOfURL:(pageURL) -- Or: (* set {HTMLText, encoding} to |⌘|'s class "NSString"'s stringWithContentsOfURL:(pageURL) ¬ usedEncoding:(reference) |error|:(missing value) set HTMLData to HTMLText's dataUsingEncoding:(encoding) *)   -- Extract the page's visible text from the HTML. set straightText to (|⌘|'s class "NSAttributedString"'s alloc()'s initWithHTML:(HTMLData) ¬ documentAttributes:(missing value))'s |string|()   -- Use an NSDataDetector to locate the first date in the text. (It's assumed here there'll be one.) set dateDetector to |⌘|'s class "NSDataDetector"'s dataDetectorWithTypes:(|⌘|'s NSTextCheckingTypeDate) ¬ |error|:(missing value) set matchRange to dateDetector's rangeOfFirstMatchInString:(straightText) options:(0) ¬ range:({0, straightText's |length|()})   -- Return the date text found. return (straightText's substringWithRange:(matchRange)) as text end firstDateonWebPage   firstDateonWebPage("https://www.rosettacode.org/wiki/Talk:Web_scraping")
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#PicoLisp
PicoLisp
$ ersatz/pil + : (setq JFrame "javax.swing.JFrame" MAXIMIZED_BOTH (java (public JFrame 'MAXIMIZED_BOTH)) ICONIFIED (java (public JFrame 'ICONIFIED)) Win (java JFrame T "Window") ) -> $JFrame   # Compare for equality : (== Win Win) -> T   # Set window visible (java Win 'setLocation 100 100) (java Win 'setSize 400 300) (java Win 'setVisible T)   # Hide window (java Win 'hide)   # Show again (java Win 'setVisible T)   # Move window (java Win 'setLocation 200 200)   # Iconify window (java Win 'setExtendedState (| (java (java Win 'getExtendedState)) ICONIFIED) )   # De-conify window (java Win 'setExtendedState (& (java (java Win 'getExtendedState)) (x| (hex "FFFFFFFF") ICONIFIED)) )   # Maximize window (java Win 'setExtendedState (| (java (java Win 'getExtendedState)) MAXIMIZED_BOTH) )   # Close window (java Win 'dispose)
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#PureBasic
PureBasic
;- Create a linked list to store created windows. NewList Windows() Define i, j, dh, dw, flags, err$, x, y   ;- Used sub-procedure to simplify the error handling Procedure HandleError(Result, Text.s,ErrorLine=0,ExitCode=0) If Not Result MessageRequester("Error",Text) End ExitCode EndIf ProcedureReturn Result EndProcedure   ;- Window handling procedures Procedure Minimize(window) SetWindowState(window,#PB_Window_Minimize) EndProcedure   Procedure Normalize(window) SetWindowState(window,#PB_Window_Normal) EndProcedure   ;- Get enviroment data HandleError(ExamineDesktops(), "Failed to examine you Desktop.") dh=HandleError(DesktopHeight(0),"Could not retrieve DesktopHight")/3 dw=HandleError(DesktopWidth(0), "Could not retrieve DesktopWidth")/3   ;- Now, creating 9 windows flags=#PB_Window_SystemMenu err$="Failed to open Window" For i=0 To 8 j=HandleError(OpenWindow(#PB_Any,i*10,i*10+30,10,10,Str(i),flags),err$) SmartWindowRefresh(j, 1) AddElement(Windows()) Windows()=j Next i Delay(1000)   ;- Call a sub-routine for each Window stored in the list. ForEach Windows() Minimize(Windows()) Next Delay(1000) ;- and again ForEach Windows() Normalize(Windows()) Next Delay(1000)   ;- Spread them evenly ForEach Windows() ResizeWindow(Windows(),x*dw,y*dh,dw-15,dh-35) x+1 If x>2 x=0: y+1 EndIf Next Delay(2000)   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
#AWK
AWK
  # syntax: GAWK -f WORD_FREQUENCY.AWK [-v show=x] LES_MISERABLES.TXT # # A word is anything separated by white space. # Therefor "this" and "this." are different. # But "This" and "this" are identical. # As I am "free to define what a letter is" I have chosen to allow # numerics and all special characters as they are usually considered # parts of words in text processing applications. # { nbytes += length($0) + 2 # +2 for CR/LF nfields += NF $0 = tolower($0) for (i=1; i<=NF; i++) { arr[$i]++ } } END { show = (show == "") ? 10 : show width1 = length(show) PROCINFO["sorted_in"] = "@val_num_desc" for (i in arr) { if (width2 == 0) { width2 = length(arr[i]) } if (n++ >= show) { break } printf("%*d %*d %s\n",width1,n,width2,arr[i],i) } printf("input: %d records, %d bytes, %d words of which %d are unique\n",NR,nbytes,nfields,length(arr)) exit(0) }  
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.
#Ceylon
Ceylon
abstract class Cell(shared Character char) of emptyCell | head | tail | conductor {   shared Cell output({Cell*} neighbors) => switch (this) case (emptyCell) emptyCell case (head) tail case (tail) conductor case (conductor) (neighbors.count(head.equals) in 1..2 then head else conductor);   string => char.string; }   object emptyCell extends Cell(' ') {}   object head extends Cell('H') {}   object tail extends Cell('t') {}   object conductor extends Cell('.') {}   Map<Character,Cell> cellsByChar = map { for (cell in `Cell`.caseValues) cell.char->cell };   class Wireworld(String data) {   value lines = data.lines;   value width = max(lines*.size); value height = lines.size;   function toIndex(Integer x, Integer y) => x + y * width;   variable value currentState = Array.ofSize(width * height, emptyCell); variable value nextState = Array.ofSize(width * height, emptyCell);   for (j->line in lines.indexed) { for (i->char in line.indexed) { currentState[toIndex(i, j)] = cellsByChar[char] else emptyCell; } }   value emptyGrid = Array.ofSize(width * height, emptyCell); void clear(Array<Cell> cells) => emptyGrid.copyTo(cells);   shared void update() { clear(nextState); for(j in 0:height) { for(i in 0:width) { if(exists cell = currentState[toIndex(i, j)]) { value nextCell = cell.output(neighborhood(currentState, i, j)); nextState[toIndex(i, j)] = nextCell; } } } value temp = currentState; currentState = nextState; nextState = temp; }   shared void display() { for (row in currentState.partition(width)) { print("".join(row)); } }   shared {Cell*} neighborhood(Array<Cell> grid, Integer x, Integer y) => { for (j in y - 1..y + 1) for (i in x - 1..x + 1) if(i in 0:width && j in 0:height) grid[toIndex(i, j)] }.coalesced;   }   shared void run() { value data = "tH......... . . ... . . Ht.. ......";   value world = Wireworld(data);   variable value generation = 0;   void display() { print("generation: ``generation``"); world.display(); }   display();   while (true) { if (exists input = process.readLine(), input.lowercased == "q") { return; } world.update(); generation++; display();   } }  
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.
#Common_Lisp
Common Lisp
(defun electron-neighbors (wireworld row col) (destructuring-bind (rows cols) (array-dimensions wireworld) (loop for off-row from (max 0 (1- row)) to (min (1- rows) (1+ row)) sum (loop for off-col from (max 0 (1- col)) to (min (1- cols) (1+ col)) count (and (not (and (= off-row row) (= off-col col))) (eq 'electron-head (aref wireworld off-row off-col)))))))   (defun wireworld-next-generation (wireworld) (destructuring-bind (rows cols) (array-dimensions wireworld) (let ((backing (make-array (list rows cols)))) (do ((c 0 (if (= c (1- cols)) 0 (1+ c))) (r 0 (if (= c (1- cols)) (1+ r) r))) ((= r rows)) (setf (aref backing r c) (aref wireworld r c))) (do ((c 0 (if (= c (1- cols)) 0 (1+ c))) (r 0 (if (= c (1- cols)) (1+ r) r))) ((= r rows)) (setf (aref wireworld r c) (case (aref backing r c) (electron-head 'electron-tail) (electron-tail 'conductor) (conductor (case (electron-neighbors backing r c) ((1 2) 'electron-head) (otherwise 'conductor))) (otherwise nil)))))))   (defun print-wireworld (wireworld) (destructuring-bind (rows cols) (array-dimensions wireworld) (do ((r 0 (1+ r))) ((= r rows)) (do ((c 0 (1+ c))) ((= c cols)) (format t "~C" (case (aref wireworld r c) (electron-head #\H) (electron-tail #\t) (conductor #\.) (otherwise #\Space)))) (format t "~&"))))   (defun wireworld-show-gens (wireworld n) (dotimes (m n) (terpri) (wireworld-next-generation wireworld) (print-wireworld wireworld)))   (defun ww-char-to-symbol (char) (ecase char (#\Space 'nil) (#\. 'conductor) (#\t 'electron-tail) (#\H 'electron-head)))   (defun make-wireworld (image) "Make a wireworld grid from a list of strings (rows) of equal length (columns), each character being ' ', '.', 'H', or 't'." (make-array (list (length image) (length (first image))) :initial-contents (mapcar (lambda (s) (map 'list #'ww-char-to-symbol s)) image)))   (defun make-rosetta-wireworld () (make-wireworld '("tH........." ". . " " ... " ". . " "Ht.. ......")))
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#jq
jq
def is_prime: . as $n | if ($n < 2) then false elif ($n % 2 == 0) then $n == 2 elif ($n % 3 == 0) then $n == 3 elif ($n % 5 == 0) then $n == 5 elif ($n % 7 == 0) then $n == 7 elif ($n % 11 == 0) then $n == 11 elif ($n % 13 == 0) then $n == 13 elif ($n % 17 == 0) then $n == 17 elif ($n % 19 == 0) then $n == 19 else {i:23} | until( (.i * .i) > $n or ($n % .i == 0); .i += 2) | .i * .i > $n end;   # Emit an array of primes less than `.` def primes: if . < 2 then [] else [2] + [range(3; .; 2) | select(is_prime)] end;   # for the sake of infinite-precision integer arithmetic def power($b): . as $a | reduce range(0; $b) as $i (1; .*$a);  
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Julia
Julia
using Primes   println(filter(p -> (big"2"^(p - 1) - 1) % p^2 == 0, primes(5000))) # [1093, 3511]  
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[WieferichPrimeQ] WieferichPrimeQ[n_Integer] := PrimeQ[n] && Divisible[2^(n - 1) - 1, n^2] Select[Range[5000], WieferichPrimeQ]
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Nim
Nim
import math import bignum   func isPrime(n: Positive): bool = if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d <= sqrt(n.toFloat).int: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 result = true   echo "Wieferich primes less than 5000:" let two = newInt(2) for p in 2u..<5000: if p.isPrime: if exp(two, p - 1, p * p) == 1: # Modular exponentiation. echo p
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#PARI.2FGP
PARI/GP
iswief(p)=if(isprime(p)&&(2^(p-1)-1)%p^2==0,1,0) for(N=1,5000,if(iswief(N),print(N)))
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Pascal
Pascal
program xshowwindow; {$mode objfpc}{$H+}   uses xlib, x, ctypes;   procedure ModalShowX11Window(AMsg: string); var d: PDisplay; w: TWindow; e: TXEvent; msg: PChar; s: cint; begin msg := PChar(AMsg);   { open connection with the server } d := XOpenDisplay(nil); if (d = nil) then begin WriteLn('[ModalShowX11Window] Cannot open display'); exit; end; s := DefaultScreen(d);   { create window } w := XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 50, 1, BlackPixel(d, s), WhitePixel(d, s));   { select kind of events we are interested in } XSelectInput(d, w, ExposureMask or KeyPressMask);   { map (show) the window } XMapWindow(d, w);   { event loop } while (True) do begin XNextEvent(d, @e); { draw or redraw the window } if (e._type = Expose) then begin XFillRectangle(d, w, DefaultGC(d, s), 0, 10, 100, 3); XFillRectangle(d, w, DefaultGC(d, s), 0, 30, 100, 3); XDrawString (d, w, DefaultGC(d, s), 5, 25, msg, strlen(msg)); end; { exit on key press } if (e._type = KeyPress) then Break; end;   { close connection to server } XCloseDisplay(d); end;   begin ModalShowX11Window('Hello, World!'); end.  
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Wren
Wren
import "/math" for Int import "/big" for BigInt import "/fmt" for Fmt   var limit = 11000 var primes = Int.primeSieve(limit) var facts = List.filled(limit, null) facts[0] = BigInt.one for (i in 1...11000) facts[i] = facts[i-1] * i var sign = 1 System.print(" n: Wilson primes") System.print("--------------------") for (n in 1..11) { Fmt.write("$2d: ", n) sign = -sign for (p in primes) { if (p < n) continue var f = facts[n-1] * facts[p-n] - sign if (f.isDivisibleBy(p*p)) Fmt.write("%(p) ", p) } System.print() }
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.
#Emacs_Lisp
Emacs Lisp
(make-frame)
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.
#Euphoria
Euphoria
include arwen.ew   constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0})   WinMain(win, SW_NORMAL)  
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) 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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly Dirs As Integer(,) = { {1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1} }   Const RowCount = 10 Const ColCount = 10 Const GridSize = RowCount * ColCount Const MinWords = 25   Class Grid Public cells(RowCount - 1, ColCount - 1) As Char Public solutions As New List(Of String) Public numAttempts As Integer   Sub New() For i = 0 To RowCount - 1 For j = 0 To ColCount - 1 cells(i, j) = ControlChars.NullChar Next Next End Sub End Class   Dim Rand As New Random()   Sub Main() PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))) End Sub   Function ReadWords(filename As String) As List(Of String) Dim maxlen = Math.Max(RowCount, ColCount) Dim words As New List(Of String)   Dim objReader As New IO.StreamReader(filename) Dim line As String Do While objReader.Peek() <> -1 line = objReader.ReadLine() If line.Length > 3 And line.Length < maxlen Then If line.All(Function(c) Char.IsLetter(c)) Then words.Add(line) End If End If Loop   Return words End Function   Function CreateWordSearch(words As List(Of String)) As Grid For numAttempts = 1 To 1000 Shuffle(words)   Dim grid As New Grid() Dim messageLen = PlaceMessage(grid, "Rosetta Code") Dim target = GridSize - messageLen   Dim cellsFilled = 0 For Each word In words cellsFilled = cellsFilled + TryPlaceWord(grid, word) If cellsFilled = target Then If grid.solutions.Count >= MinWords Then grid.numAttempts = numAttempts Return grid Else 'grid is full but we didn't pack enough words, start over Exit For End If End If Next Next   Return Nothing End Function   Function PlaceMessage(grid As Grid, msg As String) As Integer msg = msg.ToUpper() msg = msg.Replace(" ", "")   If msg.Length > 0 And msg.Length < GridSize Then Dim gapSize As Integer = GridSize / msg.Length   Dim pos = 0 Dim lastPos = -1 For i = 0 To msg.Length - 1 If i = 0 Then pos = pos + Rand.Next(gapSize - 1) Else pos = pos + Rand.Next(2, gapSize - 1) End If Dim r As Integer = Math.Floor(pos / ColCount) Dim c = pos Mod ColCount   grid.cells(r, c) = msg(i)   lastPos = pos Next Return msg.Length End If   Return 0 End Function   Function TryPlaceWord(grid As Grid, word As String) As Integer Dim randDir = Rand.Next(Dirs.GetLength(0)) Dim randPos = Rand.Next(GridSize)   For d = 0 To Dirs.GetLength(0) - 1 Dim dd = (d + randDir) Mod Dirs.GetLength(0)   For p = 0 To GridSize - 1 Dim pp = (p + randPos) Mod GridSize   Dim lettersPLaced = TryLocation(grid, word, dd, pp) If lettersPLaced > 0 Then Return lettersPLaced End If Next Next   Return 0 End Function   Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer Dim r As Integer = pos / ColCount Dim c = pos Mod ColCount Dim len = word.Length   'check bounds If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then Return 0 End If If r = RowCount OrElse c = ColCount Then Return 0 End If   Dim rr = r Dim cc = c   'check cells For i = 0 To len - 1 If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then Return 0 End If   cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) Next   'place Dim overlaps = 0 rr = r cc = c For i = 0 To len - 1 If grid.cells(rr, cc) = word(i) Then overlaps = overlaps + 1 Else grid.cells(rr, cc) = word(i) End If   If i < len - 1 Then cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) End If Next   Dim lettersPlaced = len - overlaps If lettersPlaced > 0 Then grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr)) End If   Return lettersPlaced End Function   Sub PrintResult(grid As Grid) If IsNothing(grid) OrElse grid.numAttempts = 0 Then Console.WriteLine("No grid to display") Return End If   Console.WriteLine("Attempts: {0}", grid.numAttempts) Console.WriteLine("Number of words: {0}", GridSize) Console.WriteLine()   Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9") For r = 0 To RowCount - 1 Console.WriteLine() Console.Write("{0} ", r) For c = 0 To ColCount - 1 Console.Write(" {0} ", grid.cells(r, c)) Next Next   Console.WriteLine() Console.WriteLine()   For i = 0 To grid.solutions.Count - 1 If i Mod 2 = 0 Then Console.Write("{0}", grid.solutions(i)) Else Console.WriteLine(" {0}", grid.solutions(i)) End If Next   Console.WriteLine() End Sub   'taken from https://stackoverflow.com/a/20449161 Sub Shuffle(Of T)(list As IList(Of T)) Dim r As Random = New Random() For i = 0 To list.Count - 1 Dim index As Integer = r.Next(i, list.Count) If i <> index Then ' swap list(i) and list(index) Dim temp As T = list(i) list(i) = list(index) list(index) = temp End If Next End Sub   End Module
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
#Elixir
Elixir
defmodule Word_wrap do def paragraph( string, max_line_length ) do [word | rest] = String.split( string, ~r/\s+/, trim: true ) lines_assemble( rest, max_line_length, String.length(word), word, [] ) |> Enum.join( "\n" ) end   defp lines_assemble( [], _, _, line, acc ), do: [line | acc] |> Enum.reverse defp lines_assemble( [word | rest], max, line_length, line, acc ) do if line_length + 1 + String.length(word) > max do lines_assemble( rest, max, String.length(word), word, [line | acc] ) else lines_assemble( rest, max, line_length + 1 + String.length(word), line <> " " <> word, acc ) end end end   text = """ 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. """ Enum.each([72, 80], fn len -> IO.puts String.duplicate("-", len) IO.puts Word_wrap.paragraph(text, len) 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
#Erlang
Erlang
  -module( word_wrap ).   -export( [paragraph/2, task/0] ).   paragraph( String, Max_line_length ) -> Lines = lines( string:tokens(String, " "), Max_line_length ), string:join( Lines, "\n" ).   task() -> Paragraph = "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.", io:fwrite( "~s~n~n", [paragraph(Paragraph, 72)] ), io:fwrite( "~s~n~n", [paragraph(Paragraph, 80)] ).       lines( [Word | T], Max_line_length ) -> {Max_line_length, _Length, Last_line, Lines} = lists:foldl( fun lines_assemble/2, {Max_line_length, erlang:length(Word), Word, []}, T ), lists:reverse( [Last_line | Lines] ).   lines_assemble( Word, {Max, Line_length, Line, Acc} ) when erlang:length(Word) + Line_length > Max -> {Max, erlang:length(Word), Word, [Line | Acc]}; lines_assemble( Word, {Max, Line_length, Line, Acc} ) -> {Max, Line_length + 1 + erlang:length(Word), Line ++ " " ++ Word, Acc}.  
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX pgm finds (dictionary) words which can be found in a specified word wheel (grid).*/ parse arg grid minL iFID . /*obtain optional arguments from the CL*/ if grid==''|grid=="," then grid= 'ndeokgelw' /*Not specified? Then use the default.*/ if minL==''|minL=="," then minL= 3 /* " " " " " " */ if iFID==''|iFID=="," then iFID= 'UNIXDICT.TXT' /* " " " " " " */ oMinL= minL; minL= abs(minL) /*if negative, then don't show a list. */ gridU= grid; upper gridU /*get an uppercase version of the grid.*/ Lg= length(grid); Hg= Lg % 2 + 1 /*get length of grid & the middle char.*/ ctr= substr(grid, Hg, 1); upper ctr /*get uppercase center letter in grid. */ wrds= 0 /*# words that are in the dictionary. */ wees= 0 /*" " " " too short. */ bigs= 0 /*" " " " too long. */ dups= 0 /*" " " " duplicates. */ ills= 0 /*" " " contain "not" letters.*/ good= 0 /*" " " contain center letter. */ nine= 0 /*" wheel─words that contain 9 letters.*/ say ' Reading the file: ' iFID /*align the text. */ @.= . /*uppercase non─duplicated dict. words.*/ $= /*the list of dictionary words in grid.*/ do recs=0 while lines(iFID)\==0 /*process all words in the dictionary. */ u= space( linein(iFID), 0); upper u /*elide blanks; uppercase the word. */ L= length(u) /*obtain the length of the word. */ if @.u\==. then do; dups= dups+1; iterate; end /*is this a duplicate? */ if L<minL then do; wees= wees+1; iterate; end /*is the word too short? */ if L>Lg then do; bigs= bigs+1; iterate; end /*is the word too long? */ if \datatype(u,'M') then do; ills= ills+1; iterate; end /*has word non─letters? */ @.u= /*signify that U is a dictionary word*/ wrds= wrds + 1 /*bump the number of "good" dist. words*/ if pos(ctr, u)==0 then iterate /*word doesn't have center grid letter.*/ good= good + 1 /*bump # center─letter words in dict. */ if verify(u, gridU)\==0 then iterate /*word contains a letter not in grid. */ if pruned(u, gridU) then iterate /*have all the letters not been found? */ if L==9 then nine= nine + 1 /*bump # words that have nine letters. */ $= $ u /*add this word to the "found" list. */ end /*recs*/ say say ' number of records (words) in the dictionary: ' right( commas(recs), 9) say ' number of ill─formed words in the dictionary: ' right( commas(ills), 9) say ' number of duplicate words in the dictionary: ' right( commas(dups), 9) say ' number of too─small words in the dictionary: ' right( commas(wees), 9) say ' number of too─long words in the dictionary: ' right( commas(bigs), 9) say ' number of acceptable words in the dictionary: ' right( commas(wrds), 9) say ' number center─letter words in the dictionary: ' right( commas(good), 9) say ' the minimum length of words that can be used: ' right( commas(minL), 9) say ' the word wheel (grid) being used: ' grid say ' center of the word wheel (grid) being used: ' right('↑', Hg) say; #= words($); $= strip($) say ' number of word wheel words in the dictionary: ' right( commas(# ), 9) say ' number of nine-letter wheel words found: ' right( commas(nine), 9) if #==0 | oMinL<0 then exit # say say ' The list of word wheel words found:'; say copies('─', length($)); say lower($) exit # /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ lower: arg aa; @='abcdefghijklmnopqrstuvwxyz'; @u=@; upper @u; return translate(aa,@,@U) commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ pruned: procedure; parse arg aa,gg /*obtain word to be tested, & the grid.*/ do n=1 for length(aa); p= pos( substr(aa,n,1), gg); if p==0 then return 1 gg= overlay(., gg, p) /*"rub out" the found character in grid*/ end /*n*/; return 0 /*signify that the AA passed the test*/
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   class XiaolinWu { construct new(width, height) { Window.title = "Xiaolin Wu's line algorithm" Window.resize(width, height) Canvas.resize(width, height) }   init() { Canvas.cls(Color.white) drawLine(550, 170, 50, 435) }   plot(x, y, c) { var col = Color.rgb(0, 0, 0, c * 255) x = ipart(x) y = ipart(y) Canvas.ellipsefill(x, y, x + 2, y + 2, col) }   ipart(x) { x.truncate }   fpart(x) { x.fraction }   rfpart(x) { 1 - fpart(x) }   drawLine(x0, y0, x1, y1) { var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0) if (steep) drawLine(y0, x0, y1, x1) if (x0 > x1) drawLine(x1, y1, x0, y0) var dx = x1 - x0 var dy = y1 - y0 var gradient = dy / dx   // handle first endpoint var xend = Math.round(x0) var yend = y0 + gradient * (xend - x0) var xgap = rfpart(x0 + 0.5) var xpxl1 = xend // this will be used in the main loop var ypxl1 = ipart(yend)   if (steep) { plot(ypxl1, xpxl1, rfpart(yend) * xgap) plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap) } else { plot(xpxl1, ypxl1, rfpart(yend) * xgap) plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap) }   // first y-intersection for the main loop var intery = yend + gradient   // handle second endpoint xend = Math.round(x1) yend = y1 + gradient * (xend - x1) xgap = fpart(x1 + 0.5) var xpxl2 = xend // this will be used in the main loop var ypxl2 = ipart(yend)   if (steep) { plot(ypxl2, xpxl2, rfpart(yend) * xgap) plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap) } else { plot(xpxl2, ypxl2, rfpart(yend) * xgap) plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap) }   // main loop var x = xpxl1 + 1 while (x <= xpxl2 - 1) { if (steep) { plot(ipart(intery), x, rfpart(intery)) plot(ipart(intery) + 1, x, fpart(intery)) } else { plot(x, ipart(intery), rfpart(intery)) plot(x, ipart(intery) + 1, fpart(intery)) } intery = intery + gradient x = x + 1 } }   update() {}   draw(alpha) {} }   var Game = XiaolinWu.new(640, 640)
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.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols nobinary   import java.io.StringWriter   import javax.xml.parsers.DocumentBuilderFactory import javax.xml.transform.Result import javax.xml.transform.Source import javax.xml.transform.Transformer import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult   import org.w3c.dom.Document import org.w3c.dom.Element   names = [String - "April", "Tam O'Shanter", "Emily" - ]   remarks = [ String - "Bubbly: I'm > Tam and <= Emily" - , 'Burns: "When chapman billies leave the street ..."' - , 'Short & shrift' - ]   do -- Create a new XML document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()   -- Append the root element root = doc.createElement("CharacterRemarks") doc.appendChild(root)   -- Read input data and create a new <Character> element for each name. loop i_ = 0 to names.length - 1 character = doc.createElement("Character") root.appendChild(character) character.setAttribute("name", names[i_]) character.appendChild(doc.createTextNode(remarks[i_])) end i_   -- Serializing XML in Java is unnecessary complicated -- Create a Source from the document. source = DOMSource(doc)   -- This StringWriter acts as a buffer buffer = StringWriter()   -- Create a Result as a transformer target. result = StreamResult(buffer)   -- The Transformer is used to copy the Source to the Result object. transformer = TransformerFactory.newInstance().newTransformer() transformer.setOutputProperty("indent", "yes") transformer.transform(source, result)   -- Now the buffer is filled with the serialized XML and we can print it to the console. say buffer.toString catch ex = Exception ex.printStackTrace end   return  
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Lingo
Lingo
q = QUOTE r = RETURN xml = "<Students>"&r&\ " <Student Name="&q&"April"&q&" Gender="&q&"F"&q&" DateOfBirth="&q&"1989-01-02"&q&" />"&r&\ " <Student Name="&q&"Bob"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1990-03-04"&q&" />"&r&\ " <Student Name="&q&"Chad"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1991-05-06"&q&" />"&r&\ " <Student Name="&q&"Dave"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1992-07-08"&q&">"&r&\ " <Pet Type="&q&"dog"&q&" Name="&q&"Rover"&q&" />"&r&\ " </Student>"&r&\ " <Student DateOfBirth="&q&"1993-09-10"&q&" Gender="&q&"F"&q&" Name="&q&"&#x00C9;mily"&q&" />"&r&\ "</Students>"   parser = xtra("xmlparser").new() parser.parseString(xml) res = parser.makePropList() repeat with c in res.child put c.attributes.name end repeat
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
#LiveCode
LiveCode
put revXMLCreateTree(fld "FieldXML",true,true,false) into currTree put revXMLAttributeValues(currTree,"Students","Student","Name",return,-1)
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)
#VBA
VBA
Option Base {0|1}
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Tcl
Tcl
set x {1 2 3 1e11} foreach a $x {lappend y [expr {sqrt($a)}]} set fh [open sqrt.dat w] foreach a $x b $y { puts $fh [format "%.*g\t%.*g" $xprecision $a $yprecision $b] } close $fh   set fh [open sqrt.dat] puts [read $fh [file size sqrt.dat]] close $fh
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#VBA
VBA
Public Sub main() x = [{1, 2, 3, 1e11}] y = [{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}] Dim TextFile As Integer TextFile = FreeFile Open "filename" For Output As TextFile For i = 1 To UBound(x) Print #TextFile, Format(x(i), "0.000E-000"), Format(y(i), "0.00000E-000") Next i Close TextFile End Sub
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   True = Rexx(1 == 1) False = Rexx(\True)   doors = False   loop i_ = 1 to 100 loop j_ = 1 to 100 if 0 = (j_ // i_) then doors[j_] = \doors[j_] end j_ end i_   loop d_ = 1 to 100 if doors[d_] then state = 'open' else state = 'closed'   say 'Door Nr.' Rexx(d_).right(4) 'is' state end d_
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
#F.23
F#
let divisors n = [1..n/2] |> List.filter (fun x->n % x = 0)   let abundant (n:int) divs = Seq.sum(divs) > n   let rec semiperfect (n:int) (divs:List<int>) = if divs.Length > 0 then let h = divs.Head let t = divs.Tail if n < h then semiperfect n t else n = h || (semiperfect (n - h) t) || (semiperfect n t) else false   let weird n = let d = divisors n if abundant n d then not(semiperfect n d) else false   [<EntryPoint>] let main _ = let mutable i = 1 let mutable count = 0 while (count < 25) do if (weird i) then count <- count + 1 printf "%d -> %d\n" count i i <- i + 1   0 // return an integer exit 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
#Lasso
Lasso
local(lasso = " --------------------------------------------------------------- | ,--, | | ,---.'| ,----.. | | | | : ,---, .--.--. .--.--. / / \\ | | :  : | ' .' \\ / / '. / / '. / .  : | | | ' : /  ; '. |  : /`. /|  : /`. / . /  ;. \\ | | ;  ; '  :  : \\ ; | |--` ; | |--` .  ; / ` ; | | ' | |__ : | /\\ \\|  :  ;_ |  :  ;_  ; |  ; \\ ; | | | | | :.'||  : ' ;.  :\\ \\ `. \\ \\ `. |  : | ; | ' | | '  :  ;| |  ;/ \\ \\`----. \\ `----. \\. | ' ' ' : | | | | ./ '  : | \\ \\ ,'__ \\ \\ | __ \\ \\ |'  ; \\; / | | | ;  : ; | | ' '--' / /`--' // /`--' / \\ \\ ', / | | | ,/ |  :  : '--'. /'--'. /  ;  : / | | '---' | | ,' `--'---' `--'---' \\ \\ .' | | `--'' `---` | ---------------------------------------------------------------- ")   stdoutnl(#lasso)
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
#Lua
Lua
io.write(" /$$\n") io.write("| $$\n") io.write("| $$ /$$ /$$ /$$$$$$\n") io.write("| $$ | $$ | $$ |____ $$\n") io.write("| $$ | $$ | $$ /$$$$$$$\n") io.write("| $$ | $$ | $$ /$$__ $$\n") io.write("| $$$$$$$$| $$$$$$/| $$$$$$$\n") io.write("|________/ \______/ \_______/\n")
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#AutoHotkey
AutoHotkey
UrlDownloadToFile, http://tycho.usno.navy.mil/cgi-bin/timer.pl, time.html FileRead, timefile, time.html pos := InStr(timefile, "UTC") msgbox % time := SubStr(timefile, pos - 9, 8)
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#AWK
AWK
SYS "LoadLibrary", "URLMON.DLL" TO urlmon% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF% SYS "LoadLibrary", "WININET.DLL" TO wininet% SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%   url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" file$ = @tmp$+"navytime.txt"   SYS DUCE%, url$ SYS UDTF%, 0, url$, file$, 0, 0 TO result% IF result% ERROR 100, "Download failed"   file% = OPENIN(file$) REPEAT text$ = GET$#file% IF INSTR(text$, "UTC") PRINT MID$(text$, 5) UNTIL EOF#file% CLOSE #file%
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Python
Python
  from tkinter import * import tkinter.messagebox   def maximise(): """get screenwidth and screenheight, and resize window to that size. Also move to 0,0""" root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))   def minimise(): """Iconify window to the taskbar. When reopened, the window is unfortunately restored to its original state, NOT its most recent state.""" root.iconify()   def delete(): """create a modal dialog. If answer is "OK", quit the program""" if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"): root.quit()   root = Tk()   mx=Button(root,text="maximise",command=maximise) mx.grid() mx.bind(maximise)   mn=Button(root,text="minimise",command=minimise) mn.grid() mn.bind(minimise)   #catch exit events, including "X" on title bar. root.protocol("WM_DELETE_WINDOW",delete)   mainloop()  
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
#BASIC
BASIC
  OPTION _EXPLICIT   ' SUBs and FUNCTIONs DECLARE SUB CountWords (FromString AS STRING) DECLARE SUB QuickSort (lLeftN AS LONG, lRightN AS LONG, iMode AS INTEGER) DECLARE SUB ShowResults () DECLARE SUB ShowCompletion () DECLARE SUB TopCounted () DECLARE FUNCTION InsertWord& (WhichWord AS STRING) DECLARE FUNCTION BinarySearch& (LookFor AS STRING, RetPos AS INTEGER) DECLARE FUNCTION CleanWord$ (WhichWord AS STRING)   ' Var DIM iFile AS INTEGER DIM iCol AS INTEGER DIM iFil AS INTEGER DIM iStep AS INTEGER DIM iBar AS INTEGER DIM iBlock AS INTEGER DIM lIni AS LONG DIM lEnd AS LONG DIM lLines AS LONG DIM lLine AS LONG DIM lLenF AS LONG DIM iRuns AS INTEGER DIM lMaxWords AS LONG DIM sTimer AS SINGLE DIM strFile AS STRING DIM strKey AS STRING DIM strText AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strBar AS STRING DIM lWords AS LONG DIM strWords AS STRING CONST AddWords = 100 CONST TopCount = 10 CONST FALSE = 0, TRUE = NOT FALSE   ' Initialize iFile = FREEFILE lIni = 1 strDate = DATE$ strTime = TIME$ lEnd = 0 lMaxWords = 1000 REDIM strWords(lIni TO lMaxWords) AS STRING REDIM lWords(lIni TO lMaxWords) AS LONG REDIM lTopWords(1) AS LONG REDIM strTopWords(1) AS STRING   ' ---Main program loop $RESIZE:SMOOTH DO DO CLS PRINT "This program will count how many words are in a text file and shows the 10" PRINT "most used of them." PRINT INPUT "Document to open (TXT file) (f=see files): ", strFile IF UCASE$(strFile) = "F" THEN strFile = "" FILES DO: LOOP UNTIL INKEY$ <> "" END IF LOOP UNTIL strFile <> "" OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN iRuns = iRuns + 1 CLOSE #iFile   ' Opens the document file to analyze it sTimer = TIMER ON TIMER(1) GOSUB ShowAdvance OPEN strFile FOR INPUT AS #iFile lLenF = LOF(iFile) PRINT "Looking for words in "; strFile; ". File size:"; STR$(lLenF); ". ";: iCol = POS(0): PRINT "Initializing"; COLOR 23: PRINT "...";: COLOR 7   ' Count how many lines has the file lLines = 0 DO WHILE NOT EOF(iFile) LINE INPUT #iFile, strText lLines = lLines + 1 LOOP CLOSE #iFile   ' Shows the bar LOCATE , iCol: PRINT "Initialization complete." PRINT PRINT "Processing"; lLines; "lines";: COLOR 23: PRINT "...": COLOR 7 iFil = CSRLIN iCol = POS(0) iBar = 80 iBlock = 80 / lLines IF iBlock = 0 THEN iBlock = 1 PRINT STRING$(iBar, 176) lLine = 0 iStep = lLines * iBlock / iBar IF iStep = 0 THEN iStep = 1 IF iStep > 20 THEN TIMER ON END IF OPEN strFile FOR INPUT AS #iFile DO WHILE NOT EOF(iFile) lLine = lLine + 1 IF (lLine MOD iStep) = 0 THEN strBar = STRING$(iBlock * (lLine / iStep), 219) LOCATE iFil, 1 PRINT strBar ShowCompletion END IF LINE INPUT #iFile, strText CountWords strText strKey = INKEY$ LOOP ShowCompletion CLOSE #iFile TIMER OFF LOCATE iFil - 1, 1 PRINT "Done!" + SPACE$(70) strBar = STRING$(iBar, 219) LOCATE iFil, 1 PRINT strBar LOCATE iFil + 5, 1 PRINT "Finishing";: COLOR 23: PRINT "...";: COLOR 7 ShowResults   ' Frees the RAM lMaxWords = 1000 lEnd = 0 REDIM strWords(lIni TO lMaxWords) AS STRING REDIM lWords(lIni TO lMaxWords) AS LONG   ELSE CLOSE #iFile KILL strFile PRINT PRINT "Document does not exist." END IF PRINT PRINT "Try again? (Y/n)" DO strKey = UCASE$(INKEY$) LOOP UNTIL strKey = "Y" OR strKey = "N" OR strKey = CHR$(13) OR strKey = CHR$(27) LOOP UNTIL strKey = "N" OR strKey = CHR$(27) OR iRuns >= 99   CLS IF iRuns >= 99 THEN PRINT "Maximum runs reached for this session." END IF   PRINT "End of program" PRINT "Start date/time: "; strDate; " "; strTime PRINT "End date/time..: "; DATE$; " "; TIME$ END ' ---End main program   ShowAdvance: ShowCompletion RETURN   FUNCTION BinarySearch& (LookFor AS STRING, RetPos AS INTEGER) ' Var DIM lFound AS LONG DIM lLow AS LONG DIM lHigh AS LONG DIM lMid AS LONG DIM strLookFor AS STRING SHARED lIni AS LONG SHARED lEnd AS LONG SHARED lMaxWords AS LONG SHARED strWords() AS STRING SHARED lWords() AS LONG   ' Binary search for stated word in the list lLow = lIni lHigh = lEnd lFound = 0 strLookFor = UCASE$(LookFor) DO WHILE (lFound < 1) AND (lLow <= lHigh) lMid = (lHigh + lLow) / 2 IF strWords(lMid) = strLookFor THEN lFound = lMid ELSEIF strWords(lMid) > strLookFor THEN lHigh = lMid - 1 ELSE lLow = lMid + 1 END IF LOOP   ' Should I return the position if not found? IF lFound = 0 AND RetPos THEN IF lEnd < 1 THEN lFound = 1 ELSEIF strWords(lMid) > strLookFor THEN lFound = lMid ELSE lFound = lMid + 1 END IF END IF   ' Return the value BinarySearch = lFound   END FUNCTION   FUNCTION CleanWord$ (WhichWord AS STRING) ' Var DIM iSeek AS INTEGER DIM iStep AS INTEGER DIM bOK AS INTEGER DIM strWord AS STRING DIM strChar AS STRING   strWord = WhichWord   ' Look for trailing wrong characters strWord = LTRIM$(RTRIM$(strWord)) IF LEN(strWord) > 0 THEN iStep = 0 DO ' Determines if step will be forward or backwards IF iStep = 0 THEN iStep = -1 ELSE iStep = 1 END IF   ' Sets the initial value of iSeek IF iStep = -1 THEN iSeek = LEN(strWord) ELSE iSeek = 1 END IF   bOK = FALSE DO strChar = MID$(strWord, iSeek, 1) SELECT CASE strChar CASE "A" TO "Z" bOK = TRUE CASE CHR$(129) TO CHR$(154) bOK = TRUE CASE CHR$(160) TO CHR$(165) bOK = TRUE END SELECT   ' If it is not a character valid as a letter, please move one space IF NOT bOK THEN iSeek = iSeek + iStep END IF   ' If no letter was recognized, then exit the loop IF iSeek < 1 OR iSeek > LEN(strWord) THEN bOK = TRUE END IF LOOP UNTIL bOK   IF iStep = -1 THEN ' Reviews if a word was encountered IF iSeek > 0 THEN strWord = LEFT$(strWord, iSeek) ELSE strWord = "" END IF ELSEIF iStep = 1 THEN IF iSeek <= LEN(strWord) THEN strWord = MID$(strWord, iSeek) ELSE strWord = "" END IF END IF LOOP UNTIL iStep = 1 OR strWord = "" END IF   ' Return the result CleanWord = strWord   END FUNCTION   SUB CountWords (FromString AS STRING) ' Var DIM iStart AS INTEGER DIM iLenW AS INTEGER DIM iLenS AS INTEGER DIM iLenD AS INTEGER DIM strString AS STRING DIM strWord AS STRING DIM lWhichWord AS LONG SHARED lEnd AS LONG SHARED lMaxWords AS LONG SHARED strWords() AS STRING SHARED lWords() AS LONG   ' Converts to Upper Case and cleans leading and trailing spaces strString = UCASE$(FromString) strString = LTRIM$(RTRIM$(strString))   ' Get words from string iStart = 1 iLenW = 0 iLenS = LEN(strString) DO WHILE iStart <= iLenS iLenW = INSTR(iStart, strString, " ") IF iLenW = 0 AND iStart <= iLenS THEN iLenW = iLenS + 1 END IF strWord = MID$(strString, iStart, iLenW - iStart)   ' Will remove mid dashes or apostrophe or "â€" iLenD = INSTR(strWord, "-") IF iLenD < 1 THEN iLenD = INSTR(strWord, "'") IF iLenD < 1 THEN iLenD = INSTR(strWord, "â€") END IF END IF IF iLenD >= 2 THEN strWord = LEFT$(strWord, iLenD - 1) iLenW = iStart + (iLenD - 1) END IF strWord = CleanWord(strWord)   IF strWord <> "" THEN ' Look for the word to be counted lWhichWord = BinarySearch(strWord, FALSE)   ' If the word doesn't exist in the list, add it IF lWhichWord = 0 THEN lWhichWord = InsertWord(strWord) END IF   ' Count the word IF lWhichWord > 0 THEN lWords(lWhichWord) = lWords(lWhichWord) + 1 END IF END IF iStart = iLenW + 1 LOOP   END SUB   ' Here a word will be inserted in the list FUNCTION InsertWord& (WhichWord AS STRING) ' Var DIM lFound AS LONG DIM lWord AS LONG DIM strWord AS STRING SHARED lIni AS LONG SHARED lEnd AS LONG SHARED lMaxWords AS LONG SHARED strWords() AS STRING SHARED lWords() AS LONG   ' Look for the word in the list strWord = UCASE$(WhichWord) lFound = BinarySearch(WhichWord, TRUE) IF lFound > 0 THEN ' Add one word lEnd = lEnd + 1   ' Verifies if there is still room for a new word IF lEnd > lMaxWords THEN lMaxWords = lMaxWords + AddWords ' Other words IF lMaxWords > 32767 THEN IF lEnd <= 32767 THEN lMaxWords = 32767 ELSE lFound = -1 END IF END IF   IF lFound > 0 THEN REDIM _PRESERVE strWords(lIni TO lMaxWords) AS STRING REDIM _PRESERVE lWords(lIni TO lMaxWords) AS LONG END IF END IF   IF lFound > 0 THEN ' Move the words below this IF lEnd > 1 THEN FOR lWord = lEnd TO lFound + 1 STEP -1 strWords(lWord) = strWords(lWord - 1) lWords(lWord) = lWords(lWord - 1) NEXT lWord END IF   ' Insert the word in the position strWords(lFound) = strWord lWords(lFound) = 0 END IF END IF   InsertWord = lFound END FUNCTION   SUB QuickSort (lLeftN AS LONG, lRightN AS LONG, iMode AS INTEGER) ' Var DIM lPivot AS LONG DIM lLeftNIdx AS LONG DIM lRightNIdx AS LONG SHARED lWords() AS LONG SHARED strWords() AS STRING   ' Clasifies from highest to lowest lLeftNIdx = lLeftN lRightNIdx = lRightN IF (lRightN - lLeftN) > 0 THEN lPivot = (lLeftN + lRightN) / 2 DO WHILE (lLeftNIdx <= lPivot) AND (lRightNIdx >= lPivot) IF iMode = 0 THEN ' Ascending DO WHILE (lWords(lLeftNIdx) < lWords(lPivot)) AND (lLeftNIdx <= lPivot) lLeftNIdx = lLeftNIdx + 1 LOOP DO WHILE (lWords(lRightNIdx) > lWords(lPivot)) AND (lRightNIdx >= lPivot) lRightNIdx = lRightNIdx - 1 LOOP ELSE ' Descending DO WHILE (lWords(lLeftNIdx) > lWords(lPivot)) AND (lLeftNIdx <= lPivot) lLeftNIdx = lLeftNIdx + 1 LOOP DO WHILE (lWords(lRightNIdx) < lWords(lPivot)) AND (lRightNIdx >= lPivot) lRightNIdx = lRightNIdx - 1 LOOP END IF SWAP lWords(lLeftNIdx), lWords(lRightNIdx) SWAP strWords(lLeftNIdx), strWords(lRightNIdx) lLeftNIdx = lLeftNIdx + 1 lRightNIdx = lRightNIdx - 1 IF (lLeftNIdx - 1) = lPivot THEN lRightNIdx = lRightNIdx + 1 lPivot = lRightNIdx ELSEIF (lRightNIdx + 1) = lPivot THEN lLeftNIdx = lLeftNIdx - 1 lPivot = lLeftNIdx END IF LOOP QuickSort lLeftN, lPivot - 1, iMode QuickSort lPivot + 1, lRightN, iMode END IF END SUB   SUB ShowCompletion () ' Var SHARED iFil AS INTEGER SHARED lLine AS LONG SHARED lLines AS LONG SHARED lEnd AS LONG   LOCATE iFil + 1, 1 PRINT "Lines analyzed :"; lLine PRINT USING "% of completion: ###%"; (lLine / lLines) * 100 PRINT "Words found....:"; lEnd END SUB   SUB ShowResults () ' Var DIM iMaxL AS INTEGER DIM iMaxW AS INTEGER DIM lWord AS LONG DIM lHowManyWords AS LONG DIM strString AS STRING DIM strFileR AS STRING SHARED lIni AS LONG SHARED lEnd AS LONG SHARED lLenF AS LONG SHARED lMaxWords AS LONG SHARED sTimer AS SINGLE SHARED strFile AS STRING SHARED strWords() AS STRING SHARED lWords() AS LONG SHARED strTopWords() AS STRING SHARED lTopWords() AS LONG SHARED iRuns AS INTEGER   ' Show results   ' Creates file name lWord = INSTR(strFile, ".") IF lWord = 0 THEN lWord = LEN(strFile) strFileR = LEFT$(strFile, lWord) IF RIGHT$(strFileR, 1) <> "." THEN strFileR = strFileR + "."   ' Retrieves the longest word found and the highest count FOR lWord = lIni TO lEnd ' Gets the longest word found IF LEN(strWords(lWord)) > iMaxL THEN iMaxL = LEN(strWords(lWord)) END IF   lHowManyWords = lHowManyWords + lWords(lWord) NEXT lWord IF iMaxL > 60 THEN iMaxW = 60 ELSE iMaxW = iMaxL   ' Gets top counted TopCounted   ' Shows the results CLS PRINT "File analyzed : "; strFile PRINT "Length of file:"; lLenF PRINT "Time lapse....:"; TIMER - sTimer;"seconds" PRINT "Words found...:"; lHowManyWords; "(Unique:"; STR$(lEnd); ")" PRINT "Longest word..:"; iMaxL PRINT PRINT "The"; TopCount; "most used are:" PRINT STRING$(iMaxW, "-"); "+"; STRING$(80 - (iMaxW + 1), "-") PRINT " Word"; SPACE$(iMaxW - 5); "| Count" PRINT STRING$(iMaxW, "-"); "+"; STRING$(80 - (iMaxW + 1), "-") strString = "\" + SPACE$(iMaxW - 2) + "\| #########," FOR lWord = lIni TO TopCount PRINT USING strString; strTopWords(lWord); lTopWords(lWord) NEXT lWord PRINT STRING$(iMaxW, "-"); "+"; STRING$(80 - (iMaxW + 1), "-") PRINT "See files "; strFileR + "S" + LTRIM$(STR$(iRuns)); " and "; strFileR + "C" + LTRIM$(STR$(iRuns)); " to see the full list." END SUB   SUB TopCounted () ' Var DIM lWord AS LONG DIM strFileR AS STRING DIM iFile AS INTEGER CONST Descending = 1 SHARED lIni AS LONG SHARED lEnd AS LONG SHARED lMaxWords AS LONG SHARED strWords() AS STRING SHARED lWords() AS LONG SHARED strTopWords() AS STRING SHARED lTopWords() AS LONG SHARED iRuns AS INTEGER SHARED strFile AS STRING   ' Assigns new dimmentions REDIM strTopWords(lIni TO TopCount) AS STRING REDIM lTopWords(lIni TO TopCount) AS LONG   ' Saves the current values lWord = INSTR(strFile, ".") IF lWord = 0 THEN lWord = LEN(strFile) strFileR = LEFT$(strFile, lWord) IF RIGHT$(strFileR, 1) <> "." THEN strFileR = strFileR + "." iFile = FREEFILE OPEN strFileR + "S" + LTRIM$(STR$(iRuns)) FOR OUTPUT AS #iFile FOR lWord = lIni TO lEnd WRITE #iFile, strWords(lWord), lWords(lWord) NEXT lWord CLOSE #iFile   ' Classifies the counted in descending order QuickSort lIni, lEnd, Descending   ' Now, saves the required values in the arrays FOR lWord = lIni TO TopCount strTopWords(lWord) = strWords(lWord) lTopWords(lWord) = lWords(lWord) NEXT lWord   ' Now, saves the order from the file OPEN strFileR + "C" + LTRIM$(STR$(iRuns)) FOR OUTPUT AS #iFile FOR lWord = lIni TO lEnd WRITE #iFile, strWords(lWord), lWords(lWord) NEXT lWord CLOSE #iFile   END SUB  
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.
#D
D
import std.stdio, std.algorithm;   void wireworldStep(char[][] W1, char[][] W2) pure nothrow @safe @nogc { foreach (immutable r; 1 .. W1.length - 1) foreach (immutable c; 1 .. W1[0].length - 1) switch (W1[r][c]) { case 'H': W2[r][c] = 't'; break; case 't': W2[r][c] = '.'; break; case '.': int nH = 0; foreach (sr; -1 .. 2) foreach (sc; -1 .. 2) nH += W1[r + sr][c + sc] == 'H'; W2[r][c] = (nH == 1 || nH == 2) ? 'H' : '.'; break; default: } }   void main() { auto world = [" ".dup, " tH ".dup, " . .... ".dup, " .. ".dup, " ".dup];   char[][] world2; foreach (row; world) world2 ~= row.dup;   foreach (immutable step; 0 .. 7) { writefln("\nStep %d: ------------", step); foreach (row; world[1 .. $ - 1]) row[1 .. $ - 1].writeln; wireworldStep(world, world2); swap(world, world2); } }
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Perl
Perl
use feature 'say'; use ntheory qw(is_prime powmod);   say 'Wieferich primes less than 5000: ' . join ', ', grep { is_prime($_) and powmod(2, $_-1, $_*$_) == 1 } 1..5000;