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/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.
#ALGOL_68
ALGOL 68
CO Wireworld implementation. CO   PROC exception = ([]STRING args)VOID:( putf(stand error, ($"Exception"$, $", "g$, args, $l$)); stop );   PROC assertion error = (STRING message)VOID:exception(("assertion error", message));   MODE CELL = CHAR; MODE WORLD = FLEX[0, 0]CELL; CELL head="H", tail="t", conductor=".", empty = " "; STRING all states := empty;   BOOL wrap = FALSE; # is the world round? #   STRING nl := REPR 10;   STRING in string := "tH........."+nl+ ". ."+nl+ " ..."+nl+ ". ."+nl+ "Ht.. ......"+nl ;   OP +:= = (REF FLEX[]FLEX[]CELL lines, FLEX[]CELL line)VOID:( [UPB lines + 1]FLEX[0]CELL new lines; new lines[:UPB lines]:=lines; lines := new lines; lines[UPB lines]:=line );   PROC read file = (REF FILE in file)WORLD: ( # file > initial world configuration" # FLEX[0]CELL line; FLEX[0]FLEX[0]CELL lines; INT upb x:=0, upb y := 0; BEGIN # on physical file end(in file, exit read line); # make term(in file, nl); FOR x TO 5 DO get(in file, (line, new line)); upb x := x; IF UPB line > upb y THEN upb y := UPB line FI; lines +:= line OD; exit read line: SKIP END; [upb x, upb y]CELL out; FOR x TO UPB out DO out[x,]:=lines[x]+" "*(upb y-UPB lines[x]) OD; out );   PROC new cell = (WORLD current world, INT x, y)CELL: ( CELL istate := current world[x, y]; IF INT pos; char in string (istate, pos, all states); pos IS REF INT(NIL) THEN assertion error("Wireworld cell set to unknown value "+istate) FI; IF istate = head THEN tail ELIF istate = tail THEN conductor ELIF istate = empty THEN empty ELSE # istate = conductor # [][]INT dxy list = ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ); INT n := 0; FOR enum dxy TO UPB dxy list DO []INT dxy = dxy list[enum dxy]; IF wrap THEN INT px = ( x + dxy[1] - 1 ) MOD 1 UPB current world + 1; INT py = ( y + dxy[2] - 1 ) MOD 2 UPB current world + 1; n +:= ABS (current world[px, py] = head) ELSE INT px = x + dxy[1]; INT py = y + dxy[2]; IF px >= 1 LWB current world AND px <= 1 UPB current world AND py >= 2 LWB current world AND py <= 2 UPB current world THEN n +:= ABS (current world[px, py] = head) FI FI OD; IF 1 <= n AND n <= 2 THEN head ELSE conductor FI FI );   PROC next gen = (WORLD world)WORLD:( # compute next generation of wireworld # WORLD new world := world; FOR x TO 1 UPB world DO FOR y TO 2 UPB world DO new world[x,y] := new cell(world, x, y) OD OD; new world );   PROC world2string = (WORLD world) STRING:( STRING out:=""; FOR x TO UPB world DO out +:= world[x,]+nl OD; out );   FILE in file; associate(in file, in string);   WORLD ww := read file(in file); close(in file);   FOR gen TO 10 DO printf ( ($lg(-3)" "$, gen-1, $g$,"="* (2 UPB ww-4), $l$)); print ( world2string(ww) ); ww := next gen(ww) OD
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
#BASIC
BASIC
print "Wieferich primes less than 5000: " for i = 1 to 5000 if isWeiferich(i) then print i next i end   function isWeiferich(p) if not isPrime(p) then return False q = 1 p2 = p ^ 2 while p > 1 q = (2 * q) mod p2 p -= 1 end while if q = 1 then return True else return False end function   function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v mod d = 0 then return False else d += 2 end while return True end function
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
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdint.h>   #define LIMIT 5000 static bool PRIMES[LIMIT];   static void prime_sieve() { uint64_t p; int i;   PRIMES[0] = false; PRIMES[1] = false; for (i = 2; i < LIMIT; i++) { PRIMES[i] = true; }   for (i = 4; i < LIMIT; i += 2) { PRIMES[i] = false; }   for (p = 3;; p += 2) { uint64_t q = p * p; if (q >= LIMIT) { break; } if (PRIMES[p]) { uint64_t inc = 2 * p; for (; q < LIMIT; q += inc) { PRIMES[q] = false; } } } }   uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { uint64_t result = 1;   if (mod == 1) { return 0; }   base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) { result = (result * base) % mod; } base = (base * base) % mod; } return result; }   void wieferich_primes() { uint64_t p;   for (p = 2; p < LIMIT; ++p) { if (PRIMES[p] && modpow(2, p - 1, p * p) == 1) { printf("%lld\n", p); } } }   int main() { prime_sieve();   printf("Wieferich primes less than %d:\n", LIMIT); wieferich_primes();   return 0; }
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.
#Forth
Forth
  warnings off require xlib.fs   0 value X11-D \ Display 0 value X11-S \ Screen 0 value X11-root 0 value X11-GC 0 value X11-W \ Window 0 value X11-Black 0 value X11-White 9 value X11-Top 0 value X11-Left create X11-ev 96 allot   variable wm_delete   : X11-D-S X11-D X11-S ; : X11-D-G X11-D X11-GC ; : X11-D-W X11-D X11-W ; : X11-D-W-G X11-D-W X11-GC ;   : open-X11 ( -- ) X11-D 0= if 0 XOpendisplay to X11-D X11-D 0= abort" can't connect to X server" X11-D XDefaultscreen to X11-S X11-D-S XRootwindow to X11-root X11-D-S XDefaultGC to X11-GC X11-D-S XBlackPixel to X11-Black X11-D-S XWhitePixel to X11-White then X11-W 0= if X11-D X11-root X11-top X11-left 400 220 0 0 $808080 XCreateSimplewindow to X11-W X11-W 0= abort" failed to create X11-window" X11-D-W $28043 XSelectInput drop X11-D s" WM_DELETE_WEINDOW" 1 XInternAtom wm_delete ! X11-D-W wm_delete 1 XSetWMProtocols drop X11-D-W XMapwindow drop X11-D XFlush drop then ;   : close-graphics ( -- ) X11-W if X11-D-W XDestroywindow drop 0 to X11-W then X11-D if X11-D XClosedisplay 0 to X11-D then ;   : foreground >r X11-D-G r> XSetForeground drop ; : background >r X11-D-G r> XSetBackground drop ; : keysym X11-ev 0 XLookupKeysym ;   : ev-loop begin X11-D X11-ev XNextEvent throw X11-White foreground X11-Black background X11-D-W-G 100 100 s" Hello World" XDrawString drop X11-D-W-G 100 120 150 25 XDrawRectangle drop X11-D-W-G 110 135 s" Press ESC to exit ..." XDrawString drop case X11-ev @ $ffffffff and 3 of keysym XK_Escape = if exit then endof endcase again ; \ #### Test ##### 0 open-X11 ev-loop close-graphics bye  
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.
#Go
Go
package main   // Copyright (c) 2013 Alex Kesling // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE.   import ( "log" "github.com/jezek/xgb" "github.com/jezek/xgb/xproto" )   func main() { // Open the connection to the X server X, err := xgb.NewConn() if err != nil { log.Fatal(err) }   // geometric objects points := []xproto.Point{ {10, 10}, {10, 20}, {20, 10}, {20, 20}};   polyline := []xproto.Point{ {50, 10}, { 5, 20}, // rest of points are relative {25,-20}, {10, 10}};   segments := []xproto.Segment{ {100, 10, 140, 30}, {110, 25, 130, 60}};   rectangles := []xproto.Rectangle{ { 10, 50, 40, 20}, { 80, 50, 10, 40}};   arcs := []xproto.Arc{ {10, 100, 60, 40, 0, 90 << 6}, {90, 100, 55, 40, 0, 270 << 6}};   setup := xproto.Setup(X) // Get the first screen screen := setup.DefaultScreen(X)   // Create black (foreground) graphic context foreground, _ := xproto.NewGcontextId(X) mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures) values := []uint32{screen.BlackPixel, 0} xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)   // Ask for our window's Id win, _ := xproto.NewWindowId(X) winDrawable := xproto.Drawable(win)   // Create the window mask = uint32(xproto.CwBackPixel | xproto.CwEventMask) values = []uint32{screen.WhitePixel, xproto.EventMaskExposure} xproto.CreateWindow(X, // Connection screen.RootDepth, // Depth win, // Window Id screen.Root, // Parent Window 0, 0, // x, y 150, 150, // width, height 10, // border_width xproto.WindowClassInputOutput, // class screen.RootVisual, // visual mask, values) // masks   // Map the window on the screen xproto.MapWindow(X, win)   for { evt, err := X.WaitForEvent() switch evt.(type) { case xproto.ExposeEvent: /* We draw the points */ xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)   /* We draw the polygonal line */ xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)   /* We draw the segments */ xproto.PolySegment(X, winDrawable, foreground, segments)   /* We draw the rectangles */ xproto.PolyRectangle(X, winDrawable, foreground, rectangles)   /* We draw the arcs */ xproto.PolyArc(X, winDrawable, foreground, arcs)   default: /* Unknown event type, ignore it */ }   if err != nil { log.Fatal(err) } } return }
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
#Java
Java
import java.math.BigInteger; import java.util.*;   public class WilsonPrimes { public static void main(String[] args) { final int limit = 11000; BigInteger[] f = new BigInteger[limit]; f[0] = BigInteger.ONE; BigInteger factorial = BigInteger.ONE; for (int i = 1; i < limit; ++i) { factorial = factorial.multiply(BigInteger.valueOf(i)); f[i] = factorial; } List<Integer> primes = generatePrimes(limit); System.out.printf(" n | Wilson primes\n--------------------\n"); BigInteger s = BigInteger.valueOf(-1); for (int n = 1; n <= 11; ++n) { System.out.printf("%2d |", n); for (int p : primes) { if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s) .mod(BigInteger.valueOf(p * p)) .equals(BigInteger.ZERO)) System.out.printf(" %d", p); } s = s.negate(); System.out.println(); } }   private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
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.
#BASIC256
BASIC256
clg text (50,50, "I write in the graphics area")
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB2" dlg% = FN_newdialog("GUI Window", 0, 0, 200, 150, 8, 1000) PROC_showdialog(dlg%)
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
#Nim
Nim
import random, sequtils, strformat, strutils   const   Dirs = [[1, 0], [ 0, 1], [ 1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]   NRows = 10 NCols = 10 GridSize = NRows * NCols MinWords = 25   type Grid = ref object numAttempts: Natural cells: array[NRows, array[NCols, char]] solutions: seq[string]   proc readWords(filename: string): seq[string] =   const MaxLen = max(NRows, NCols)   for word in filename.lines(): if word.len in 3..MaxLen: if word.allCharsInSet(Letters): result.add word.toLowerAscii     proc placeMessage(grid: var Grid; msg: string): int = let msg = msg.map(toUpperAscii).filter(isUpperAscii).join() if msg.len in 1..<GridSize: let gapSize = GridSize div msg.len for i in 0..msg.high: let pos = i * gapSize + rand(gapSize - 1) grid.cells[pos div NCols][pos mod NCols] = msg[i] result = msg.len     proc tryLocation(grid: var Grid; word: string; dir, pos: Natural): int = let row = pos div NCols let col = pos mod NCols let length = word.len   # Check bounds. if (Dirs[dir][0] == 1 and (length + col) > NCols) or (Dirs[dir][0] == -1 and (length - 1) > col) or (Dirs[dir][1] == 1 and (length + row) > NRows) or (Dirs[dir][1] == -1 and (length - 1) > row): return 0   # Check cells. var r = row var c = col for ch in word: if grid.cells[r][c] != '\0' and grid.cells[r][c] != ch: return 0 c += Dirs[dir][0] r += Dirs[dir][1]   # Place. r = row c = col var overlaps = 0 for i, ch in word: if grid.cells[r][c] == ch: inc overlaps else: grid.cells[r][c] = ch if i < word.high: c += Dirs[dir][0] r += Dirs[dir][1]   let lettersPlaced = length - overlaps if lettersPlaced > 0: grid.solutions.add &"{word:<10} ({col}, {row}) ({c}, {r})"   result = lettersPlaced     proc tryPlaceWord(grid: var Grid; word: string): int = let randDir = rand(Dirs.high) let randPos = rand(GridSize - 1)   for dir in 0..Dirs.high: let dir = (dir + randDir) mod Dirs.len for pos in 0..<GridSize: let pos = (pos + randPos) mod GridSize let lettersPlaced = grid.tryLocation(word, dir, pos) if lettersPlaced > 0: return lettersPlaced     proc initGrid(words: seq[string]): Grid = var words = words for numAttempts in 1..100: words.shuffle() new(result) let messageLen = result.placeMessage("Rosetta Code") let target = GridSize - messageLen   var cellsFilled = 0 for word in words: cellsFilled += result.tryPlaceWord(word) if cellsFilled == target: if result.solutions.len >= MinWords: result.numAttempts = numAttempts return # Grid is full but we didn't pack enough words: start over. break   proc printResult(grid: Grid) = if grid.isNil or grid.numAttempts == 0: echo "No grid to display." return   let size = grid.solutions.len echo "Attempts: ", grid.numAttempts echo "Number of words: ", size   echo "\n 0 1 2 3 4 5 6 7 8 9\n" for r in 0..<NRows: echo &"{r} ", grid.cells[r].join(" ") echo()   for i in countup(0, size - 2, 2): echo grid.solutions[i], " ", grid.solutions[i + 1] if (size and 1) == 1: echo grid.solutions[^1]     randomize() let grid = initGrid("unixdict.txt".readWords()) grid.printResult()
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
#Perl
Perl
#!/usr/bin/perl   use strict; # http://www.rosettacode.org/wiki/Word_search use warnings; use Path::Tiny; use List::Util qw( shuffle );   my $size = 10; my $s1 = $size + 1; $_ = <<END; .....R.... ......O... .......S.. ........E. T........T .A........ ..C....... ...O...... ....D..... .....E.... END   my @words = shuffle path('/usr/share/dict/words')->slurp =~ /^[a-z]{3,7}$/gm; my @played; my %used;   for my $word ( (@words) x 5 ) { my ($pat, $start, $end, $mask, $nulls) = find( $word ); defined $pat or next; $used{$word}++ and next; # only use words once $nulls //= ''; my $expand = $word =~ s/\B/$nulls/gr; my $pos = $start; if( $start > $end ) { $pos = $end; $expand = reverse $expand; } substr $_, $pos, length $mask, (substr( $_, $pos, length $mask ) & ~ "$mask") | "$expand"; push @played, join ' ', $word, $start, $end; tr/.// > 0 or last; }   print " 0 1 2 3 4 5 6 7 8 9\n\n"; my $row = 0; print s/(?<=.)(?=.)/ /gr =~ s/^/ $row++ . ' ' /gemr; print "\nNumber of words: ", @played . "\n\n"; my @where = map { my ($word, $start, $end) = split; sprintf "%11s %s", $word, $start < $end ? "(@{[$start % $s1]},@{[int $start / $s1]})->" . "(@{[$end % $s1 - 1]},@{[int $end / $s1]})" : "(@{[$start % $s1 - 1]},@{[int $start / $s1]})->" . "(@{[$end % $s1]},@{[int $end / $s1]})"; } sort @played; print splice(@where, 0, 3), "\n" while @where; tr/.// and die "incomplete";   sub find { my ($word) = @_; my $n = length $word; my $nm1 = $n - 1; my %pats;   for my $space ( 0, $size - 1 .. $size + 1 ) { my $nulls = "\0" x $space; my $mask = "\xff" . ($nulls . "\xff") x $nm1; # vert my $gap = qr/.{$space}/s; while( /(?=(.(?:$gap.){$nm1}))/g ) { my $pat = ($1 & $mask) =~ tr/\0//dr; $pat =~ tr/.// or next; my $pos = "$-[1] $+[1]"; $word =~ /$pat/ or reverse($word) =~ /$pat/ or next; push @{ $pats{$pat} }, "$pos $mask $nulls"; } }   for my $key ( sort keys %pats ) { if( $word =~ /^$key$/ ) { my @all = @{ $pats{$key} }; return $key, split ' ', $all[ rand @all ]; } elsif( (reverse $word) =~ /^$key$/ ) { my @all = @{ $pats{$key} }; my @parts = split ' ', $all[ rand @all ]; return $key, @parts[ 1, 0, 2, 3] } }   return undef; }
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
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <string>   const char *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." };   std::string wrap(const char *text, size_t line_length = 72) { std::istringstream words(text); std::ostringstream wrapped; std::string word;   if (words >> word) { wrapped << word; size_t space_left = line_length - word.length(); while (words >> word) { if (space_left < word.length() + 1) { wrapped << '\n' << word; space_left = line_length - word.length(); } else { wrapped << ' ' << word; space_left -= word.length() + 1; } } } return wrapped.str(); }   int main() { std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n"; std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n"; }
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. 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
lower: procedure; parse arg a; @= 'abcdefghijklmnopqrstuvwxyz'; @u= @; upper @u return translate(a, @, @u)
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. 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
#Ruby
Ruby
require "set"   Words = File.open("unixdict.txt").read.split("\n"). group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }. to_h   def word_ladder(from, to) raise "Length mismatch" unless from.length == to.length sized_words = Words[from.length] work_queue = [[from]] used = Set.new [from] while work_queue.length > 0 new_q = [] work_queue.each do |words| last_word = words[-1] new_tails = Enumerator.new do |enum| ("a".."z").each do |replacement_letter| last_word.length.times do |i| new_word = last_word.clone new_word[i] = replacement_letter next unless sized_words.include? new_word and not used.include? new_word enum.yield new_word used.add new_word return words + [new_word] if new_word == to end end end new_tails.each do |t| new_q.push(words + [t]) end end work_queue = new_q end end   [%w<boy man>, %w<girl lady>, %w<john jane>, %w<child adult>].each do |from, to| if ladder = word_ladder(from, to) puts ladder.join " → " else puts "#{from} into #{to} cannot be done" end end
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
#Pascal
Pascal
  program WordWheel;   {$mode objfpc}{$H+}   uses SysUtils;   const WheelSize = 9; MinLength = 3; WordListFN = 'unixdict.txt';   procedure search(Wheel : string); var Allowed, Required, Available, w : string; Len, i, p : integer; WordFile : TextFile; Match : boolean; begin AssignFile(WordFile, WordListFN); try Reset(WordFile); except writeln('Could not open dictionary file: ' + WordListFN); exit; end; Allowed := LowerCase(Wheel); Required := copy(Allowed, 5, 1); { central letter is required } while not eof(WordFile) do begin readln(WordFile, w); Len := length(w); if (Len < MinLength) or (Len > WheelSize) then continue; if pos(Required, w) = 0 then continue; Available := Allowed; Match := True; for i := 1 to Len do begin p := pos(w[i], Available); if p > 0 then { prevent re-use of letter } delete(Available, p, 1) else begin Match := False; break; end; end; if Match then writeln(w); end; CloseFile(WordFile); end;   { exercise the procedure } begin search('NDE' + 'OKG' + 'ELW'); end.  
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.
#REXX
REXX
/*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */ background= '·' /*background character: a middle-dot. */ image.= background /*fill the array with middle-dots. */ plotC= '░▒▓█' /*characters used for plotting points. */ EoE= 3000 /*EOE = End Of Earth, er, ··· graph. */ do j=-EoE to +EoE /*define the graph: lowest ──► highest.*/ image.j.0= '─' /*define the graph's horizontal axis. */ image.0.j= '│' /* " " " verical " */ end /*j*/ image.0.0= '┼' /*define the graph's axis origin (char)*/ parse arg xi yi xf yf . /*allow specifying the line-end points.*/ if xi=='' | xi=="," then xi= 1 /*Not specified? Then use the default.*/ if yi=='' | yi=="," then yi= 2 /* " " " " " " */ if xf=='' | xf=="," then xf=11 /* " " " " " " */ if yf=='' | yf=="," then yf=12 /* " " " " " " */ minX=0; minY=0 /*use these as the limits for plotting.*/ maxX=0; maxY=0 /* " " " " " " " */ call drawLine xi, yi, xf, yf /*invoke subroutine and graph the line.*/ border=2 /*allow additional space (plot border).*/ minX=minX - border * 2; maxX=maxX + border * 2 /*preserve screen's aspect ratio {*2}.*/ minY=minY - border  ; maxY=maxY + border do y=maxY to minY by -1; $= /*construct a row.*/ do x=minX to maxX; $=$ || image.x.y; end /*x*/ say $ /*display the constructed row to term. */ end /*y*/ /*graph is cropped by the MINs and MAXs*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ drawLine: parse arg x1,y1,x2,y2; switchXY=0; dx=x2-x1 dy=y2-y1 if abs(dx)<abs(dy) then parse value x1 y1 x2 y2 dx dy with y1 x2 y2 x2 dy dx if x2<x1 then parse value x1 x2 y1 y2 1 with x2 x1 y2 y1 switchXY gradient=dy/dx xend=round(x1) /*◄─────────────────1st endpoint.══════════════*/ yend=y1 + gradient * (xend-x1); xgap=1 - fpart(x1 + .5) xpx11=xend; ypx11=floor(yend) intery=yend+gradient call plotXY xpx11, ypx11, brite(1 - fpart(yend*xgap)), switchXY call plotXY xpx11, ypx11+1, brite( fpart(yend*xgap)), switchXY xend=round(x2) /*◄─────────────────2nd endpoint.══════════════*/ yend=y2 + gradient * (xend-x2); xgap= fpart(x2 + .5) xpx12=xend; ypx12=floor(yend) call plotXY xpx12, ypx12 , brite(1 - fpart(yend*xgap)), switchXY call plotXY xpx12, ypx12+1, brite( fpart(yend*xgap)), switchXY   do x=xpx11+1 to xpx12-1 /*◄═════════════════draw the line.═════════════*/  !intery=floor(intery) call plotXY x,  !intery , brite(1 - fpart(intery)), switchXY call plotXY x,  !intery+1, brite( fpart(intery)), switchXY intery=intery + gradient end /*x*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ brite: return substr(background || plotC, 1 + round( abs( arg(1) ) * length(plotC)), 1) floor: parse arg #; _=trunc(#); return _ - (#<0) * (#\=_) fpart: parse arg #; return abs(# - trunc(#) ) round: return format(arg(1), , word(arg(2) 0, 1) ) /*──────────────────────────────────────────────────────────────────────────────────────*/ plotXY: parse arg xx,yy,bc,switchYX; if switchYX then parse arg yy,xx image.xx.yy=bc; minX=min(minX, xx); maxX=max(maxX,xx) minY=min(minY, yy); maxY=max(maxY,yy); return
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.
#HicEst
HicEst
CHARACTER names="April~Tam O'Shanter~Emily~" CHARACTER remarks*200/%Bubbly: I'm > Tam and <= Emily~Burns: "When chapman billies leave the street ..."~Short & shrift~%/ CHARACTER XML*1000   EDIT(Text=remarks, Right='&', RePLaceby='&amp;', DO) EDIT(Text=remarks, Right='>', RePLaceby='&gt;', DO) EDIT(Text=remarks, Right='<', RePLaceby='&lt;', DO)   XML = "<CharacterRemarks>" // $CRLF DO i = 1, 3 EDIT(Text=names, SePaRators='~', ITeM=i, Parse=name) EDIT(Text=remarks, SePaRators='~', ITeM=i, Parse=remark) XML = TRIM(XML) // '<Character name="' // name // '">' // remark // '</Character>' // $CRLF ENDDO XML = TRIM(XML) // "</CharacterRemarks>"
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.
#J
J
tbl=: ('&quote;'; '&amp;'; '&lt;'; '&gt;') (a.i.'"&<>')} <"0 a. esc=: [:; {&tbl@:i.~&a.
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
#HicEst
HicEst
CHARACTER in*1000, out*100   READ(ClipBoard) in EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)
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)
#TXR
TXR
(defvar li (list 1 2 3))  ;; (1 2 3) (defvar ve (vec 1 2 3)) ;; make vector #(1 2 3) ;; (defvar ve (vector 3)) ;; make #(nil nil nil) [ve 0]  ;; yields 1 [li 0]  ;; yields 1 [ve -1]  ;; yields 3 [li 5]  ;; yields nil [li -50]  ;; yields nil [ve 50]  ;; error (set [ve 2] 4) ;; changes vector to #(1 2 4). (set [ve 3] 0) ;; error (set [ve 3] 0) ;; error
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.
#Ring
Ring
  # Project : Write float arrays to a text file   decimals(13) x = [1, 2, 3, 100000000000] y = [1, 1.4142135623730, 1.7320508075688, 316227.76601683] str = list(4) fn = "C:\Ring\calmosoft\output.txt" fp = fopen(fn,"wb") for i = 1 to 4 str[i] = string(x[i]) + " | " + string(y[i]) + windowsnl() fwrite(fp, str[i]) next fclose(fp) fp = fopen("C:\Ring\calmosoft\output.txt","r") r = "" while isstring(r) r = fgetc(fp) if r = char(10) see nl else see r ok end fclose(fp)  
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.
#RLaB
RLaB
  >> x = rand(10,1); y = rand(10,1); >> writem("mytextfile.txt", [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.
#MOO
MOO
is_open = make(100); for pass in [1..100] for door in [pass..100] if (door % pass) continue; endif is_open[door] = !is_open[door]; endfor endfor   "output the result"; for door in [1..100] player:tell("door #", door, " is ", (is_open[door] ? "open" : "closed"), "."); endfor
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#AppleScript
AppleScript
on run take(25, weirds()) -- Gets there, but takes about 6 seconds on this system, -- (logging intermediates through the Messages channel, for the impatient :-) end run     -- weirds :: Gen [Int] on weirds() script property x : 1 property v : 0 on |λ|() repeat until isWeird(x) set x to 1 + x end repeat set v to x log v set x to 1 + x return v end |λ| end script end weirds   -- isWeird :: Int -> Bool on isWeird(n) set ds to descProperDivisors(n) set d to sum(ds) - n 0 < d and not hasSum(d, ds) end isWeird   -- hasSum :: Int -> [Int] -> Bool on hasSum(n, xs) if {} ≠ xs then set h to item 1 of xs set t to rest of xs if n < h then hasSum(n, t) else n = h or hasSum(n - h, t) or hasSum(n, t) end if else false end if end hasSum   -- GENERIC ------------------------------------------------   -- descProperDivisors :: Int -> [Int] on descProperDivisors(n) if n = 1 then {1} else set realRoot to n ^ (1 / 2) set intRoot to realRoot as integer set blnPerfect to intRoot = realRoot   -- isFactor :: Int -> Bool script isFactor on |λ|(x) n mod x = 0 end |λ| end script   -- Factors up to square root of n, set lows to filter(isFactor, enumFromTo(1, intRoot))   -- and cofactors of these beyond the square root,   -- integerQuotient :: Int -> Int script integerQuotient on |λ|(x) (n / x) as integer end |λ| end script   set t to rest of lows if blnPerfect then set xs to t else set xs to lows end if map(integerQuotient, t) & (reverse of xs) end if end descProperDivisors   -- enumFromTo :: (Int, Int) -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat return lst else return {} end if end enumFromTo   -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- sum :: [Num] -> Num on sum(xs) script add on |λ|(a, b) a + b end |λ| end script   foldl(add, 0, xs) end sum   -- take :: Int -> Gen [a] -> [a] on take(n, xs) set ys to {} repeat with i from 1 to n set v to xs's |λ|() if missing value is v then return ys else set end of ys to v end if end repeat return ys end take   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if script is class of f then f else script property |λ| : f end script end if end mReturn
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
#Go
Go
package main   import ( "fmt" "strings" )   var lean = font{ height: 5, slant: 1, spacing: 2, m: map[rune][]string{ 'G': []string{ ` _/_/_/`, `_/ `, `_/ _/_/`, `_/ _/`, ` _/_/_/`, }, 'o': []string{ ` `, ` _/_/ `, `_/ _/`, `_/ _/`, ` _/_/ `, }, }}   var smallKeyboard = font{ height: 4, slant: 0, spacing: -1, m: map[rune][]string{ 'G': []string{ ` ____ `, `||G ||`, `||__||`, `|/__\|`, }, 'o': []string{ ` ____ `, `||o ||`, `||__||`, `|/__\|`, }, }}   type font struct { height int slant int spacing int m map[rune][]string }   func render(s string, f font) string { rows := make([]string, f.height) if f.slant != 0 { start := 0 if f.slant > 0 { start = f.height } for i := range rows { rows[i] = strings.Repeat(" ", (start-i)*f.slant) } } if f.spacing >= 0 { spacing := strings.Repeat(" ", f.spacing) for j, c := range s { for i, r := range f.m[c] { if j > 0 { r = spacing + r } rows[i] += r } } } else { overlap := -f.spacing for j, c := range s { for i, r := range f.m[c] { if j > 0 { r = r[overlap:] } rows[i] += r } } } return strings.Join(rows, "\n") }   func main() { fmt.Println(render("Go", lean)) fmt.Println(render("Go", smallKeyboard)) }
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.
#Java
Java
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder;   public class WindowController extends JFrame { // Create UI on correct thread public static void main( final String[] args ) { EventQueue.invokeLater( () -> new WindowController() ); }   private JComboBox<ControlledWindow> list;   // Button class to call the right method private class ControlButton extends JButton { private ControlButton( final String name ) { super( new AbstractAction( name ) { public void actionPerformed( final ActionEvent e ) { try { WindowController.class.getMethod( "do" + name ) .invoke ( WindowController.this ); } catch ( final Exception x ) { // poor practice x.printStackTrace(); // also poor practice } } } ); } }   // UI for controlling windows public WindowController() { super( "Controller" );   final JPanel main = new JPanel(); final JPanel controls = new JPanel();   setLocationByPlatform( true ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( 3, 3 ) ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH ); main.add( list = new JComboBox<>() ); add( main, BorderLayout.CENTER ); controls.setLayout( new GridLayout( 0, 1, 3, 3 ) ); controls.add( new ControlButton( "Add" ) ); controls.add( new ControlButton( "Hide" ) ); controls.add( new ControlButton( "Show" ) ); controls.add( new ControlButton( "Close" ) ); controls.add( new ControlButton( "Maximise" ) ); controls.add( new ControlButton( "Minimise" ) ); controls.add( new ControlButton( "Move" ) ); controls.add( new ControlButton( "Resize" ) ); add( controls, BorderLayout.EAST ); pack(); setVisible( true ); }   // These are the windows we're controlling, but any JFrame would do private static class ControlledWindow extends JFrame { private int num;   public ControlledWindow( final int num ) { super( Integer.toString( num ) ); this.num = num; setLocationByPlatform( true ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); add( new JLabel( "I am window " + num + ". Use the controller to control me." ) ); pack(); setVisible( true ); }   public String toString() { return "Window " + num; } }   // Here comes the useful bit - window control code // Everything else was just to allow us to do this!   public void doAdd() { list.addItem( new ControlledWindow( list.getItemCount () + 1 ) ); pack(); }   public void doHide() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( false ); }   public void doShow() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( true ); }   public void doClose() { final JFrame window = getWindow(); if ( null == window ) { return; } window.dispose(); }   public void doMinimise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setState( Frame.ICONIFIED ); }   public void doMaximise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setExtendedState( Frame.MAXIMIZED_BOTH ); }   public void doMove() { final JFrame window = getWindow(); if ( null == window ) { return; } final int hPos = getInt( "Horizontal position?" ); if ( -1 == hPos ) { return; } final int vPos = getInt( "Vertical position?" ); if ( -1 == vPos ) { return; } window.setLocation ( hPos, vPos ); }   public void doResize() { final JFrame window = getWindow(); if ( null == window ) { return; } final int width = getInt( "Width?" ); if ( -1 == width ) { return; } final int height = getInt( "Height?" ); if ( -1 == height ) { return; } window.setBounds ( window.getX(), window.getY(), width, height ); }   private JFrame getWindow() { final JFrame window = ( JFrame ) list.getSelectedItem(); if ( null == window ) { JOptionPane.showMessageDialog( this, "Add a window first" ); } return window; }   private int getInt(final String prompt) { final String s = JOptionPane.showInputDialog( prompt ); if ( null == s ) { return -1; } try { return Integer.parseInt( s ); } catch ( final NumberFormatException x ) { JOptionPane.showMessageDialog( this, "Not a number" ); return -1; } } }  
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ada
Ada
with Ada.Command_Line; with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Strings.Maps; with Ada.Strings.Fixed; with Ada.Characters.Handling; with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Indefinite_Ordered_Sets; with Ada.Containers.Ordered_Maps;   procedure Word_Frequency is package TIO renames Ada.Text_IO;   package String_Counters is new Ada.Containers.Indefinite_Ordered_Maps(String, Natural); package String_Sets is new Ada.Containers.Indefinite_Ordered_Sets(String); package Sorted_Counters is new Ada.Containers.Ordered_Maps (Natural, String_Sets.Set, "=" => String_Sets."=", "<" => ">"); -- for sorting by decreasing number of occurrences and ascending lexical order   procedure Increment(Key : in String; Element : in out Natural) is begin Element := Element + 1; end Increment;   path : constant String := Ada.Command_Line.Argument(1); how_many : Natural := 10; set : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set(ranges => (('a', 'z'), ('0', '9'))); F : TIO.File_Type; first : Positive; last : Natural; from : Positive; counter : String_Counters.Map; sorted_counts : Sorted_Counters.Map; C1 : String_Counters.Cursor; C2 : Sorted_Counters.Cursor; tmp_set : String_Sets.Set; begin -- read file and count words TIO.Open(F, name => path, mode => TIO.In_File); while not TIO.End_Of_File(F) loop declare line : constant String := Ada.Characters.Handling.To_Lower(TIO.Get_Line(F)); begin from := line'First; loop Ada.Strings.Fixed.Find_Token(line(from .. line'Last), set, Ada.Strings.Inside, first, last); exit when last < First; C1 := counter.Find(line(first .. last)); if String_Counters.Has_Element(C1) then counter.Update_Element(C1, Increment'Access); else counter.Insert(line(first .. last), 1); end if; from := last + 1; end loop; end; end loop; TIO.Close(F);   -- fill Natural -> StringSet Map C1 := counter.First; while String_Counters.Has_Element(C1) loop if sorted_counts.Contains(String_Counters.Element(C1)) then tmp_set := sorted_counts.Element(String_Counters.Element(C1)); tmp_set.Include(String_Counters.Key(C1)); else sorted_counts.Include(String_Counters.Element(C1), String_Sets.To_Set(String_Counters.Key(C1))); end if; String_Counters.Next(C1); end loop;   -- output C2 := sorted_counts.First; while Sorted_Counters.Has_Element(C2) loop for Item of Sorted_Counters.Element(C2) loop Ada.Integer_Text_IO.Put(TIO.Standard_Output, Sorted_Counters.Key(C2), width => 9); TIO.Put(TIO.Standard_Output, " "); TIO.Put_Line(Item); end loop; Sorted_Counters.Next(C2); how_many := how_many - 1; exit when how_many = 0; end loop; end Word_Frequency;  
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.
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1 File := "Wireworld.txt" CellSize := 20 CellSize2 := CellSize - 2 C1 := 0xff000000 C2 := 0xff0066ff C3 := 0xffd40055 C4 := 0xffffcc00   if (!FileExist(File)) { MsgBox, % "File(" File ") is not present." ExitApp }   ; Uncomment if Gdip.ahk is not in your standard library ; #Include, Gdip.ahk If !pToken := Gdip_Startup(){ MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. ExitApp } OnExit, Exit   A := [], Width := 0 Loop, Read, % File { Row := A_Index Loop, Parse, A_LoopReadLine { if (A_Index > Width) Width := A_Index if (A_LoopField = A_Space) continue A[Row, A_Index] := A_LoopField } }   Width := Width * CellSize + 2 * CellSize , Height := Row * CellSize + 2 * CellSize , Row := "" , TopLeftX := (A_ScreenWidth - Width) // 2 , TopLeftY := (A_ScreenHeight - Height) // 2   Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA   hwnd1 := WinExist() , hbm := CreateDIBSection(Width, Height) , hdc := CreateCompatibleDC() , obm := SelectObject(hdc, hbm) , G := Gdip_GraphicsFromHDC(hdc) , Gdip_SetSmoothingMode(G, 4)   Loop { pBrush := Gdip_BrushCreateSolid(C1) , Gdip_FillRectangle(G, pBrush, 0, 0, Width, Height) , Gdip_DeleteBrush(pBrush)   for RowNum, Row in A for CellNum, Cell in Row C := Cell = "H" ? C2 : Cell = "t" ? C3 : C4 , pBrush := Gdip_BrushCreateSolid(C) , Gdip_FillRectangle(G, pBrush, CellNum * CellSize + 1, RowNum * CellSize - 2, CellSize2, CellSize2) , Gdip_DeleteBrush(pBrush)     UpdateLayeredWindow(hwnd1, hdc, TopLeftX, TopLeftY, Width, Height) , Gdip_GraphicsClear(G) , A := NextState(A) Sleep, 600 }   NextState(A) { B := {} for RowNum, Row in A { for CellNum, Cell in Row { if (Cell = "H") B[RowNum, CellNum] := "t" else if (Cell = "t") B[RowNum, CellNum] := "." else if (Cell = ".") { H_Count := 0 Loop 3 { Y := RowNum - 2 + A_Index Loop, 3 { X := CellNum - 2 + A_Index if (A[Y, X] = "H") H_Count++ } } if (H_Count = 1 || H_Count = 2) B[RowNum, CellNum] := "H" else B[RowNum, CellNum] := "." } } } return B }   p::Pause   Esc:: Exit: Gdip_Shutdown(pToken) ExitApp
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
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <vector>   std::vector<bool> prime_sieve(uint64_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (uint64_t i = 4; i < limit; i += 2) sieve[i] = false; for (uint64_t p = 3; ; p += 2) { uint64_t q = p * p; if (q >= limit) break; if (sieve[p]) { uint64_t inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; }   uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; }   std::vector<uint64_t> wieferich_primes(uint64_t limit) { std::vector<uint64_t> result; std::vector<bool> sieve(prime_sieve(limit)); for (uint64_t p = 2; p < limit; ++p) if (sieve[p] && modpow(2, p - 1, p * p) == 1) result.push_back(p); return result; }   int main() { const uint64_t limit = 5000; std::cout << "Wieferich primes less than " << limit << ":\n"; for (uint64_t p : wieferich_primes(limit)) std::cout << p << '\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.
#Groovy
Groovy
groovy WindowCreation.groovy
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.
#GUISS
GUISS
Start,Programs,Applications,Editors,Leafpad,Textbox, Type:[openbox]Hello World[pling][closebox]
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
#jq
jq
def emit_until(cond; stream): label $out | stream | if cond then break $out else . end;   # For 0 <= $n <= ., factorials[$n] is $n ! def factorials: reduce range(1; .+1) as $n ([1]; .[$n] = $n * .[$n-1]);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def primes: 2, (range(3; infinite; 2) | select(is_prime));
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
#Julia
Julia
using Primes   function wilsonprimes(limit = 11000) sgn, facts = 1, accumulate(*, 1:limit, init = big"1") println(" n: Wilson primes\n--------------------") for n in 1:11 print(lpad(n, 2), ": ") sgn = -sgn for p in primes(limit) if p > n && (facts[n < 2 ? 1 : n - 1] * facts[p - n] - sgn) % p^2 == 0 print("$p ") end end println() end end   wilsonprimes()  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[WilsonPrime] WilsonPrime[n_Integer] := Module[{primes, out}, primes = Prime[Range[PrimePi[11000]]]; out = Reap@Do[ If[Divisible[((n - 1)!) ((p - n)!) - (-1)^n, p^2], Sow[p]] , {p, primes} ]; First[out[[2]], {}] ] Do[ Print[WilsonPrime[n]] , {n, 1, 11} ]
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
#Nim
Nim
import strformat, strutils import bignum   const Limit = 11_000   # Build list of primes using "nextPrime" function from "bignum". var primes: seq[int] var p = newInt(2) while p < Limit: primes.add p.toInt p = p.nextPrime()   # Build list of factorials. var facts: array[Limit, Int] facts[0] = newInt(1) for i in 1..<Limit: facts[i] = facts[i - 1] * i   var sign = 1 echo " n: Wilson primes" echo "—————————————————" for n in 1..11: sign = -sign var wilson: seq[int] for p in primes: if p < n: continue let f = facts[n - 1] * facts[p - n] - sign if f mod (p * p) == 0: wilson.add p echo &"{n:2}: ", wilson.join(" ")
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
#Perl
Perl
use strict; use warnings; use ntheory <primes factorial>;   my @primes = @{primes( 10500 )};   for my $n (1..11) { printf "%3d: %s\n", $n, join ' ', grep { $_ >= $n && 0 == (factorial($n-1) * factorial($_-$n) - (-1)**$n) % $_**2 } @primes }
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.
#C
C
/* * Opens an 800x600 16bit color window. * Done here with ANSI C. */   #include <stdio.h> #include <stdlib.h> #include "SDL.h"   int main() { SDL_Surface *screen;   if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );   return 0; }
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.
#C.23
C#
using System; using System.Windows.Forms;   public class Window { [STAThread] static void Main() { Form form = new Form();   form.Text = "Window"; form.Disposed += delegate { Application.Exit(); };   form.Show(); Application.Run(); } }
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
#Phix
Phix
-- -- demo\rosetta\wordsearch.exw -- =========================== -- with javascript_semantics string message = "ROSETTACODE" sequence words = unix_dict(), solution="", placed constant grid = split(""" X 0 1 2 3 4 5 6 7 8 9 X 0 X 1 X 2 X 3 X 4 X 5 X 6 X 7 X 8 X 9 X X X X X X X X X X X X X""",'\n') constant DX = {-1, 0,+1,+1,+1, 0,-1,-1}, DY = {-3,-3,-3, 0,+3,+3,+3, 0} procedure wordsearch(sequence grid, integer rqd, integer left, sequence done) sequence rw = shuffle(tagset(length(words))), rd = shuffle(tagset(8)), rs = shuffle(tagset(100)) for i=1 to length(rs) do integer sx = floor((rs[i]-1)/10)+2, sy = remainder(rs[i]-1,10)*3+4 for w=1 to length(rw) do string word = words[rw[w]] if not find(word,done[1]) then for d=1 to length(rd) do integer {dx,dy} = {DX[rd[d]],DY[rd[d]]}, {nx,ny} = {sx,sy}, chcount = length(word) sequence newgrid = deep_copy(grid) for c=1 to length(word) do integer ch = grid[nx][ny] if ch!=' ' then if ch!=word[c] then chcount = -1 exit end if chcount -= 1 end if newgrid[nx][ny] = word[c] nx += dx ny += dy end for if chcount!=-1 then sequence posinfo = {sx-2,(sy-4)/3,nx-dx-2,(ny-dy-4)/3}, newdone = {append(deep_copy(done[1]),word), append(deep_copy(done[2]),posinfo)} if rqd<=1 and left-chcount=length(message) then {solution, placed} = {newgrid, newdone} return elsif left-chcount>length(message) then wordsearch(newgrid,rqd-1,left-chcount,newdone) if length(solution) then return end if end if end if end for end if end for end for end procedure function valid_word(string word) if length(word)<3 then return false end if for i=1 to length(word) do integer ch = word[i] if ch<'a' or ch>'z' then return false end if end for return true end function for i=length(words) to 1 by -1 do if not valid_word(words[i]) then words[i] = words[$] words = words[1..$-1] end if end for printf(1,"%d words loaded\n",length(words)) -- 24822 wordsearch(grid,25,100,{{},{}}) for x=2 to 11 do for y=4 to 31 by 3 do if solution[x][y]=' ' then solution[x][y] = message[1] message = message[2..$] end if end for end for if length(message) then ?9/0 end if puts(1,substitute(join(solution,'\n'),"X"," ")) printf(1,"\n%d words\n",length(placed[1])) for i=1 to length(placed[1]) do printf(1,"%10s %10s ",{placed[1][i],sprint(placed[2][i])}) if mod(i,3)=0 then puts(1,"\n") end if end for {} = wait_key()
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
#Clojure
Clojure
;; Wrap line naive version (defn wrap-line [size text] (loop [left size line [] lines [] words (clojure.string/split text #"\s+")] (if-let [word (first words)] (let [wlen (count word) spacing (if (== left size) "" " ") alen (+ (count spacing) wlen)] (if (<= alen left) (recur (- left alen) (conj line spacing word) lines (next words)) (recur (- size wlen) [word] (conj lines (apply str line)) (next words)))) (when (seq line) (conj lines (apply str line))))))
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Swift
Swift
import Foundation   func oneAway(string1: [Character], string2: [Character]) -> Bool { if string1.count != string2.count { return false } var result = false var i = 0 while i < string1.count { if string1[i] != string2[i] { if result { return false } result = true } i += 1 } return result }   func wordLadder(words: [[Character]], from: String, to: String) { let fromCh = Array(from) let toCh = Array(to) var poss = words.filter{$0.count == fromCh.count} var queue: [[[Character]]] = [[fromCh]] while !queue.isEmpty { var curr = queue[0] let last = curr[curr.count - 1] queue.removeFirst() let next = poss.filter{oneAway(string1: $0, string2: last)} if next.contains(toCh) { curr.append(toCh) print(curr.map{String($0)}.joined(separator: " -> ")) return } poss.removeAll(where: {next.contains($0)}) for str in next { var temp = curr temp.append(str) queue.append(temp) } } print("\(from) into \(to) cannot be done.") }   do { let words = try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii) .components(separatedBy: "\n") .filter{!$0.isEmpty} .map{Array($0)} wordLadder(words: words, from: "man", to: "boy") wordLadder(words: words, from: "girl", to: "lady") wordLadder(words: words, from: "john", to: "jane") wordLadder(words: words, from: "child", to: "adult") wordLadder(words: words, from: "cat", to: "dog") wordLadder(words: words, from: "lead", to: "gold") wordLadder(words: words, from: "white", to: "black") wordLadder(words: words, from: "bubble", to: "tickle") } catch { print(error.localizedDescription) }
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "io" for File import "/sort" for Find   var words = File.read("unixdict.txt").trim().split("\n")   var oneAway = Fn.new { |a, b| var sum = 0 for (i in 0...a.count) if (a[i] != b[i]) sum = sum + 1 return sum == 1 }   var wordLadder = Fn.new { |a, b| var l = a.count var poss = words.where { |w| w.count == l }.toList var todo = [[a]] while (todo.count > 0) { var curr = todo[0] todo = todo[1..-1] var next = poss.where { |w| oneAway.call(w, curr[-1]) }.toList if (Find.first(next, b) != -1) { curr.add(b) System.print(curr.join(" -> ")) return } poss = poss.where { |p| !next.contains(p) }.toList for (i in 0...next.count) { var temp = curr.toList temp.add(next[i]) todo.add(temp) } } System.print("%(a) into %(b) cannot be done.") }   var pairs = [ ["boy", "man"], ["girl", "lady"], ["john", "jane"], ["child", "adult"] ] for (pair in pairs) wordLadder.call(pair[0], pair[1])
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
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Word_wheel use warnings;   $_ = <<END; N D E O K G E L W END   my $file = do { local(@ARGV, $/) = 'unixdict.txt'; <> }; my $length = my @letters = lc =~ /\w/g; my $center = $letters[@letters / 2]; my $toomany = (join '', sort @letters) =~ s/(.)\1*/ my $count = length "$1$&"; "(?!(?:.*$1){$count})" /ger; my $valid = qr/^(?=.*$center)$toomany([@letters]{3,$length}$)$/m;   my @words = $file =~ /$valid/g;   print @words . " words for\n$_\n@words\n" =~ s/.{60}\K /\n/gr;
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
#Phix
Phix
with javascript_semantics requires("1.0.1") -- (fixed another glitch in unique()) constant wheel = "ndeokgelw", musthave = wheel[5] sequence words = unix_dict(), word9 = {} -- (for the optional extra part) integer found = 0 for i=1 to length(words) do string word = lower(words[i]) integer lw = length(word) if lw>=3 then if lw<=9 then word9 = append(word9,word) end if if find(musthave,word) then string remaining = wheel while lw do integer k = find(word[lw],remaining) if k=0 then exit end if remaining[k] = '\0' -- (prevent re-use) lw -= 1 end while if lw=0 then found += 1 words[found] = word end if end if end if end for string jbw = join_by(words[1..found],1,9," ","\n ") printf(1, "The following %d words were found:\n %s\n",{found,jbw}) -- optional extra if platform()!=JS then -- (works but no progress/blank screen for 2min 20s) -- (the "working" won't show, even w/o the JS check) integer mostFound = 0 sequence mostWheels = {}, mustHaves = {} for i=1 to length(word9) do string try_wheel = word9[i] if length(try_wheel)=9 then string musthaves = unique(try_wheel) for j=1 to length(musthaves) do found = 0 for k=1 to length(word9) do string word = word9[k] if find(musthaves[j],word) then string rest = try_wheel bool ok = true for c=1 to length(word) do integer ix = find(word[c],rest) if ix=0 then ok = false exit end if rest[ix] = '\0' end for found += ok end if end for if platform()!=JS then -- (wouldn't show up anyway) printf(1,"working (%s)\r",{try_wheel}) end if if found>mostFound then mostFound = found mostWheels = {try_wheel} mustHaves = {musthaves[j]} elsif found==mostFound then mostWheels = append(mostWheels,try_wheel) mustHaves = append(mustHaves,musthaves[j]) end if end for end if end for printf(1,"Most words found = %d\n",mostFound) printf(1,"Nine letter words producing this total:\n") for i=1 to length(mostWheels) do printf(1,"%s with central letter '%c'\n",{mostWheels[i],mustHaves[i]}) end for end if
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.
#Ruby
Ruby
def ipart(n); n.truncate; end def fpart(n); n - ipart(n); end def rfpart(n); 1.0 - fpart(n); end   class Pixmap def draw_line_antialised(p1, p2, colour) x1, y1 = p1.x, p1.y x2, y2 = p2.x, p2.y   steep = (y2 - y1).abs > (x2 - x1).abs if steep x1, y1 = y1, x1 x2, y2 = y2, x2 end if x1 > x2 x1, x2 = x2, x1 y1, y2 = y2, y1 end deltax = x2 - x1 deltay = (y2 - y1).abs gradient = 1.0 * deltay / deltax   # handle the first endpoint xend = x1.round yend = y1 + gradient * (xend - x1) xgap = rfpart(x1 + 0.5) xpxl1 = xend ypxl1 = ipart(yend) put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap) put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap) itery = yend + gradient   # handle the second endpoint xend = x2.round yend = y2 + gradient * (xend - x2) xgap = rfpart(x2 + 0.5) xpxl2 = xend ypxl2 = ipart(yend) put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap) put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap)   # in between (xpxl1 + 1).upto(xpxl2 - 1).each do |x| put_colour(x, ipart(itery), colour, steep, rfpart(itery)) put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery)) itery = itery + gradient end end   def put_colour(x, y, colour, steep, c) x, y = y, x if steep self[x, y] = anti_alias(colour, self[x, y], c) end   def anti_alias(new, old, ratio) blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round} RGBColour.new(*blended) end end   bitmap = Pixmap.new(500, 500) bitmap.fill(RGBColour::BLUE) 10.step(430, 60) do |a| bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW) bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW) end bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)
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.
#Java
Java
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;   public class XmlCreation {   private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"};   public static void main(String[] args) { try { // Create a new XML document final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();   // Append the root element final Element root = doc.createElement("CharacterRemarks"); doc.appendChild(root);   // Read input data and create a new <Character> element for each name. for(int i = 0; i < names.length; i++) { final Element character = doc.createElement("Character"); root.appendChild(character); character.setAttribute("name", names[i]); character.appendChild(doc.createTextNode(remarks[i])); }   // Serializing XML in Java is unnecessary complicated // Create a Source from the document. final Source source = new DOMSource(doc);   // This StringWriter acts as a buffer final StringWriter buffer = new StringWriter();   // Create a Result as a transformer target. final Result result = new StreamResult(buffer);   // The Transformer is used to copy the Source to the Result object. final Transformer 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. System.out.println(buffer.toString()); } catch (Exception e) { e.printStackTrace(); } }   }
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
#J
J
load'xml/sax'   saxclass 'Students' startElement =: ([: smoutput 'Name' getAttribute~ [)^:('Student'-:]) cocurrent'base'   process_Students_ XML
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#uBasic.2F4tH
uBasic/4tH
Let @(0) = 5 : Print @(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.
#Ruby
Ruby
# prepare test data x = [1, 2, 3, 1e11] y = x.collect { |xx| Math.sqrt xx } xprecision = 3 yprecision = 5   # write the arrays open('sqrt.dat', 'w') do |f| x.zip(y) { |xx, yy| f.printf("%.*g\t%.*g\n", xprecision, xx, yprecision, yy) } end   # print the result file open('sqrt.dat', 'r') { |f| puts f.read }
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.
#Run_BASIC
Run BASIC
x$ = "1, 2, 3, 1e11" y$ = "1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791"   open "filename" for output as #f ' Output to "filename" for i = 1 to 4 print #f, using("##############.###",val(word$(x$,i,",")));"|";using("#######.#####",val(word$(y$,i,","))) next i close #f
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#MoonScript
MoonScript
is_open = [false for door = 1,100]   for pass = 1,100 for door = pass,100,pass is_open[door] = not is_open[door]   for i,v in ipairs is_open print "Door #{i}: " .. if v then 'open' else 'closed'
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#C
C
#include "stdio.h" #include "stdlib.h" #include "stdbool.h" #include "string.h"   struct int_a { int *ptr; size_t size; };   struct int_a divisors(int n) { int *divs, *divs2, *out; int i, j, c1 = 0, c2 = 0; struct int_a array;   divs = malloc(n * sizeof(int) / 2); divs2 = malloc(n * sizeof(int) / 2); divs[c1++] = 1;   for (i = 2; i * i <= n; i++) { if (n % i == 0) { j = n / i; divs[c1++] = i; if (i != j) { divs2[c2++] = j; } } }   out = malloc((c1 + c2) * sizeof(int)); for (int i = 0; i < c2; i++) { out[i] = divs2[i]; } for (int i = 0; i < c1; i++) { out[c2 + i] = divs[c1 - i - 1]; } array.ptr = out; array.size = c1 + c2;   free(divs); free(divs2); return array; }   bool abundant(int n, struct int_a divs) { int sum = 0; int i; for (i = 0; i < divs.size; i++) { sum += divs.ptr[i]; } return sum > n; }   bool semiperfect(int n, struct int_a divs) { if (divs.size > 0) { int h = *divs.ptr; int *t = divs.ptr + 1;   struct int_a ta; ta.ptr = t; ta.size = divs.size - 1;   if (n < h) { return semiperfect(n, ta); } else { return n == h || semiperfect(n - h, ta) || semiperfect(n, ta); } } else { return false; } }   bool *sieve(int limit) { bool *w = calloc(limit, sizeof(bool)); struct int_a divs; int i, j;   for (i = 2; i < limit; i += 2) { if (w[i]) continue; divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (j = i; j < limit; j += i) { w[j] = true; } } }   free(divs.ptr); return w; }   int main() { bool *w = sieve(17000); int count = 0; int max = 25; int n;   printf("The first 25 weird numbers:\n"); for (n = 2; count < max; n += 2) { if (!w[n]) { printf("%d ", n); count++; } } printf("\n");   free(w); 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
#Groovy
Groovy
println """\ _|_|_| _| _| _|_| _|_| _|_| _| _| _| _| _| _|_| _|_| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _|_|_| _| _|_| _|_| _| _|_|_| _| _|_|"""
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Haskell
Haskell
module Main where {- __ __ __ ___ ___ /\ \/\ \ /\ \ /\_ \ /\_ \ \ \ \_\ \ __ ____\ \ \/'\ __\//\ \ \//\ \ \ \ _ \ /'__`\ /',__\\ \ , < /'__`\\ \ \ \ \ \ \ \ \ \ \/\ \L\.\_/\__, `\\ \ \\`\ /\ __/ \_\ \_ \_\ \_ \ \_\ \_\ \__/.\_\/\____/ \ \_\ \_\ \____\/\____\/\____\ \/_/\/_/\/__/\/_/\/___/ \/_/\/_/\/____/\/____/\/____/ -}   ascii3d :: String ascii3d = " __ __ __ ___ ___ \n" ++ "/\\ \\/\\ \\ /\\ \\ /\\_ \\ /\\_ \\ \n" ++ "\\ \\ \\_\\ \\ __ ____\\ \\ \\/'\\ __\\//\\ \\ \\//\\ \\ \n" ++ " \\ \\ _ \\ /'__`\\ /',__\\\\ \\ , < /'__`\\\\ \\ \\ \\ \\ \\ \n" ++ " \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\__, `\\\\ \\ \\\\`\\ /\\ __/ \\_\\ \\_ \\_\\ \\_ \n" ++ " \\ \\_\\ \\_\\ \\__/.\\_\\/\\____/ \\ \\_\\ \\_\\ \\____\\/\\____\\/\\____\\\n" ++ " \\/_/\\/_/\\/__/\\/_/\\/___/ \\/_/\\/_/\\/____/\\/____/\\/____/"   main = putStrLn ascii3d  
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.
#Julia
Julia
using Gtk   function controlwindow(win, lab) sleep(4) set_gtk_property!(lab, :label, "Hiding...") sleep(1) println("Hiding widow") set_gtk_property!(win, :visible, false) sleep(5) set_gtk_property!(lab, :label, "Showing...") println("Showing window") set_gtk_property!(win, :visible, true) sleep(5) set_gtk_property!(lab, :label, "Resizing...") println("Resizing window") resize!(win, 300, 300) sleep(4) set_gtk_property!(lab, :label, "Maximizing...") println("Maximizing window") sleep(1) maximize(win) set_gtk_property!(lab, :label, "Closing...") sleep(5) println("Closing window") destroy(win) sleep(2) exit(0) end   function runwindow() win = GtkWindow("Window Control Test", 500, 30) |> (GtkFrame() |> (vbox = GtkBox(:v))) lab = GtkLabel("Window under external control") push!(vbox, lab) @async(controlwindow(win, lab))   cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) showall(win) wait(cond) end   runwindow()  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
nb=NotebookCreate[]; (*Create a window and store in a variable*) nb===nb2 (*test for equality with another window object*) SetOptions[nb,Visible->False](*Hide*) SetOptions[nb,Visible->True](*Show*) NotebookClose[nb] (*Close*) SetOptions[nb,WindowMargins->{{x,Automatic},{y,Automatic}}](*Move to x,y screen position*) SetOptions[nb,WindowSize->{100,100}](*Resize*)
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
#ALGOL_68
ALGOL 68
# find the n most common words in a file # # use the associative array in the Associate array/iteration task # # but with integer values # PR read "aArrayBase.a68" PR MODE AAKEY = STRING; MODE AAVALUE = INT; AAVALUE init element value = 0; # returns text converted to upper case # OP TOUPPER = ( STRING text )STRING: BEGIN STRING result := text; FOR ch pos FROM LWB result TO UPB result DO IF is lower( result[ ch pos ] ) THEN result[ ch pos ] := to upper( result[ ch pos ] ) FI OD; result END # TOUPPER # ; # returns text converted to an INT or -1 if text is not a number # OP TOINT = ( STRING text )INT: BEGIN INT result := 0; BOOL is numeric := TRUE; FOR ch pos FROM UPB text BY -1 TO LWB text WHILE is numeric DO CHAR c = text[ ch pos ]; is numeric := is numeric AND c >= "0" AND c <= "9"; IF is numeric THEN ( result *:= 10 ) +:= ABS c - ABS "0" FI OD; IF is numeric THEN result ELSE -1 FI END # TOINT # ; # returns TRUE if c is a letter, FALSE otherwise # OP ISLETTER = ( CHAR c )BOOL: IF ( c >= "a" AND c <= "z" ) OR ( c >= "A" AND c <= "Z" ) THEN TRUE ELSE char in string( c, NIL, "ÇåçêëÆôöÿÖØáóÔ" ) FI # ISLETER # ; # get the file name and number of words from then commmand line # STRING file name := "pg-les-misrables.txt"; INT number of words := 10; FOR arg pos TO argc - 1 DO STRING arg upper = TOUPPER argv( arg pos ); IF arg upper = "FILE" THEN file name := argv( arg pos + 1 ) ELIF arg upper = "NUMBER" THEN number of words := TOINT argv( arg pos + 1 ) FI OD; IF FILE input file; open( input file, file name, stand in channel ) /= 0 THEN # failed to open the file # print( ( "Unable to open """ + file name + """", newline ) ) ELSE # file opened OK # print( ( "Processing: ", file name, newline ) ); BOOL at eof := FALSE; BOOL at eol := FALSE; # set the EOF handler for the file # on logical file end( input file, ( REF FILE f )BOOL: BEGIN # note that we reached EOF on the # # latest read # at eof := TRUE; # return TRUE so processing can continue # TRUE END ); # set the end-of-line handler for the file so get word can see line boundaries # on line end( input file , ( REF FILE f )BOOL: BEGIN # note we reached end-of-line # at eol := TRUE; # return FALSE to use the default eol handling # # i.e. just get the next charactefr # FALSE END ); # get the words from the file and store the counts in an associative array # REF AARRAY words := INIT LOC AARRAY; INT word count := 0; CHAR c := " "; WHILE get( input file, ( c ) ); NOT at eof DO WHILE NOT ISLETTER c AND NOT at eof DO get( input file, ( c ) ) OD; STRING word := ""; at eol := FALSE; WHILE ISLETTER c AND NOT at eol AND NOT at eof DO word +:= c; get( input file, ( c ) ) OD; word count +:= 1; words // TOUPPER word +:= 1 OD; close( input file ); print( ( file name, " contains ", whole( word count, 0 ), " words", newline ) ); # find the most used words # [ number of words ]STRING top words; [ number of words ]INT top counts; FOR i TO number of words DO top words[ i ] := ""; top counts[ i ] := 0 OD; REF AAELEMENT w := FIRST words; WHILE w ISNT nil element DO INT count = value OF w; STRING word = key OF w; BOOL found := FALSE; FOR i TO number of words WHILE NOT found DO IF count > top counts[ i ] THEN # found a word that is used nore than a current # # most used word # found := TRUE; # move the other words down one place # FOR move pos FROM number of words BY - 1 TO i + 1 DO top counts[ move pos ] := top counts[ move pos - 1 ]; top words [ move pos ] := top words [ move pos - 1 ] OD; # install the new word # top counts[ i ] := count; top words [ i ] := word FI OD; w := NEXT words OD; print( ( whole( number of words, 0 ), " most used words:", newline ) ); print( ( " count word", newline ) ); FOR i TO number of words DO print( ( whole( top counts[ i ], -6 ), ": ", top words[ i ], newline ) ) OD FI
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.
#AutoIt
AutoIt
  $ww = "" $ww &= "tH........." & @CR $ww &= ". . " & @CR $ww &= " ... " & @CR $ww &= ". . " & @CR $ww &= "Ht.. ......" $rows = StringSplit($ww, @CR) $cols = StringSplit($rows[1], "") Global $Wireworldarray[$rows[0]][$cols[0]] For $I = 1 To $rows[0] $cols = StringSplit($rows[$I], "") For $k = 1 To $cols[0] $Wireworldarray[$I - 1][$k - 1] = $cols[$k] Next Next Wireworld($Wireworldarray) Func Wireworld($array) Local $labelarray = $array Local $Top = 0, $Left = 0 $hFui = GUICreate("Wireworld", UBound($array, 2) * 25, UBound($array) * 25) For $I = 0 To UBound($array) - 1 For $k = 0 To UBound($array, 2) - 1 Switch $array[$I][$k] Case "t" ; Tail $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) Case "h" ; Head $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) Case "." ; Conductor $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) Case " " ; Empty $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) EndSwitch $Left += 25 Next $Left = 0 $Top += 25 Next GUISetState() Local $nextsteparray = $array While 1 $msg = GUIGetMsg() $array = $nextsteparray Sleep(250) For $I = 0 To UBound($array) - 1 For $k = 0 To UBound($array, 2) - 1 If $array[$I][$k] = " " Then ContinueLoop If $array[$I][$k] = "h" Then $nextsteparray[$I][$k] = "t" If $array[$I][$k] = "t" Then $nextsteparray[$I][$k] = "." If $array[$I][$k] = "." Then $counter = 0 If $I - 1 >= 0 Then ; Top If $array[$I - 1][$k] = "h" Then $counter += 1 EndIf If $k - 1 >= 0 Then ; left If $array[$I][$k - 1] = "h" Then $counter += 1 EndIf If $I + 1 <= UBound($array) - 1 Then ; Bottom If $array[$I + 1][$k] = "h" Then $counter += 1 EndIf If $k + 1 <= UBound($array, 2) - 1 Then ;Right If $array[$I][$k + 1] = "h" Then $counter += 1 EndIf If $I - 1 >= 0 And $k - 1 >= 0 Then ; left Top If $array[$I - 1][$k - 1] = "h" Then $counter += 1 EndIf If $I + 1 <= UBound($array) - 1 And $k + 1 <= UBound($array, 2) - 1 Then ; Right Bottom If $array[$I + 1][$k + 1] = "h" Then $counter += 1 EndIf If $I + 1 <= UBound($array) - 1 And $k - 1 >= 0 Then ;Left Bottom If $array[$I + 1][$k - 1] = "h" Then $counter += 1 EndIf If $I - 1 >= 0 And $k + 1 <= UBound($array, 2) - 1 Then ; Top Right If $array[$I - 1][$k + 1] = "h" Then $counter += 1 EndIf If $counter = 1 Or $counter = 2 Then $nextsteparray[$I][$k] = "h" EndIf Next Next For $I = 0 To UBound($nextsteparray) - 1 For $k = 0 To UBound($nextsteparray, 2) - 1 Switch $nextsteparray[$I][$k] Case "t" ; Tail GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) Case "h" ; Head GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) Case "." ; Conductor GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) Case " " ; Empty GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) EndSwitch $Left += 25 Next $Left = 0 $Top += 25 Next If $msg = -3 Then Exit WEnd EndFunc ;==>Wireworld  
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace WieferichPrimes { class Program { 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; }   static bool[] PrimeSieve(int limit) { bool[] sieve = Enumerable.Repeat(true, limit).ToArray();   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; }   static List<int> WiefreichPrimes(int limit) { bool[] sieve = PrimeSieve(limit); List<int> result = new List<int>(); for (int p = 2; p < limit; p++) { if (sieve[p] && ModPow(2, p - 1, p * p) == 1) { result.Add(p); } } return result; }   static void Main() { const int limit = 5000; Console.WriteLine("Wieferich primes less that {0}:", limit); foreach (int p in WiefreichPrimes(limit)) { Console.WriteLine(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.
#Haskell
Haskell
import Graphics.X11.Xlib import Control.Concurrent (threadDelay)   main = do display <- openDisplay "" let defScr = defaultScreen display rw <- rootWindow display defScr   xwin <- createSimpleWindow display rw 0 0 400 200 1 (blackPixel display defScr) (whitePixel display defScr)   setTextProperty display xwin "Rosetta Code: X11 simple window" wM_NAME   mapWindow display xwin   sync display False threadDelay (5000000)   destroyWindow display xwin closeDisplay display  
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() W1 := open("X-Window","g","size=250,250","bg=black","fg=red") | stop("unable to open window") FillRectangle(W1,50,50,150,150) WDone(W1) end   link graphics
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
#Phix
Phix
with javascript_semantics constant limit = 11000 include mpfr.e mpz f = mpz_init() sequence primes = get_primes_le(limit), facts = mpz_inits(limit,1) -- (nb 0!==1!, same slot) for i=2 to limit do mpz_mul_si(facts[i],facts[i-1],i) end for integer sgn = 1 printf(1," n: Wilson primes\n") printf(1,"--------------------\n") for n=1 to 11 do printf(1,"%2d: ", n) sgn = -sgn for i=1 to length(primes) do integer p = primes[i] if p>=n then mpz_mul(f,facts[max(n-1,1)],facts[max(p-n,1)]) mpz_sub_si(f,f,sgn) if mpz_divisible_ui_p(f,p*p) then printf(1,"%d ", p) end if end if end for printf(1,"\n") end for
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
#Prolog
Prolog
main:- wilson_primes(11000).   wilson_primes(Limit):- writeln(' n | Wilson primes\n---------------------'), make_factorials(Limit), find_prime_numbers(Limit), wilson_primes(1, 12, -1).   wilson_primes(N, N, _):-!. wilson_primes(N, M, S):- wilson_primes(N, S), S1 is -S, N1 is N + 1, wilson_primes(N1, M, S1).   wilson_primes(N, S):- writef('%3r |', [N]), N1 is N - 1, factorial(N1, F1), is_prime(P), P >= N, PN is P - N, factorial(PN, F2), 0 is (F1 * F2 - S) mod (P * P), writef(' %w', [P]), fail. wilson_primes(_, _):- nl.   make_factorials(N):- retractall(factorial(_, _)), make_factorials(N, 0, 1).   make_factorials(N, N, F):- assert(factorial(N, F)), !. make_factorials(N, M, F):- assert(factorial(M, F)), M1 is M + 1, F1 is F * M1, make_factorials(N, M1, F1).
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.
#C.2B.2B
C++
#include <QApplication> #include <QMainWindow>   int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow window; window.show(); return app.exec(); }
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Clojure
Clojure
(import '(javax.swing JFrame))   (let [frame (JFrame. "A Window")] (doto frame (.setSize 600 800) (.setVisible true)))
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
#Python
Python
  import re from random import shuffle, randint   dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25     class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = []     def read_words(filename): max_len = max(n_rows, n_cols)   words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s)   return words     def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper())   message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len   for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i]   return message_len   return 0     def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word)   # check bounds if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0   rr = r cc = c i = 0 overlaps = 0   # check cells while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1   rr = r cc = c i = 0 # place while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i]   if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1]   i += 1   letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))   return letters_placed     def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size)   for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs)   for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size   letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed   return 0     def create_word_search(words): grid = None num_attempts = 0   while num_attempts < 100: num_attempts += 1 shuffle(words)   grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len   cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break # grid is full but we didn't pack enough words, start over   return grid     def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return   size = len(grid.solutions)   print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size))   print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print()   for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))   if size % 2 == 1: print(grid.solutions[size - 1])     if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))  
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
#Commodore_BASIC
Commodore BASIC
10 rem word wrap - commodore basic 20 rem rosetta code 30 s$="":co=40:gosub 200 35 print chr$(147);chr$(14) 40 print "The current string is:" 41 print chr$(18);s$;chr$(146) 42 print:print "Enter a string, blank to keep previous," 43 print "or type 'sample' to use a preset"len(z$)" character string." 44 print:input s$:if s$="sample" then s$=z$ 45 print:print "enter column limit, 10-80 [";co;"{left}]";:input co 46 if co<12 or co>80 then goto 45 50 print chr$(147);"Wrapping on column";co;"results as:" 55 gosub 400 60 print 65 print r$ 70 print 80 input "Again (y/n)";yn$ 90 if yn$="y" then goto 35 100 end 200 rem set up sample string 205 data "Lorem Ipsum is typically a corrupted version of 'De finibus " 210 data "bonorum et malorum', a first-century BC text by the Roman statesman " 215 data "and philosopher Cicero, with words altered, added, and removed to " 220 data "make it nonsensical, improper Latin." 225 data "zzz" 230 z$="" 235 read tp$:if tp$<>"zzz" then z$=z$+tp$:goto 235 240 return 400 rem word-wrap string 401 tp$=s$:as$="" 405 if len(tp$)<=co then goto 440 410 for i=0 to co-1:c$=mid$(tp$,co-i,1) 420 if c$<>" " and c$<>"-" then next i 425 ad$=chr$(13):if c$="-" then ad$="-"+chr$(13) 430 as$=as$+left$(tp$,co-1-i)+ad$:tp$=mid$(tp$,co-i+1,len(tp$)):i=0 435 goto 405 440 as$=as$+tp$ 450 r$=as$ 460 return
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
#Picat
Picat
main => MinLen = 3, MaxLen = 9, Chars = "ndeokgelw", MustContain = 'k',   WordList = "unixdict.txt", Words = read_file_lines(WordList), Res = word_wheel(Chars,Words,MustContain,MinLen, MaxLen), println(Res), println(len=Res.len), nl.   word_wheel(Chars,Words,MustContain,MinLen,MaxLen) = Res.reverse => Chars := to_lowercase(Chars), D = make_hash(Chars), Res = [], foreach(W in Words, W.len >= MinLen, W.len <= MaxLen, membchk(MustContain,W)) WD = make_hash(W), Check = true, foreach(C in keys(WD), break(Check == false)) if not D.has_key(C) ; WD.get(C,0) > D.get(C,0) then Check := false end end, if Check == true then Res := [W|Res] end end.   % Returns a map of the elements and their occurrences % in the list L. make_hash(L) = D => D = new_map(), foreach(E in L) D.put(E,D.get(E,0)+1) end.
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
#PureBasic
PureBasic
Procedure.b check_word(word$) Shared letters$ If Len(word$)<3 Or FindString(word$,"k")<1 ProcedureReturn #False EndIf For i=1 To Len(word$) If CountString(letters$,Mid(word$,i,1))<CountString(word$,Mid(word$,i,1)) ProcedureReturn #False EndIf Next ProcedureReturn #True EndProcedure   If ReadFile(0,"./Data/unixdict.txt") txt$=LCase(ReadString(0,#PB_Ascii|#PB_File_IgnoreEOL)) CloseFile(0) EndIf   If OpenConsole() letters$="ndeokgelw" wordcount=1 Repeat buf$=StringField(txt$,wordcount,~"\n") wordcount+1 If check_word(buf$)=#False Continue EndIf PrintN(buf$) : r+1 Until buf$="" PrintN("- Finished: "+Str(r)+" words found -") Input() EndIf End
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.
#Scala
Scala
import java.awt.Color import math.{floor => ipart, round, abs}   case class Point(x: Double, y: Double) {def swap = Point(y, x)}   def plotter(bm: RgbBitmap, c: Color)(x: Double, y: Double, v: Double) = { val X = round(x).toInt val Y = round(y).toInt val V = v.toFloat // tint the existing pixels val c1 = c.getRGBColorComponents(null) val c2 = bm.getPixel(X, Y).getRGBColorComponents(null) val c3 = (c1 zip c2).map{case (n, o) => n * V + o * (1 - V)} bm.setPixel(X, Y, new Color(c3(0), c3(1), c3(2))) }   def drawLine(plotter: (Double,Double,Double) => _)(p1: Point, p2: Point) { def fpart(x: Double) = x - ipart(x) def rfpart(x: Double) = 1 - fpart(x) def avg(a: Float, b: Float) = (a + b) / 2   val steep = abs(p2.y - p1.y) > abs(p2.x - p1.x) val (p3, p4) = if (steep) (p1.swap, p2.swap) else (p1, p2) val (a, b) = if (p3.x > p4.x) (p4, p3) else (p3, p4) val dx = b.x - a.x val dy = b.y - a.y val gradient = dy / dx var intery = 0.0   def endpoint(xpxl: Double, yend: Double, xgap: Double) { val ypxl = ipart(yend) if (steep) { plotter(ypxl, xpxl, rfpart(yend) * xgap) plotter(ypxl+1, xpxl, fpart(yend) * xgap) } else { plotter(xpxl, ypxl , rfpart(yend) * xgap) plotter(xpxl, ypxl+1, fpart(yend) * xgap) } }   // handle first endpoint var xpxl1 = round(a.x); { val yend = a.y + gradient * (xpxl1 - a.x) val xgap = rfpart(a.x + 0.5) endpoint(xpxl1, yend, xgap) intery = yend + gradient }   // handle second endpoint val xpxl2 = round(b.x); { val yend = b.y + gradient * (xpxl2 - b.x) val xgap = fpart(b.x + 0.5) endpoint(xpxl2, yend, xgap) }   // main loop for (x <- (xpxl1 + 1) to (xpxl2 - 1)) { if (steep) { plotter(ipart(intery) , x, rfpart(intery)) plotter(ipart(intery)+1, x, fpart(intery)) } else { plotter(x, ipart (intery), rfpart(intery)) plotter(x, ipart (intery)+1, fpart(intery)) } intery = 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.
#Joy
Joy
  DEFINE subst == [[['< "&lt;" putchars] ['> "&gt;" putchars] ['& "&amp;" putchars] [putch]] case] step;   XMLOutput == "<CharacterRemarks>\n" putchars [ "<Character name=\"" putchars uncons swap putchars "\">" putchars first subst "</Character>\n" putchars] step "</CharacterRemarks>\n" putchars.   [ [ "April" "Bubbly: I'm > Tam and <= Emily" ] [ "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" ] [ "Emily" "Short & shrift" ] ] XMLOutput.  
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.
#Julia
Julia
using LightXML   dialog = [("April", "Bubbly: I'm > Tam and <= Emily"), ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""), ("Emily", "Short & shrift")]   const xdoc = XMLDocument() const xroot = create_root(xdoc, "CharacterRemarks")   for (name, remarks) in dialog xs1 = new_child(xroot, "Character") set_attribute(xs1, "name", name) add_text(xs1, remarks) end   println(xdoc)  
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
#Java
Java
import java.io.IOException; import java.io.StringReader; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory;   public class StudentHandler extends DefaultHandler { public static void main(String[] args)throws Exception{ String xml = "<Students>\n"+ "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"+ "<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n"+ "<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n"+ "<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n"+ " <Pet Type=\"dog\" Name=\"Rover\" />\n"+ "</Student>\n"+ "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n"+ "</Students>"; StudentHandler handler = new StudentHandler(); handler.parse(new InputSource(new StringReader(xml))); }   public void parse(InputSource src) throws SAXException, IOException { XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(this); parser.parse(src); }   @Override public void characters(char[] ch, int start, int length) throws SAXException { //if there were text as part of the elements, we would deal with it here //by adding it to a StringBuffer, but we don't have to for this task super.characters(ch, start, length); }   @Override public void endElement(String uri, String localName, String qName) throws SAXException { //this is where we would get the info from the StringBuffer if we had to, //but all we need is attributes super.endElement(uri, localName, qName); }   @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("Student")){ System.out.println(attributes.getValue("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)
#Unicon_2
Unicon
L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[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.
#SAS
SAS
data _null_; input x y; file "output.txt"; put x 12.3 " " y 12.5; cards; 1 1 2 1.4142135623730951 3 1.7320508075688772 1e11 316227.76601683791 ; run;
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.
#Scala
Scala
import java.io.{File, FileWriter, IOException}   object FloatArray extends App { val x: List[Float] = List(1f, 2f, 3f, 1e11f)   def writeStringToFile(file: File, data: String, appending: Boolean = false) = using(new FileWriter(file, appending))(_.write(data))   def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B = try f(resource) finally resource.close()   try { val file = new File("sqrt.dat") using(new FileWriter(file))(writer => x.foreach(x => writer.write(f"$x%.3g\t${math.sqrt(x)}%.5g\n"))) } catch { case e: IOException => println(s"Running Example failed: ${e.getMessage}") } }
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.
#MUMPS
MUMPS
doors new door,pass For door=1:1:100 Set door(door)=0 For pass=1:1:100 For door=pass:pass:100 Set door(door)='door(door) For door=1:1:100 If door(door) Write !,"Door",$j(door,4)," is open" Write !,"All other doors are closed." Quit Do doors Door 1 is open Door 4 is open Door 9 is open Door 16 is open Door 25 is open Door 36 is open Door 49 is open Door 64 is open Door 81 is open Door 100 is open All other doors are closed.
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   namespace WeirdNumbers { class Program { static List<int> Divisors(int n) { List<int> divs = new List<int> { 1 }; List<int> divs2 = new List<int>();   for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs2.Add(j); } } }   divs.Reverse(); divs2.AddRange(divs); return divs2; }   static bool Abundant(int n, List<int> divs) { return divs.Sum() > n; }   static bool Semiperfect(int n, List<int> divs) { if (divs.Count > 0) { var h = divs[0]; var t = divs.Skip(1).ToList(); if (n < h) { return Semiperfect(n, t); } else { return n == h || Semiperfect(n - h, t) || Semiperfect(n, t); } } else { return false; } }   static List<bool> Sieve(int limit) { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 bool[] w = new bool[limit]; for (int i = 2; i < limit; i += 2) { if (w[i]) continue; var 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.ToList(); }   static void Main() { var w = Sieve(17_000); int count = 0; int max = 25; Console.WriteLine("The first 25 weird numbers:"); for (int n = 2; count < max; n += 2) { if (!w[n]) { Console.Write("{0} ", n); count++; } } Console.WriteLine(); } } }
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
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) write(ExpandText( if !arglist == "icon" then "14/\\\n14\\/\n12/\\\n11/1/\n10/1/1/\\\n10\\/1/2\\\n12/1/\\1\\\n_ 12\\1\\1\\/\n10/\\1\\1\\2/\\\n9/2\\1\\/1/2\\\n_ 8/1/\\1\\2/1/\\1\\2/\\\n8\\1\\/1/2\\1\\/1/2\\1\\\n_ 6/\\1\\2/4\\2/1/\\1\\1\\\n5/1/2\\/6\\/1/2\\1\\/\n_ /\\2/1/1/\\10/1/\\1\\2/\\\n\\/2\\1\\/1/10\\/1/1/2\\/\n_ 2/\\1\\2/1/\\6/\\2/1/\n2\\1\\1\\/1/2\\4/2\\1\\/\n_ 3\\1\\2/1/\\1\\2/1/\\1\\\n4\\/2\\1\\/1/2\\1\\/1/\n_ 9\\2/1/\\1\\2/\n10\\/2\\1\\1\\/\n12/\\1\\1\\\n12\\1\\/1/\n_ 13\\2/1/\\\n14\\/1/1/\n16/1/\n16\\/\n14/\\\n14\\/\n" else "13/\\\n12/1/\n11/1/1/\\\n11\\1\\/1/\n12\\2/1/\\\n13\\/1/2\\\n_ 15/1/\\1\\2/\\\n15\\/1/1/2\\/\n17/1/1/\\18/\\\n17\\/1/1/17/2\\\n_ 19/1/1/\\14/1/\\1\\\n19\\/1/2\\13\\1\\1\\/\n21/1/\\1\\10/\\1\\1\\\n_ 21\\1\\1\\/10\\1\\1\\/\n19/\\1\\1\\2/\\6/\\1\\1\\\n_ 18/2\\1\\/1/2\\5\\1\\/1/\n17/1/\\1\\2/1/\\1\\2/\\1\\2/\n_ 17\\1\\/1/2\\1\\/1/2\\1\\1\\/\n15/\\1\\2/4\\2/1/\\1\\1\\\n_ 14/1/2\\/6\\/1/2\\1\\/\n9/\\2/1/1/\\10/1/\\1\\2/\\\n_ 9\\/2\\1\\/1/10\\/1/1/2\\/\n11/\\1\\2/1/\\6/\\2/1/\n_ 11\\1\\1\\/1/2\\4/2\\1\\/\n9/\\1\\1\\2/1/\\1\\2/1/\\1\\\n_ 8/2\\1\\/2\\1\\/1/2\\1\\/1/\n7/1/\\1\\5\\2/1/\\1\\2/\n_ 7\\1\\1\\/6\\/2\\1\\1\\/\n5/\\1\\1\\10/\\1\\1\\\n_ 5\\1\\1\\/10\\1\\/1/\n3/\\1\\1\\13\\2/1/\\\n3\\1\\/1/14\\/1/1/\n_ 4\\2/17/1/1/\\\n5\\/18\\/1/1/\n23/\\2/1/1/\\\n23\\/2\\1\\/1/\n_ 28\\2/1/\\\n29\\/1/2\\\n31/1/\\1\\\n31\\/1/1/\n33/1/\n33\\/\n" )) end   procedure ExpandText(s) s ? until pos(0) do writes(repl(" ",tab(many(&digits)))|tab(upto(&digits)|0)) end
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible, only use libraries that come at no extra monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++.
#8th
8th
\ Web-scrape sample: get UTC time from the US Naval Observatory: : read-url \ -- s "http://tycho.usno.navy.mil/cgi-bin/timer.pl" net:get not if "Could not connect" throw then >s ;   : get-time read-url /<BR>.*?(\d{2}:\d{2}:\d{2})\sUTC/ tuck r:match if 1 r:@ . cr then ;   get-time bye  
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.
#Nim
Nim
import os import gintro/[glib, gobject, gtk, gio] from gintro/gdk import processAllUpdates   type MyWindow = ref object of ApplicationWindow isShifted: bool   #---------------------------------------------------------------------------------------------------   proc wMaximize(button: Button; window: MyWindow) = window.maximize()   proc wUnmaximize(button: Button; window: MyWindow) = window.unmaximize()   proc wIconify(button: Button; window: MyWindow) = window.iconify()   proc wDeiconify(button: Button; window: MyWindow) = window.deiconify()   proc wHide(button: Button; window: MyWindow) = window.hide() processAllUpdates() os.sleep(2000) window.show()   proc wShow(button: Button; window: MyWindow) = window.show()   proc wMove(button: Button; window: MyWindow) = var x, y: int window.getPosition(x, y) if window.isShifted: window.move(x - 10, y - 10) else: window.move(x + 10, y + 10) window.isShifted = not window.isShifted   proc wQuit(button: Button; window: MyWindow) = window.destroy()   #---------------------------------------------------------------------------------------------------   proc activate(app: Application) = ## Activate the application.   let window = newApplicationWindow(MyWindow, app) window.setTitle("Window management")   let stackBox = newBox(Orientation.vertical, 10) stackBox.setHomogeneous(true)   let bMax = newButton("maximize") bUnmax = newButton("unmaximize") bIcon = newButton("iconize") bDeicon = newButton("deiconize") bHide = newButton("hide") bShow = newButton("show") bMove = newButton("move") bQuit = newButton("Quit")   for button in [bMax, bUnmax, bIcon, bDeicon, bHide, bShow, bMove, bQuit]: stackBox.add button   window.setBorderWidth(5) window.add(stackBox)   discard bMax.connect("clicked", wMaximize, window) discard bUnmax.connect("clicked", wUnmaximize, window) discard bIcon.connect("clicked", wIconify, window) discard bDeicon.connect("clicked", wDeiconify, window) discard bHide.connect("clicked", wHide, window) discard bShow.connect("clicked", wShow, window) discard bMove.connect("clicked", wMove, window) discard bQuit.connect("clicked", wQuit, window)   window.showAll()   #———————————————————————————————————————————————————————————————————————————————————————————————————   let app = newApplication(Application, "Rosetta.Window.Management") discard app.connect("activate", activate) discard app.run()
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.
#Oz
Oz
declare [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}   %% The messages that can be sent to the windows. WindowActions = [hide show close iconify deiconify maximize restore set(minsize:minsize(width:400 height:400)) set(minsize:minsize(width:200 height:200)) set(geometry:geometry(x:0 y:0)) set(geometry:geometry(x:500 y:500)) ]   %% Two windows, still uninitialized. Windows = windows(window1:_ window2:_)   fun {CreateWindow} Message = {NewCell WindowActions.1} ReceiverName = {NewCell {Arity Windows}.1} fun {ButtonText} "Send"#" "#{ValueToString @Message}#" to "#@ReceiverName end Button Desc = td(title:"Window Management" lr(listbox(init:{Arity Windows} glue:nswe tdscrollbar:true actionh:proc {$ W} ReceiverName := {GetSelected W} {Button set(text:{ButtonText})} end ) listbox(init:{Map WindowActions ValueToString} glue:nswe tdscrollbar:true actionh:proc {$ A} Message := {GetSelected A} {Button set(text:{ButtonText})} end ) glue:nswe ) button(text:{ButtonText} glue:we handle:Button action:proc {$} {Windows.@ReceiverName @Message} end ) ) Window = {Extend {QTk.build Desc}} in {Window show} Window end   %% Adds two methods to a toplevel instance. %% For maximize and restore we have to interact directly with Tk %% because that functionality is not part of the QTk library. fun {Extend Toplevel} proc {$ A} case A of maximize then {Tk.send wm(state Toplevel zoomed)} [] restore then {Tk.send wm(state Toplevel normal)} else {Toplevel A} end end end   %% Returns the current entry of a listbox %% as an Oz value. fun {GetSelected LB} Entries = {LB get($)} Index = {LB get(firstselection:$)} in {Compiler.virtualStringToValue {Nth Entries Index}} end   fun {ValueToString V} {Value.toVirtualString V 100 100} end in {Record.forAll Windows CreateWindow}
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
#APL
APL
  ⍝⍝ NOTE: input text is assumed to be encoded in ISO-8859-1 ⍝⍝ (The suggested example '135-0.txt' of Les Miserables on ⍝⍝ Project Gutenberg is in UTF-8.) ⍝⍝ ⍝⍝ Use Unix 'iconv' if required ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝ ∇r ← lowerAndStrip s;stripped;mixedCase ⍝⍝ Convert text to lowercase, punctuation and newlines to spaces stripped ← ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz*' mixedCase ← ⎕av[11],' ,.?!;:"''()[]-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' r ← stripped[mixedCase ⍳ s] ∇   ⍝⍝ Return the _n_ most frequent words and a count of their occurrences ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝ ∇r ← n wordCount fname ;D;wl;sidx;swv;pv;wc;uw;sortOrder D ← lowerAndStrip (⎕fio['read_file'] fname) ⍝ raw text with newlines wl ← (~ D ∊ ' ') ⊂ D sidx ← ⍒wl swv ← wl[sidx] pv ← +\ 1,~2 ≡/ swv wc ← ∊ ⍴¨ pv ⊂ pv uw ← 1 ⊃¨ pv ⊂ swv sortOrder ← ⍒wc r ← n↑[2] uw[sortOrder],[0.5]wc[sortOrder] ∇   5 wordCount '135-0.txt' the of and a to 41042 19952 14938 14526 13942  
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
#AppleScript
AppleScript
(* For simplicity here, words are considered to be uninterrupted sequences of letters and/or digits. The set text is too messy to warrant faffing around with anything more sophisticated. The first letter in each word is upper-cased and the rest lower-cased for case equivalence and presentation. Where more than n words qualify for the top n or fewer places, all are included in the result. *)   use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation" use scripting additions   on wordFrequency(filePath, n) set |⌘| to current application   -- Get the text and "capitalize" it (lower-case except for the first letters in words). set theText to |⌘|'s class "NSString"'s stringWithContentsOfFile:(filePath) usedEncoding:(missing value) |error|:(missing value) set theText to theText's capitalizedStringWithLocale:(|⌘|'s class "NSLocale"'s currentLocale()) -- Yosemite compatible. -- Split it at the non-word characters. set nonWordCharacters to |⌘|'s class "NSCharacterSet"'s alphanumericCharacterSet()'s invertedSet() set theWords to theText's componentsSeparatedByCharactersInSet:(nonWordCharacters)   -- Use a counted set to count the individual words' occurrences. set countedSet to |⌘|'s class "NSCountedSet"'s alloc()'s initWithArray:(theWords)   -- Build a list of word/frequency records, excluding any empty strings left over from the splitting above. set mutableSet to |⌘|'s class "NSMutableSet"'s setWithSet:(countedSet) tell mutableSet to removeObject:("") script o property discreteWords : mutableSet's allObjects() as list property wordsAndFrequencies : {} end script set discreteWordCount to (count o's discreteWords) repeat with i from 1 to discreteWordCount set thisWord to item i of o's discreteWords set end of o's wordsAndFrequencies to {thisWord:thisWord, frequency:(countedSet's countForObject:(thisWord)) as integer} end repeat   -- Convert to NSMutableArray, reverse-sort the result on the frequencies, and convert back to list. set wordsAndFrequencies to |⌘|'s class "NSMutableArray"'s arrayWithArray:(o's wordsAndFrequencies) set descendingByFrequency to |⌘|'s class "NSSortDescriptor"'s sortDescriptorWithKey:("frequency") ascending:(false) tell wordsAndFrequencies to sortUsingDescriptors:({descendingByFrequency}) set o's wordsAndFrequencies to wordsAndFrequencies as list   if (discreteWordCount > n) then -- If there are more than n records, check for any immediately following the nth which may have the same frequency as it. set nthHighestFrequency to frequency of item n of o's wordsAndFrequencies set qualifierCount to n repeat with i from (n + 1) to discreteWordCount if (frequency of item i of o's wordsAndFrequencies = nthHighestFrequency) then set qualifierCount to i else exit repeat end if end repeat else -- Otherwise reduce n to the actual number of discrete words. set n to discreteWordCount set qualifierCount to discreteWordCount end if   -- Compose a text report from the qualifying words and frequencies. if (qualifierCount = n) then set output to {"The " & n & " most frequently occurring words in the file are:"} else set output to {(qualifierCount as text) & " words share the " & ((n as text) & " highest frequencies in the file:")} end if repeat with i from 1 to qualifierCount set {thisWord:thisWord, frequency:frequency} to item i of o's wordsAndFrequencies set end of output to thisWord & ": " & (tab & frequency) end repeat set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid   return output end wordFrequency   -- Test code: set filePath to POSIX path of ((path to desktop as text) & "www.rosettacode.org:Word frequency:135-0.txt") set n to 10 return wordFrequency(filePath, n)
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#BBC_BASIC
BBC BASIC
Size% = 20 DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1)   VDU 23,22,Size%*8;Size%*8;64,64,16,0 OFF   DATA "tH........." DATA ". . " DATA " ... " DATA ". . " DATA "Ht.. ......"   FOR Y% = 12 TO 8 STEP -1 READ A$ FOR X% = 1 TO LEN(A$) P&(X%+4, Y%) = ASCMID$(A$, X%, 1) AND 15 NEXT NEXT Y%   COLOUR 8,0,0,255 : REM Electron head = blue COLOUR 4,255,0,0 : REM Electron tail = red COLOUR 14,255,200,0 : REM Conductor orange   REPEAT FOR Y% = 1 TO Size%-2 FOR X% = 1 TO Size%-2 IF P&(X%,Y%)<>Q&(X%,Y%) GCOL P&(X%,Y%) : PLOT X%*16, Y%*16 CASE P&(X%,Y%) OF WHEN 0: Q&(X%,Y%) = 0 WHEN 8: Q&(X%,Y%) = 4 WHEN 4: Q&(X%,Y%) = 14 WHEN 14: T% = (P&(X%+1,Y%)=8) + (P&(X%+1,Y%+1)=8) + (P&(X%+1,Y%-1)=8) + \ \ (P&(X%-1,Y%)=8) + (P&(X%-1,Y%+1)=8) + (P&(X%-1,Y%-1)=8) + \ \ (P&(X%,Y%-1)=8) + (P&(X%,Y%+1)=8) IF T%=-1 OR T%=-2 THEN Q&(X%,Y%) = 8 ELSE Q&(X%,Y%) = 14 ENDCASE NEXT NEXT Y% SWAP P&(), Q&() WAIT 50 UNTIL FALSE
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
C
/* 2009-09-27 <[email protected]> */ #define ANIMATE_VT100_POSIX #include <stdio.h> #include <string.h> #ifdef ANIMATE_VT100_POSIX #include <time.h> #endif   char world_7x14[2][512] = { { "+-----------+\n" "|tH.........|\n" "|. . |\n" "| ... |\n" "|. . |\n" "|Ht.. ......|\n" "+-----------+\n" } };   void next_world(const char *in, char *out, int w, int h) { int i;   for (i = 0; i < w*h; i++) { switch (in[i]) { case ' ': out[i] = ' '; break; case 't': out[i] = '.'; break; case 'H': out[i] = 't'; break; case '.': { int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + (in[i-1] == 'H') + (in[i+1] == 'H') + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; break; } default: out[i] = in[i]; } } out[i] = in[i]; }   int main() { int f;   for (f = 0; ; f = 1 - f) { puts(world_7x14[f]); next_world(world_7x14[f], world_7x14[1-f], 14, 7); #ifdef ANIMATE_VT100_POSIX printf("\x1b[%dA", 8); printf("\x1b[%dD", 14); { static const struct timespec ts = { 0, 100000000 }; nanosleep(&ts, 0); } #endif }   return 0; }
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
#F.23
F#
  // Weiferich primes: Nigel Galloway. June 2nd., 2021 primes32()|>Seq.takeWhile((>)5000)|>Seq.filter(fun n->(2I**(n-1)-1I)%(bigint(n*n))=0I)|>Seq.iter(printfn "%d")  
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
#Factor
Factor
USING: io kernel math math.functions math.primes prettyprint sequences ;   "Wieferich primes less than 5000:" print 5000 primes-upto [ [ 1 - 2^ 1 - ] [ sq divisor? ] bi ] filter .
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
#fermat
fermat
  Func Iswief(p)=Isprime(p)*Divides(p^2, 2^(p-1)-1). for i=2 to 5000 do if Iswief(i) then !!i fi od  
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
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : notprime! ( n -- ) here + 1 swap c! ;   : prime_sieve { n -- } here n erase 0 notprime! 1 notprime! n 4 > if n 4 do i notprime! 2 +loop then 3 begin dup dup * n < while dup prime? if n over dup * do i notprime! dup 2* +loop then 2 + repeat drop ;   : modpow { c b a -- a^b mod c } c 1 = if 0 exit then 1 a c mod to a begin b 0> while b 1 and 1 = if a * c mod then a a * c mod to a b 2/ to b repeat ;   : wieferich_prime? { p -- ? } p prime? if p p * p 1- 2 modpow 1 = else false then ;   : wieferich_primes { n -- } ." Wieferich primes less than " n 1 .r ." :" cr n prime_sieve n 0 do i wieferich_prime? if i 1 .r cr then loop ;   5000 wieferich_primes bye
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.
#Java
Java
javac WindowExample.java
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.
#Julia
Julia
  using Xlib   function x11demo() # Open connection to the server. dpy = XOpenDisplay(C_NULL) dpy == C_NULL && error("unable to open display") scr = DefaultScreen(dpy)   # Create a window. win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr), 10, 10, 300, 100, 1, BlackPixel(dpy, scr), WhitePixel(dpy, scr))   # Select the kind of events we are interested in. XSelectInput(dpy, win, ExposureMask | KeyPressMask)   # Show or in x11 terms map window. XMapWindow(dpy, win)   # Run event loop. evt = Ref(XEvent()) while true XNextEvent(dpy, evt)   # Draw or redraw the window. if EventType(evt) == Expose XFillRectangle(dpy, win, DefaultGC(dpy, scr), 24, 24, 16, 16) XDrawString(dpy, win, DefaultGC(dpy, scr), 50, 50, "Hello, World! Press any key to exit.") end   # Exit whenever a key is pressed. if EventType(evt) == KeyPress break end end   # Shutdown server connection XCloseDisplay(dpy) end   x11demo()  
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.
#Kotlin
Kotlin
// Kotlin Native v0.3   import kotlinx.cinterop.* import Xlib.*   fun main(args: Array<String>) { val msg = "Hello, World!" val d = XOpenDisplay(null) if (d == null) { println("Cannot open display") return }   val s = XDefaultScreen(d) val w = XCreateSimpleWindow(d, XRootWindow(d, s), 10, 10, 160, 160, 1, XBlackPixel(d, s), XWhitePixel(d, s)) XSelectInput(d, w, ExposureMask or KeyPressMask) XMapWindow(d, w) val e = nativeHeap.alloc<XEvent>()   while (true) { XNextEvent(d, e.ptr) if (e.type == Expose) { XFillRectangle(d, w, XDefaultGC(d, s), 55, 40, 50, 50) XDrawString(d, w, XDefaultGC(d, s), 45, 120, msg, msg.length) } else if (e.type == KeyPress) break }   XCloseDisplay(d) nativeHeap.free(e) }
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
#Racket
Racket
#lang racket   (require math/number-theory)   (define ((wilson-prime? n) p) (and (>= p n) (prime? p) (divides? (sqr p) (- (* (factorial (- n 1)) (factorial (- p n))) (expt -1 n)))))   (define primes<11000 (filter prime? (range 1 11000)))   (for ((n (in-range 1 (add1 11)))) (printf "~a: ~a~%" n (filter (wilson-prime? n) primes<11000)))
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
#Raku
Raku
# Factorial sub postfix:<!> (Int $n) { (constant f = 1, |[\×] 1..*)[$n] }   # Invisible times sub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };   # Prime the iterator for thread safety sink 11000!;   my @primes = ^1.1e4 .grep: *.is-prime;   say ' n: Wilson primes ────────────────────';   .say for (1..40).hyper(:1batch).map: -> \𝒏 { sprintf "%3d: %s", 𝒏, @primes.grep( -> \𝒑 { (𝒑 ≥ 𝒏) && ((𝒏 - 1)!⁢(𝒑 - 𝒏)! - (-1) ** 𝒏) %% 𝒑² } ).Str }
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.
#Common_Lisp
Common Lisp
(capi:display (make-instance 'capi:interface :title "A Window"))
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.
#D
D
module Window;   import fltk4d.all;   void main() { auto window = new Window(300, 300, "A window"); window.show; FLTK.run; }
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
#QB64
QB64
OPTION _EXPLICIT _TITLE "Puzzle Builder for Rosetta" 'by B+ started 2018-10-31 ' 2018-11-02 Now that puzzle is working with basic and plus starters remove them and make sure puzzle works as well. ' Added Direction legend to printout. ' OverHauled LengthLimit() ' Reorgnize this to try a couple of times at given Randomize number ' TODO create alphabetical copy of word list and check grid for all words embedded in it. ' LoadWords makes a copy of word list in alpha order ' FindAllWords finds all the items from the dictionary ' OK it all seems to be working OK   RANDOMIZE TIMER ' OK getting a good puzzle every time   'overhauled DIM SHARED LengthLimit(3 TO 10) AS _BYTE 'reset in Initialize, track and limit longer words   'LoadWords opens file of words and sets DIM SHARED NWORDS 'set in LoadWords, number of words with length: > 2 and < 11 and just letters   ' word file words (shuffled) to be fit into puzzle and index position DIM SHARED WORDS$(1 TO 24945), CWORDS$(1 TO 24945), WORDSINDEX AS INTEGER 'the file has 24945 words but many are unsuitable   'words placed in Letters grid, word itself (W$) x, y head (WX, WY) and direction (WD), WI is the index to all these DIM SHARED W$(1 TO 100), WX(1 TO 100) AS _BYTE, WY(1 TO 100) AS _BYTE, WD(1 TO 100) AS _BYTE, WI AS _BYTE   ' letters grid and direction arrays DIM SHARED L$(0 TO 9, 0 TO 9), DX(0 TO 7) AS _BYTE, DY(0 TO 7) AS _BYTE DX(0) = 1: DY(0) = 0 DX(1) = 1: DY(1) = 1 DX(2) = 0: DY(2) = 1 DX(3) = -1: DY(3) = 1 DX(4) = -1: DY(4) = 0 DX(5) = -1: DY(5) = -1 DX(6) = 0: DY(6) = -1 DX(7) = 1: DY(7) = -1   'to store all the words found embedded in the grid L$() DIM SHARED ALL$(1 TO 200), AllX(1 TO 200) AS _BYTE, AllY(1 TO 200) AS _BYTE, AllD(1 TO 200) AS _BYTE 'to store all the words found embedded in the grid L$() DIM SHARED ALLindex AS INTEGER   ' signal successful fill of puzzle DIM SHARED FILLED AS _BIT FILLED = 0 DIM try AS _BYTE try = 1 LoadWords 'this sets NWORDS count to work with WHILE try < 11 Initialize ShowPuzzle FOR WORDSINDEX = 1 TO NWORDS PlaceWord ShowPuzzle IF FILLED THEN EXIT FOR NEXT IF FILLED AND WI > 24 THEN FindAllWords FilePuzzle LOCATE 23, 1: PRINT "On try #"; Trm$(try); " a successful puzzle was built and filed." EXIT WHILE ELSE try = try + 1 END IF WEND IF FILLED = 0 THEN LOCATE 23, 1: PRINT "Sorry, 10 tries and no success." END   SUB LoadWords DIM wd$, i AS INTEGER, m AS INTEGER, ok AS _BIT OPEN "unixdict.txt" FOR INPUT AS #1 WHILE EOF(1) = 0 INPUT #1, wd$ IF LEN(wd$) > 2 AND LEN(wd$) < 11 THEN ok = -1 FOR m = 1 TO LEN(wd$) IF ASC(wd$, m) < 97 OR ASC(wd$, m) > 122 THEN ok = 0: EXIT FOR NEXT IF ok THEN i = i + 1: WORDS$(i) = wd$: CWORDS$(i) = wd$ END IF WEND CLOSE #1 NWORDS = i END SUB   SUB Shuffle DIM i AS INTEGER, r AS INTEGER FOR i = NWORDS TO 2 STEP -1 r = INT(RND * i) + 1 SWAP WORDS$(i), WORDS$(r) NEXT END SUB   SUB Initialize DIM r AS _BYTE, c AS _BYTE, x AS _BYTE, y AS _BYTE, d AS _BYTE, wd$ FOR r = 0 TO 9 FOR c = 0 TO 9 L$(c, r) = " " NEXT NEXT   'reset word arrays by resetting the word index back to zero WI = 0   'fun stuff for me but doubt others would like that much fun! 'pluggin "basic", 0, 0, 2 'pluggin "plus", 1, 0, 0   'to assure the spreading of ROSETTA CODE L$(INT(RND * 5) + 5, 0) = "R": L$(INT(RND * 9) + 1, 1) = "O" L$(INT(RND * 9) + 1, 2) = "S": L$(INT(RND * 9) + 1, 3) = "E" L$(1, 4) = "T": L$(9, 4) = "T": L$(INT(10 * RND), 5) = "A" L$(INT(10 * RND), 6) = "C": L$(INT(10 * RND), 7) = "O" L$(INT(10 * RND), 8) = "D": L$(INT(10 * RND), 9) = "E"   'reset limits LengthLimit(3) = 200 LengthLimit(4) = 6 LengthLimit(5) = 3 LengthLimit(6) = 2 LengthLimit(7) = 1 LengthLimit(8) = 0 LengthLimit(9) = 0 LengthLimit(10) = 0   'reset word order Shuffle END SUB   'for fun plug-in of words SUB pluggin (wd$, x AS INTEGER, y AS INTEGER, d AS INTEGER) DIM i AS _BYTE FOR i = 0 TO LEN(wd$) - 1 L$(x + i * DX(d), y + i * DY(d)) = MID$(wd$, i + 1, 1) NEXT WI = WI + 1 W$(WI) = wd$: WX(WI) = x: WY(WI) = y: WD(WI) = d END SUB   FUNCTION Trm$ (n AS INTEGER) Trm$ = RTRIM$(LTRIM$(STR$(n))) END FUNCTION   SUB ShowPuzzle DIM i AS _BYTE, x AS _BYTE, y AS _BYTE, wate$ CLS PRINT " 0 1 2 3 4 5 6 7 8 9" LOCATE 3, 1 FOR i = 0 TO 9 PRINT Trm$(i) NEXT FOR y = 0 TO 9 FOR x = 0 TO 9 LOCATE y + 3, 2 * x + 5: PRINT L$(x, y) NEXT NEXT FOR i = 1 TO WI IF i < 20 THEN LOCATE i + 1, 30: PRINT Trm$(i); " "; W$(i) ELSEIF i < 40 THEN LOCATE i - 20 + 1, 45: PRINT Trm$(i); " "; W$(i) ELSEIF i < 60 THEN LOCATE i - 40 + 1, 60: PRINT Trm$(i); " "; W$(i) END IF NEXT LOCATE 18, 1: PRINT "Spaces left:"; CountSpaces% LOCATE 19, 1: PRINT NWORDS LOCATE 20, 1: PRINT SPACE$(16) IF WORDSINDEX THEN LOCATE 20, 1: PRINT Trm$(WORDSINDEX); " "; WORDS$(WORDSINDEX) 'LOCATE 15, 1: INPUT "OK, press enter... "; wate$ END SUB   'used in PlaceWord FUNCTION CountSpaces% () DIM x AS _BYTE, y AS _BYTE, count AS INTEGER FOR y = 0 TO 9 FOR x = 0 TO 9 IF L$(x, y) = " " THEN count = count + 1 NEXT NEXT CountSpaces% = count END FUNCTION   'used in PlaceWord FUNCTION Match% (word AS STRING, template AS STRING) DIM i AS INTEGER, c AS STRING Match% = 0 IF LEN(word) <> LEN(template) THEN EXIT FUNCTION FOR i = 1 TO LEN(template) IF ASC(template, i) <> 32 AND (ASC(word, i) <> ASC(template, i)) THEN EXIT FUNCTION NEXT Match% = -1 END FUNCTION   'heart of puzzle builder SUB PlaceWord ' place the words randomly in the grid ' start at random spot and work forward or back 100 times = all the squares ' for each open square try the 8 directions for placing the word ' even if word fits Rossetta Challenge task requires leaving 11 openings to insert ROSETTA CODE, ' exactly 11 spaces needs to be left, if/when this occurs FILLED will be set true to signal finished to main loop ' if place a word update L$, WI, W$(WI), WX(WI), WY(WI), WD(WI)   DIM wd$, wLen AS _BYTE, spot AS _BYTE, testNum AS _BYTE, rdir AS _BYTE DIM x AS _BYTE, y AS _BYTE, d AS _BYTE, dNum AS _BYTE, rdd AS _BYTE DIM template$, b1 AS _BIT, b2 AS _BIT DIM i AS _BYTE, j AS _BYTE, wate$   wd$ = WORDS$(WORDSINDEX) 'the right side is all shared 'skip too many long words IF LengthLimit(LEN(wd$)) THEN LengthLimit(LEN(wd$)) = LengthLimit(LEN(wd$)) - 1 ELSE EXIT SUB 'skip long ones wLen = LEN(wd$) - 1 ' from the spot there are this many letters to check spot = INT(RND * 100) ' a random spot on grid testNum = 1 ' when this hits 100 we've tested all possible spots on grid IF RND < .5 THEN rdir = -1 ELSE rdir = 1 ' go forward or back from spot for next test WHILE testNum < 101 y = INT(spot / 10) x = spot MOD 10 IF L$(x, y) = MID$(wd$, 1, 1) OR L$(x, y) = " " THEN d = INT(8 * RND) IF RND < .5 THEN rdd = -1 ELSE rdd = 1 dNum = 1 WHILE dNum < 9 'will wd$ fit? from at x, y template$ = "" b1 = wLen * DX(d) + x >= 0 AND wLen * DX(d) + x <= 9 b2 = wLen * DY(d) + y >= 0 AND wLen * DY(d) + y <= 9 IF b1 AND b2 THEN 'build the template of letters and spaces from Letter grid FOR i = 0 TO wLen template$ = template$ + L$(x + i * DX(d), y + i * DY(d)) NEXT IF Match%(wd$, template$) THEN 'the word will fit but does it fill anything? FOR j = 1 TO LEN(template$) IF ASC(template$, j) = 32 THEN 'yes a space to fill FOR i = 0 TO wLen L$(x + i * DX(d), y + i * DY(d)) = MID$(wd$, i + 1, 1) NEXT WI = WI + 1 W$(WI) = wd$: WX(WI) = x: WY(WI) = y: WD(WI) = d IF CountSpaces% = 0 THEN FILLED = -1 EXIT SUB 'get out now that word is loaded END IF NEXT 'if still here keep looking END IF END IF d = (d + 8 + rdd) MOD 8 dNum = dNum + 1 WEND END IF spot = (spot + 100 + rdir) MOD 100 testNum = testNum + 1 WEND END SUB   SUB FindAllWords DIM wd$, wLen AS _BYTE, i AS INTEGER, x AS _BYTE, y AS _BYTE, d AS _BYTE DIM template$, b1 AS _BIT, b2 AS _BIT, j AS _BYTE, wate$   FOR i = 1 TO NWORDS wd$ = CWORDS$(i) wLen = LEN(wd$) - 1 FOR y = 0 TO 9 FOR x = 0 TO 9 IF L$(x, y) = MID$(wd$, 1, 1) THEN FOR d = 0 TO 7 b1 = wLen * DX(d) + x >= 0 AND wLen * DX(d) + x <= 9 b2 = wLen * DY(d) + y >= 0 AND wLen * DY(d) + y <= 9 IF b1 AND b2 THEN 'build the template of letters and spaces from Letter grid template$ = "" FOR j = 0 TO wLen template$ = template$ + L$(x + j * DX(d), y + j * DY(d)) NEXT IF template$ = wd$ THEN 'founda word 'store it ALLindex = ALLindex + 1 ALL$(ALLindex) = wd$: AllX(ALLindex) = x: AllY(ALLindex) = y: AllD(ALLindex) = d 'report it LOCATE 22, 1: PRINT SPACE$(50) LOCATE 22, 1: PRINT "Found: "; wd$; " ("; Trm$(x); ", "; Trm$(y); ") >>>---> "; Trm$(d); INPUT " Press enter...", wate$ END IF END IF NEXT d END IF NEXT x NEXT y NEXT i END SUB   SUB FilePuzzle DIM i AS _BYTE, r AS _BYTE, c AS _BYTE, b$ OPEN "WS Puzzle.txt" FOR OUTPUT AS #1 PRINT #1, " 0 1 2 3 4 5 6 7 8 9" PRINT #1, "" FOR r = 0 TO 9 b$ = Trm$(r) + " " FOR c = 0 TO 9 b$ = b$ + L$(c, r) + " " NEXT PRINT #1, b$ NEXT PRINT #1, "" PRINT #1, "Directions >>>---> 0 = East, 1 = SE, 2 = South, 3 = SW, 4 = West, 5 = NW, 6 = North, 7 = NE" PRINT #1, "" PRINT #1, " These are the items from unixdict.txt used to build the puzzle:" PRINT #1, "" FOR i = 1 TO WI STEP 2 PRINT #1, RIGHT$(SPACE$(7) + Trm$(i), 7); ") "; RIGHT$(SPACE$(7) + W$(i), 10); " ("; Trm$(WX(i)); ", "; Trm$(WY(i)); ") >>>---> "; Trm$(WD(i)); IF i + 1 <= WI THEN PRINT #1, RIGHT$(SPACE$(7) + Trm$(i + 1), 7); ") "; RIGHT$(SPACE$(7) + W$(i + 1), 10); " ("; Trm$(WX(i + 1)); ", "; Trm$(WY(i + 1)); ") >>>---> "; Trm$(WD(i + 1)) ELSE PRINT #1, "" END IF NEXT PRINT #1, "" PRINT #1, " These are the items from unixdict.txt found embedded in the puzzle:" PRINT #1, "" FOR i = 1 TO ALLindex STEP 2 PRINT #1, RIGHT$(SPACE$(7) + Trm$(i), 7); ") "; RIGHT$(SPACE$(7) + ALL$(i), 10); " ("; Trm$(AllX(i)); ", "; Trm$(AllY(i)); ") >>>---> "; Trm$(AllD(i)); IF i + 1 <= ALLindex THEN PRINT #1, RIGHT$(SPACE$(7) + Trm$(i + 1), 7); ") "; RIGHT$(SPACE$(7) + ALL$(i + 1), 10); " ("; Trm$(AllX(i + 1)); ", "; Trm$(AllY(i + 1)); ") >>>---> "; Trm$(AllD(i + 1)) ELSE PRINT #1, "" END IF NEXT CLOSE #1 END SUB
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
#Common_Lisp
Common Lisp
;; Greedy wrap line   (defun greedy-wrap (str width) (setq str (concatenate 'string str " ")) ; add sentinel (do* ((len (length str)) (lines nil) (begin-curr-line 0) (prev-space 0 pos-space) (pos-space (position #\Space str) (when (< (1+ prev-space) len) (position #\Space str :start (1+ prev-space)))) ) ((null pos-space) (progn (push (subseq str begin-curr-line (1- len)) lines) (nreverse lines)) ) (when (> (- pos-space begin-curr-line) width) (push (subseq str begin-curr-line prev-space) lines) (setq begin-curr-line (1+ prev-space)) )))  
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
#Python
Python
import urllib.request from collections import Counter     GRID = """ N D E O K G E L W """     def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): "Return lowercased words of 3 to 9 characters" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10)   def solve(grid, dictionary): gridcount = Counter(grid) mid = grid[4] return [word for word in dictionary if mid in word and not (Counter(word) - gridcount)]     if __name__ == '__main__': chars = ''.join(GRID.strip().lower().split()) found = solve(chars, dictionary=getwords()) print('\n'.join(found))
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
#q
q
ce:count each lc:ce group@ / letter count dict:"\n"vs .Q.hg "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" // dictionary of 3-9 letter words d39:{x where(ce x)within 3 9}{x where all each x in .Q.a}dict   solve:{[grid;dict] i:where(grid 4)in'dict; dict i where all each 0<=(lc grid)-/:lc each dict i }[;d39]